Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
Ten thousand invoices a night and a live chat reply use the same model and the same kind of prompt, but they belong on different APIs. Build a Claude message batch with a custom_id per request, read results in any order, resend only the failures and check the deadline sum.
What you will learn
- Decide between the Message Batches API and a real-time call by who is waiting and when the answer is due
- Build a batch with one custom_id per request
- Follow a batch through create, poll and read, and match results by custom_id
- Resend only the failed requests and check that a deadline fits the 24-hour window
Before you start
- The Claude Messages API: your first call
- Basic Python
Every night your company has ten thousand supplier invoices to read. Nobody sits there waiting for the answers; they only need to be ready by morning. In the same app, a customer types a question into the live chat and watches the screen.
Same model, same kind of prompt. But the two jobs belong on different APIs. The one question that decides it: who is waiting, and how soon is the answer due? How clever the prompt is doesn't come into it.
The laundry service and the dryer at home
Think about laundry. You can drop your clothes at a laundry service tonight and get them back by morning, with no promise of the exact hour. It costs less, because you're paying for waiting. Or you can use the dryer at home: press start and it's ready while you stand there, at the full price, because you're paying for speed.
A batch is the laundry service. A real-time call is the dryer at home.
Two lanes of work
The facts about the batch lane, from the Claude docs on batch processing: it costs 50% of the standard price, a batch can take up to 24 hours to finish, and there's no promise of an exact time. The real-time lane answers now at the standard price.
build_batch.py: one request per invoice
The project for this lesson is two small files in plain Python. No API key is needed: the batch is built but not sent, and the results come from a made-up sample file.
"""Build one batch request per invoice. custom_id ties each answer back."""
MODEL = "claude-sonnet-5-5"
ASK = "Extract supplier, due_date and total from this invoice."
def make_request(n, text):
return {"custom_id": f"inv-{n:04d}",
"params": {"model": MODEL, "max_tokens": 512,
"messages": [{"role": "user",
"content": f"{ASK}\n\n{text}"}]}}
def build(invoices):
return [make_request(n, t) for n, t in enumerate(invoices, 1)]
if __name__ == "__main__":
invoices = [f"Invoice text number {n}" for n in range(1, 201)]
requests = build(invoices)
print(len(requests), "requests in one batch")
for r in requests[:2]:
print(r["custom_id"], "->", r["params"]["model"])
# With a key, one call sends them all:
# batch = client.messages.batches.create(requests=requests)
# Later: client.messages.batches.results(batch.id)
200 requests in one batch
inv-0001 -> claude-sonnet-5-5
inv-0002 -> claude-sonnet-5-5
Two things to notice:
- Every request carries a
custom_id:inv-0001,inv-0002and so on. That id is how you will find this invoice's answer later. - The
paramsare the usual Messages call:model,max_tokensandmessages. If you can write a real-time call, you can write a batch request. See the Messages API, field by field.
The life cycle of a batch
- Create. One call to
client.messages.batches.createsends all the requests. The status starts asin_progressand the call returns at once. - Poll. Check the batch until its status says
ended. The docs say most batches finish within an hour, but the window is 24 hours, so plan for the window, not the typical case. - Read. Fetch the results with
client.messages.batches.results(batch.id). They don't come back in request order. Each result issucceeded,errored,canceledorexpired.
Because the order is not kept, the only safe way to tie a result to its invoice is the custom_id. Matching by position puts invoice 5's answer on invoice 1.
resubmit.py: resend only what failed
Some requests in a big batch will fail. The second file reads a sample results file (five results in a shuffled order: three succeeded, two errored), finds the failures by custom_id and plans the resend.
"""Read batch results, find the failures by custom_id, resend only those."""
import json
LONG = {"inv-0004": [f"line item {i}" for i in range(1, 91)]}
CHUNK = 30
def failures(path="results_sample.jsonl"):
bad = {}
rows = [json.loads(x) for x in open(path)]
print(len(rows), "results read")
for row in rows:
res = row["result"]
if res["type"] != "succeeded":
bad[row["custom_id"]] = res["error"]["error"]["message"]
return bad
def plan(bad):
todo = []
for cid, why in sorted(bad.items()):
if "too long" in why:
lines = LONG[cid]
for k in range(0, len(lines), CHUNK):
todo.append(f"{cid}-p{k // CHUNK + 1}")
else:
todo.append(cid)
return todo
bad = failures()
print(len(bad), "failed")
for cid, why in sorted(bad.items()):
print(" ", cid, "->", why)
print("resend only:", ", ".join(plan(bad)))
5 results read
2 failed
inv-0003 -> internal server error
inv-0004 -> prompt is too long
resend only: inv-0003, inv-0004-p1, inv-0004-p2, inv-0004-p3
Read the output line by line:
- inv-0003 hit a server error (
api_error). Nothing was wrong with the request, so it goes back exactly as it was. - inv-0004 failed with
invalid_request_error: the prompt was too long. Sending it again unchanged would fail again, so its 90 line items are split into three chunks of 30, each with its own newcustom_id(inv-0004-p1to-p3). - The three that succeeded are not sent again. Only the failures go back, so you don't pay twice for work that is already done.
This is the same rule you use for live calls: a server error can be retried, a bad request has to be fixed first. The live version is in Anthropic SDK timeouts, retries and error classes.
The deadline sum
"Can wait" needs a number. Say you promise customers their invoice results within 36 hours. These numbers are our own, just to show the sum.
- An invoice arrives just after a batch was sent, so it waits for the next one. If you send a batch every 12 hours, that wait is at most 12 hours.
- The batch itself can take up to 24 hours.
- 12 + 24 = 36. Submitting every 12 hours keeps the promise.
The rule: the longest wait for the next batch, plus the 24-hour window, must fit inside the deadline. If your promise were 24 hours, a batch alone could use it all up, and anything that arrived between batches would miss it.
Four jobs, sorted
| Job | Who waits, and when it is due | Lane |
|---|---|---|
| Nightly invoice extraction | Nobody waits; due by morning | Batch |
| Chat reply to a customer | A customer; due in seconds | Real time |
| Weekly document audit | Nobody waits; due next week | Batch |
| Autocomplete while typing | The user; due right now | Real time |
The cost follows the answer. Batch saves 50%, but only when waiting is fine. Real time pays full price for speed.
Common mistakes
- Matching results by position. Results come back in any order. Always join on
custom_id. - Reusing or skipping custom_ids. Give every request its own id, including the new chunks of a split request, or you can't tell answers apart.
- Resending the whole batch after a few failures. Resend only the failed ids. Fix an
invalid_request_error(here, by chunking) before resending; resend a server error unchanged. - Planning on "most batches finish within an hour". The promise is the 24-hour window. Do the deadline sum with 24.
- Batching something a person is waiting on. A cheaper chat reply that arrives tomorrow is useless.
Quick recap
| Idea | What to remember |
|---|---|
| The choice | Who is waiting, and how soon is it due? |
| Batch facts | 50% of the standard price, up to 24 hours, no exact time |
| Each request | A custom_id plus the usual params |
| Life cycle | Create (in_progress), poll until ended, read results |
| Results | Any order; succeeded, errored, canceled or expired; match by custom_id |
| Failures | Resend only those; fix bad requests first |
| Deadline | Wait for the next batch + 24 hours must fit the promise |
For a full overnight pipeline that also caches a shared guide and keeps a live lane for urgent documents, see the overnight document pipeline scenario.
Try it yourself
Change the promise to 30 hours. How often would you have to submit a batch to keep it? Then add a sixth line to results_sample.jsonl with "type": "expired" and check that resubmit.py picks it up. (Hint: an expired result has no error field, so you'll need to adjust failures().)
Related course on Udemy
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.