If your engineering team is still pushing nightly evaluation runs, multi-million-row dataset tagging, or offline document extraction through synchronous Claude API calls, you are paying a massive latency tax for a service level you do not need. Worse, you are burning 50% of your LLM budget on real-time execution overhead while fighting concurrency rate limits (429 Too Many Requests).
At 365Finds, our stance is unequivocal: any Claude workload that can tolerate an execution window between 15 minutes and 24 hours belongs on the Claude Message Batches API. Anthropic cuts both input and output token prices by exactly 50% across every supported model in the batch queue. Furthermore, batched workloads operate on dedicated throughput pools, freeing your synchronous rate limits for production traffic that directly faces human end-users.
Yet, halving your token invoice is not free money. Asynchronous architectures introduce distributed state complexity. Results return out of order. Input parameter errors are caught asynchronously hours after submission. And if your team does not handle partial failures with structured idempotency keys, you will spend your cost savings debugging corrupt pipelines. Here is how modern backend teams architect, execute, and safeguard production pipelines with the Claude Message Batches API.
The Economic and Operational Trade-Off
The primary driver for the Message Batches API is financial, but its operational decoupling is what keeps production systems resilient. When making standard synchronous calls to /v1/messages, you pay full price for sub-second execution guarantees. In contrast, the Batches API queues your requests and processes them against spare platform compute capacity over an SLA of up to 24 hours.
The Pricing Math
Across Claude models, the 50% discount applies across both prompt tokens and generation tokens:
| Model Tier | Synchronous Input (per MTok) | Batch Input (per MTok) | Synchronous Output (per MTok) | Batch Output (per MTok) | Effective Savings |
|---|---|---|---|---|---|
| Claude Sonnet (Standard Tier) | $3.00 | $1.50 | $15.00 | $7.50 | 50% |
| Claude Haiku (Standard Tier) | $1.00 | $0.50 | $5.00 | $2.50 | 50% |
| Claude Opus (Premium Tier) | $5.00 | $2.50 | $25.00 | $12.50 | 50% |
365Finds highlights an additional billing advantage that teams frequently overlook: Anthropic does not bill for requests that end in errored, canceled, or expired. If 200 items in a 10,000-request batch encounter platform timeouts or validation exceptions, your account is charged precisely zero tokens for those failed attempts.
Batch Limits and Service Boundaries
Before refactoring your backend pipelines, you must align with the operational limits defined by Anthropic:
- Batch Size: Up to 100,000 Message requests or 256 MB per single batch creation call, whichever limit is reached first.
- SLA Window: Anthropic guarantees results within 24 hours. Batches that remain incomplete at the 24-hour mark expire automatically. In practice, 365Finds observes that standard batches under 5,000 requests complete within 15 to 45 minutes during typical off-peak windows.
- Result Retention: Processed batch results remain accessible via download URL or SDK streaming for 29 days post-creation.
- Parameter Restrictions: You cannot pass
stream: true(batch responses are compiled into static result files),fallbacks, orspeed: fast. Crucially,max_tokensmust be at least1. Settingmax_tokens: 0for prompt cache pre-warming is rejected, as ephemeral cache writes during asynchronous execution would expire before downstream processing.
Architectural Deep Dive: The End-to-End Pipeline
Moving from synchronous request-response loops to a batch pipeline requires a five-stage architecture:
[ Data Source / DB ]
│
▼
[ Stage 1: Request Packaging & custom_id Hashing ]
│
▼
[ Stage 2: Batch Submission (POST /v1/messages/batches) ]
│
▼
[ Stage 3: Low-Frequency Polling / Worker Loop ]
│
▼
[ Stage 4: Result Streaming & Status Demuxing ]
├── succeeded ──► Write to Data Warehouse / DB
├── errored (4xx) ──► Dead-Letter Queue (DLQ)
├── errored (5xx) ──► Retry Manifest
└── expired ──────► Resubmit Pipeline
1. Constructing the Batch Request with custom_id
In a batch workload, individual requests are executed concurrently and returned out of order. If you send request A, B, and C, the results stream may return C, A, and then B.
The only bridge between your internal database records and the model output is the custom_id. Anthropic strictly enforces the format:
- Must be between 1 and 64 characters long.
- Allowed characters: alphanumeric (
a-z,A-Z,0-9), hyphens (-), and underscores (_). Regex:^[a-zA-Z0-9_-]{1,64}$. - Must be unique within the submitted batch.
365Finds strongly advises against using sequential counters like req-1 or req-2. Instead, use deterministic, structured composite keys:
import hashlib
def generate_custom_id(entity_type: str, entity_id: str, prompt_version: str) -> str:
"""Generate a collision-resistant, traceable custom_id for Claude batches."""
raw = f"{entity_type}:{entity_id}:{prompt_version}"
digest = hashlib.sha256(raw.encode()).hexdigest()[:16]
return f"{entity_type}_{digest}"
2. Batch Creation via SDK
Here is how to structure and submit a production batch using the official Anthropic Python SDK:
import anthropic
from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
from anthropic.types.messages.batch_create_params import Request
client = anthropic.Anthropic()
workload_items = [
{"doc_id": "legal_84920", "content": "Full contractual agreement text..."},
{"doc_id": "legal_84921", "content": "Termination clause addendum text..."},
]
batch_requests = []
for item in workload_items:
batch_requests.append(
Request(
custom_id=f"doc_{item['doc_id']}",
params=MessageCreateParamsNonStreaming(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
system="You are an enterprise compliance auditor. Extract all indemnification liabilities.",
messages=[
{"role": "user", "content": item["content"]}
],
),
)
)
batch = client.messages.batches.create(requests=batch_requests)
print(f"Batch created with ID: {batch.id}")
print(f"Initial Status: {batch.processing_status}")
Polling and Lifecycle Management
A rookie mistake 365Finds frequently sees is treating batch endpoints like synchronous polling sockets, querying every two seconds. This risks exhausting your HTTP rate limit on the control plane.
When a batch is submitted, it enters in_progress. You can track high-level progress using batch.request_counts:
processing: Count of items currently in flight.succeeded: Completed inference runs.errored: Items failing runtime validation or internal compute.canceled: Requests aborted before execution.expired: Requests that hit the 24-hour ceiling.
Recommended Polling Worker
Implement a conservative polling loop with a fixed interval (e.g., 60 seconds) or delegate the check to a background job scheduler (such as Celery, Temporal, or AWS Step Functions):
import time
import anthropic
client = anthropic.Anthropic()
def wait_for_batch_completion(batch_id: str, poll_interval_sec: int = 60):
while True:
batch = client.messages.batches.retrieve(batch_id)
status = batch.processing_status
counts = batch.request_counts
print(f"[{batch_id}] Status: {status} | Succeeded: {counts.succeeded} | Errored: {counts.errored} | Processing: {counts.processing}")
if status == "ended":
return batch
time.sleep(poll_interval_sec)
Streamed Ingestion, Error Isolation, and the Dead-Letter Queue
When processing_status reaches ended, do not download the entire payload into local memory if your batch contains tens of thousands of records. Use the streaming results endpoint, which reads .jsonl lines incrementally.
Every record in the stream contains:
custom_id: The ID you assigned.result: An object containing atypediscriminator:"succeeded","errored","canceled", or"expired".
The Asynchronous Validation Hazard
Batch creation only validates the HTTP payload envelope. Individual params objects are validated asynchronously during model invocation. If one of your prompts exceeds the model's context window or provides an unsupported temperature value, that specific request returns result.type == "errored" with an invalid_request_error. The rest of your batch continues unimpeded.
To keep your pipeline robust, your ingestion worker must bifurcate errors:
import anthropic
client = anthropic.Anthropic()
def process_batch_results(batch_id: str):
retry_manifest = []
dead_letter_queue = []
# Stream results line-by-line to preserve memory
for item in client.messages.batches.results(batch_id):
cid = item.custom_id
outcome = item.result
if outcome.type == "succeeded":
# Extract content blocks safely
assistant_text = outcome.message.content[0].text
usage = outcome.message.usage
save_to_database(cid, assistant_text, usage)
elif outcome.type == "errored":
error_data = outcome.error.error
error_type = error_data.type
error_message = error_data.message
if error_type == "invalid_request_error":
# Unrecoverable without code/data changes; send to DLQ
dead_letter_queue.append({
"custom_id": cid,
"reason": error_message,
"code": error_type
})
else:
# 5xx or transient internal error; queue for retry
retry_manifest.append(cid)
elif outcome.type == "expired":
# Never processed within 24 hours; must be resubmitted
retry_manifest.append(cid)
print(f"Ingested results. Succeeded. DLQ: {len(dead_letter_queue)}, Retries Needed: {len(retry_manifest)}")
return retry_manifest, dead_letter_queue
Stacking Prompt Caching with Message Batches
Can you combine the 50% Message Batches discount with Prompt Caching? Yes.
When processing homogeneous batches—such as evaluating 10,000 student essays against a 20-page grading rubric, or analyzing financial statements against a large corporate disclosure document—you can inject cache_control blocks into the shared system prompt or context window.
{
"custom_id": "eval-doc-001",
"params": {
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"system": [
{
"type": "text",
"text": "Analyze the following document based on the master legal guidelines below:"
},
{
"type": "text",
"text": "<insert 40,000 tokens of company policy guidelines>",
"cache_control": {"type": "ephemeral"}
}
],
"messages": [
{"role": "user", "content": "Audit Vendor Agreement Section 4"}
]
}
}
The Best-Effort Nuance
In synchronous calls, prompt caching offers deterministic cache hits as long as requests are dispatched sequentially within the 5-minute TTL. In the Message Batches API, processing is distributed across multiple internal workers. As a result, cache hit rates are non-deterministic, typically settling between 30% and 90% depending on cluster load and queue concurrency.
Even at an average 50% cache hit rate on prompt tokens, stacking Prompt Caching with the Batches API drops your effective input token cost to a quarter of standard real-time pricing. For high-volume data engineering teams, this transforms projects previously deemed cost-prohibitive into viable daily production routines.
Production Checklist & When to Walk Away
Before committing your architecture to the Batches API, 365Finds recommends verifying these core requirements:
- Verify Request Envelopes Synchronously First: Run 5 sample items through the synchronous
/v1/messagesendpoint in your staging environment before compiling a 50,000-item batch. Asynchronous validation errors in production waste hours of turnaround time. - Build an Idempotent Consumer: Because results stream out of order, write operations to your datastore must be keyed on
custom_idusingUPSERTsemantics. - Handle Dead-Letter Queues Automatically: Separate schema failures (
invalid_request_error) from transient infrastructure failures (internal_server_errorandexpired). Only resubmit transient issues. - Enforce Storage Retention Hygiene: Anthropic discards results after 29 days. Ingest, verify, and persist responses to S3, Google Cloud Storage, or your internal data warehouse immediately upon batch completion.
When NOT to Use Message Batches
Do not force the Batches API into architectures that require:
- Interactive Latency: User-facing conversational bots, interactive copilot tools, or autocomplete features.
- Sequential Dependent Steps: Agentic loops where Prompt B relies directly on the generation output of Prompt A.
- Immediate Cache Pre-warming: Workloads relying on
max_tokens: 0.
If your asynchronous workload processes 100,000 or more records daily, the engineering investment required to handle out-of-order streams and partial failures pays for itself on your first monthly Claude invoice.