Real-time API endpoints are an expensive misallocation for offline data pipelines. When data engineers and backend architects run text categorization over millions of customer transcripts, perform nightly model evaluations, or clean synthetic training datasets through synchronous Claude Messages API calls, they inevitably collide with two walls: strict concurrency rate limits (429 Too Many Requests) and full-price on-demand token billing.
At 365Finds, our commercial assessment is straightforward: sending non-latency-sensitive workloads through synchronous endpoints is an engineering anti-pattern. Anthropic's native Message Batches API cuts token expenses by exactly 50% across both input and output while routing workloads through an isolated processing pool. Understanding how to orchestrate this API—from schema construction and idempotent keying to polling and partial-failure streaming—transforms batch processing from an ad-hoc scripting headache into a hardened, high-throughput pipeline.
The Economic and Architectural Mechanics of Message Batches
The premise of the Message Batches API (POST /v1/messages/batches) is built on unbundling immediate availability from model compute. By granting Anthropic an asynchronous delivery window—up to 24 hours, though most standard batches complete in under 60 minutes—the platform schedules inference during capacity valleys. In exchange, users receive a flat 50% price reduction across all supported Claude models.
| Model Tier | Real-Time Input / Output (per MTok) | Message Batches Input / Output (per MTok) | Direct Savings |
|---|---|---|---|
| Claude Opus 5.5 | $4.00 / $20.00 | $2.00 / $10.00 | 50% |
| Claude Sonnet 5.5 | $2.00 / $10.00 | $1.00 / $5.00 | 50% |
| Claude Haiku 5.5 (≤100k prompt) | $0.10 / $0.50 | $0.05 / $0.25 | 50% |
| Claude Haiku 4.5 | $1.00 / $5.00 | $0.50 / $2.50 | 50% |
Beyond pure financial savings, the architectural gain is throughput decoupling. Message Batches do not consume your standard Messages API request-per-minute (RPM) or tokens-per-minute (TPM) limits. Instead, batches run against separate batch queue thresholds. A pipeline submitting 80,000 document extraction tasks at midnight will not starve or degrade user-facing production chatbots operating on the synchronous Messages API.
Core Constraints and Limits
To design around the Batches API effectively, engineers must account for several rigid boundaries:
- Batch Capacity: A single batch accommodates up to 100,000 individual requests or 256 MB of payload, whichever boundary is crossed first.
- Processing SLA: 24-hour execution ceiling. If processing is incomplete after 24 hours, remaining tasks are marked as
expired. - Result Availability: Batch status and downloadable output files persist for 29 days from batch creation (
created_at), after which result files are purged. - Billing Immunity: You are billed solely for requests that achieve
succeededstatus. Requests categorized aserrored,canceled, orexpiredincur $0.00 in token charges.
Constructing the Ingestion Pipeline: Custom IDs and Schema Rules
Unlike synchronous requests where HTTP connections preserve request-response affinity, batch inference processes individual records out of order. Establishing idempotency and downstream alignment demands a deterministic keying strategy via custom_id.
Anthropic enforces a strict regex for custom_id: ^[a-zA-Z0-9_-]{1,64}$. 365Finds recommends using composite surrogate keys encoding the entity type, database primary key, and pipeline execution hash (e.g., doc_v2_usr9482_b8f10a). Never use raw arbitrary text or non-deterministic counters.
Parameter Restrictions
Almost all Messages API capabilities carry over directly to batch mode—including Vision, complex system messages, multi-turn dialogue histories, server tools, and extended thinking. However, four specific parameters trigger immediate validation failures if present in a batch item:
stream: true(Batch returns consolidated newline-delimited JSON, not SSE token streams)speed(Fast mode synchronous latency tuning is invalid for asynchronous queuing)fallbacks(Server-side immediate failover does not apply to batch tasks)max_tokens: 0(Cache pre-warming is rejected inside batches because ephemeral cache keys may expire before subsequent requests execute)
import anthropic
from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
from anthropic.types.messages.batch_create_params import Request
client = anthropic.Anthropic()
# Constructing a typed, decoupled batch payload
requests_payload = [
Request(
custom_id="extract_inv_20261108_001",
params=MessageCreateParamsNonStreaming(
model="claude-sonnet-5-5",
max_tokens=1024,
system="Extract structured invoice metadata as strict JSON.",
messages=[
{"role": "user", "content": "Raw invoice payload: Invoice #1042, Total: $482.10, Vendor: Acme Corp."}
]
)
),
Request(
custom_id="extract_inv_20261108_002",
params=MessageCreateParamsNonStreaming(
model="claude-sonnet-5-5",
max_tokens=1024,
system="Extract structured invoice metadata as strict JSON.",
messages=[
{"role": "user", "content": "Raw invoice payload: Invoice #1043, Total: $1,290.00, Vendor: Stark Ltd."}
]
)
)
]
# Dispatch the batch job
batch = client.messages.batches.create(requests=requests_payload)
print(f"Batch dispatched. Batch ID: {batch.id} | Status: {batch.processing_status}")
Polling, Lifecycle States, and Memory-Safe Result Streaming
Once dispatched, a batch enters the in_progress state. Because validation of individual request bodies is performed asynchronously on Anthropic's worker fleet, a 200 OK on batches.create only guarantees that the outer envelope passed sanity checks.
Lifecycle State Machine
in_progress: The batch is queued or actively undergoing inference across model clusters.canceling: A cancellation signal (POST /v1/messages/batches/{id}/cancel) was acknowledged; workers are draining active operations.ended: Terminal state. All requests have finalized into one of the four outcome classifications.
import time
def await_batch_completion(client: anthropic.Anthropic, batch_id: str, poll_interval: int = 30):
"""
Polls the batch retrieval endpoint with exponential backoff or standard intervals.
Inspection of batch_status.request_counts provides real-time progress.
"""
while True:
status = client.messages.batches.retrieve(batch_id)
counts = status.request_counts
print(
f"Status: {status.processing_status} | "
f"Processing: {counts.processing} | "
f"Succeeded: {counts.succeeded} | "
f"Errored: {counts.errored}"
)
if status.processing_status == "ended":
return status
time.sleep(poll_interval)
Streaming JSONL Output Without OOM Spikes
When batches process 50,000 to 100,000 records, downloading the raw JSONL results payload into memory will crash standard application instances. 365Finds strongly advises against parsing results via monolithic HTTP GET buffers. Instead, use the SDK's built-in memory-efficient line iterator client.messages.batches.results(batch_id):
def process_batch_stream(client: anthropic.Anthropic, batch_id: str):
"""
Iterates through the .jsonl results stream line-by-line.
Handles success and error states defensively without holding the entire payload in RAM.
"""
for item in client.messages.batches.results(batch_id):
custom_id = item.custom_id
outcome = item.result
match outcome.type:
case "succeeded":
# Message response object matches standard Messages API structure
message = outcome.message
text_response = "".join(
block.text for block in message.content if block.type == "text"
)
input_tokens = message.usage.input_tokens
output_tokens = message.usage.output_tokens
# Persist to database using custom_id as primary lookup
commit_record(custom_id, text_response, input_tokens, output_tokens)
case "errored":
# Anthropic categorizes errors: invalid_request_error vs server_error
error_obj = outcome.error.error
if error_obj.type == "invalid_request_error":
# Non-retryable without payload alteration (e.g. prompt token overflow)
log_fatal_item(custom_id, error_obj.message)
else:
# Ephemeral 5xx backend error; enqueue for targeted single retry
enqueue_retry(custom_id, error_obj.message)
case "expired":
# Hit the 24-hour limit; not billed, must be re-batched
log_timeout_item(custom_id)
case "canceled":
log_canceled_item(custom_id)
Error Handling: Triage Between Invalid Requests and Ephemeral Failures
In high-volume batch processing, partial failure is an operational certainty. Treating an entire 50,000-item batch as failed because 12 items errored is a severe operational mistake.
When outcome.type == "errored", inspect outcome.error.error.type:
invalid_request_error: Indicates a structural or schema failure (e.g., system instructions exceeded token boundaries, unescaped bad characters, or illegal parameters). Re-submitting this item will always fail. These should be pushed to a dead-letter queue (DLQ) for engineering inspection.api_errororrate_limit_error(Internal Worker Throttle): Indicates an ephemeral platform fault within Anthropic's worker cluster. These items should be isolated and rolled into the next asynchronous batch run.- The Dry-Run Heuristic: Because Anthropic evaluates batch request bodies asynchronously, a malformed parameter syntax will only reveal itself hours later when the batch status changes to
ended. At 365Finds, our pipeline standard requires test-running a single item through the synchronousmessages.createendpoint in CI/CD pipelines before bundling production batches.
Stacking Prompt Caching and Server-Side Capabilities
A common misconception is that batching precludes prompt caching. In reality, Prompt Caching and Message Batches can be combined. When thousands of requests in a batch share an identical 10,000-token system prompt, classification rubric, or legal document, developers can mark the invariant prefix with cache_control: {"type": "ephemeral"}.
The Asynchronous Caching Caveat
Because the batch engine schedules sub-requests concurrently across disparate server nodes, cache hits in Message Batches are delivered on a best-effort basis. In production workloads, cache hit rates fluctuate between 30% and 95%.
- To optimize cache performance, set the cache duration to 1 hour rather than relying on ephemeral 5-minute defaults where long queues might experience cold misses.
- Keep the identical cache control block in exactly the same position across every item in the batch.
Server Tools and Extended Outputs
- Server Tools Execution: Batch requests fully support server tools (web search, web fetch, code execution). The batch execution worker manages the multi-iteration agentic tool loop on Anthropic's backend. If a turn runs out of allowed cycles, it yields
stop_reason: "pause_turn", allowing downstream systems to resume execution in a follow-up request. - Extended Output Beta (300k Tokens): Synchronous Messages API calls are constrained to standard maximum output token limits (typically 8k or 128k depending on configuration). Under the Message Batches API, passing the beta header
anthropic-beta: output-300k-2026-03-24allows a single batched generation to produce up to 300,000 output tokens. For deep document generation, comprehensive code scaffolding, and multi-turn synthetic data rollouts, this capability exists exclusively within the batch infrastructure.
365Finds Decision Matrix: Batch vs. Real-Time API
Engineers frequently struggle with where to draw the boundary between real-time Messages and asynchronous Batches. We recommend this architectural split:
Workload Classification Decision Tree:
│
├── User waiting in interactive session (< 5 sec SLA)?
│ └── YES ──> Synchronous Messages API (Full cost, low latency)
│
├── Hard downstream pipeline deadline < 1 hour?
│ └── YES ──> Synchronous Messages API with managed concurrency pools
│
└── Tolerant to completion within 1 - 24 hours?
└── YES ──> Anthropic Message Batches API (50% Cost Savings, Zero RPM Impact)
If an asynchronous task can accommodate a variable 15-minute to 4-hour completion window, leaving it on synchronous endpoints burns double the infrastructure budget and adds unnecessary retry handling for transient HTTP 429 errors.
Anthropic's Message Batches API provides an explicit, deterministic contract: half the cost, complete workload isolation from real-time traffic, resilient partial-failure reporting, and zero billing on unfulfilled queries. For modern AI backend engineering, adopting it is not just an optimization; it is baseline operational hygiene.