Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
Walk through five design decisions for a claims desk that tags 6,000 letters overnight: one batch job, a live lane for the urgent few, a cached shared prefix, a tested model tier and a morning reconcile by custom_id.
What you will learn
- Choose the Message Batches API or real-time calls by who is waiting
- Put a shared style guide first in a cached block so every request shares one prefix
- Pick a cheaper model tier only after it passes a sample check
- Reconcile batch results by custom_id and resend only the failures
Before you start
- The Claude Messages API: your first call
- Prompt caching basics
A claims desk collects about 6,000 scanned claim letters every evening. By 7 the next morning, each adjuster wants every letter tagged and summarised. Nobody waits on any single letter, but a few letters are urgent, with a customer on the phone. Every request starts with the same three-page style guide. And the monthly bill is the main worry.
That one paragraph already rules out half the designs you could build. In this article we make five decisions for this claims desk, in order, and look at the two small files that put them into practice. The short version: pay for patience, not for speed.
Read the scene for what it rules out
Before you think about any API, read each sentence of the requirement and ask what it forbids.
- Nobody waits on a single letter. You don't need an answer in seconds for most of the work.
- A few letters are urgent. Some work can't wait until tomorrow.
- Every request starts with the same style guide. A large part of each request repeats.
- The bill is the worry. Every choice gets judged on cost first, as long as the tags stay good.
Each decision below answers one of these sentences.
Decision 1: one batch job, a custom_id on every request
You could fire 6,000 parallel real-time calls and retry every failure. That works, but it pays the standard price for speed nobody asked for. Holding one streaming connection open all night doesn't help either: streaming shows the answer sooner, it doesn't make it cheaper. Cutting each letter down to its first paragraph throws away facts the adjusters need.
The fit is one Message Batches API job, with a custom_id on every request. Because nobody is waiting, you pay half price for patience. The Claude docs (Batch processing) say most batches finish within an hour, and all of them within 24 hours. For a 6 pm to 7 am window, that's enough.
Decision 2: the shared guide goes first, and gets cached
Even at the batch price, the three-page style guide is billed again on every one of the 6,000 requests. Prompt caching fixes that, but only if the requests really share a prefix.
- The guide goes first, in a block with
cache_control. The cache covers the prefix up to the breakpoint, so a guide placed after the letter shares nothing. - It must be identical in every request. Writing each letter's id at the top of the guide sounds tidy, but then no two prefixes match.
- Use the one-hour duration. A batch can run past five minutes, so the docs suggest the one-hour cache for batches. Cache hits are best effort, not guaranteed.
One trap: you can't "warm" the cache with a first request that has max_tokens set to 0 inside the batch. A batch doesn't accept that, and a warm entry would likely expire before the batch runs anyway. For how caching works in general, see prompt caching: keep the start of every request identical.
Decision 3: test a cheaper tier on a sample before you move
The pilot ran on the largest model and the tags look great. Finance wants the bill down. Moving everything to the smallest model tonight skips the check, and if the tags slip, the adjusters find out first. Keeping the largest model forever ignores a tier that might do the job just as well. Lowering max_tokens only cuts the summary short; reading the letter costs the same.
So run a fixed sample of your own letters on the smaller tier, compare its tags with tags you accept, and move only if it passes. The cheapest tier that passes your own check is the right one. The check has to be yours, because only you know what a good tag looks like on your letters.
Decision 4: the urgent few get a live lane
During the day the front desk flags a few urgent letters: a flooded kitchen, a customer on the phone. Each needs a tag within minutes. Putting it in tonight's batch is too late. Putting it at the top of the batch file doesn't help, because a batch promises no order and no time. Moving the whole pipeline to real time gives up the half price on thousands of letters nobody is waiting for.
The answer is two lanes. Who is waiting decides the lane. The urgent few go straight to a real-time call, and the rest stay in the night batch.
nightly.py: the two lanes in code
Here is the night lane in one small file. It builds the requests but doesn't send them, so it runs with no API key. The tier name is set once, after the sample check from decision 3.
"""Urgent claim letters go live. The rest wait for tonight."""
MODEL = "claude-haiku-5-5" # tier: after a sample check
STYLE = "Tag each letter: category, urgency, one-line summary."
SHARED = [{"type": "text", "text": STYLE,
"cache_control": {"type": "ephemeral", "ttl": "1h"}}]
def lane(letter):
return "live" if letter["urgent"] else "night"
def make_request(letter):
msg = {"role": "user", "content": letter["text"]}
return {"custom_id": letter["id"],
"params": {"model": MODEL, "max_tokens": 300,
"system": SHARED, "messages": [msg]}}
def split(rows):
live = [x["id"] for x in rows if lane(x) == "live"]
night = [make_request(x) for x in rows if lane(x) == "night"]
return live, night
if __name__ == "__main__":
letters = [{"id": f"clm-{n:04d}", "urgent": n in (3, 8),
"text": f"Claim letter number {n}"} for n in range(1, 13)]
live, night = split(letters)
print(len(letters), "letters:", len(live), "live,", len(night), "in the batch")
print("live ->", ", ".join(live))
print("night ->", night[0]["custom_id"], "to", night[-1]["custom_id"])
print("shared block:", night[0]["params"]["system"][0]["cache_control"]["ttl"])
# With a key, one call would send the night lane:
# batch = client.messages.batches.create(requests=night)
12 letters: 2 live, 10 in the batch
live -> clm-0003, clm-0008
night -> clm-0001 to clm-0012
shared block: 1h
SHAREDis the style guide as one system block, the same object in every request, withcache_controland"ttl": "1h".lane()is the whole routing rule: urgent goes live, everything else waits.- Every batch request carries the letter's id as its
custom_id. That id is what you'll match on in the morning. - The last line shows the one call that would send the night lane with a real key.
In this demo, 12 letters stand in for the 6,000: letters 3 and 8 are urgent and go live, the other 10 go into the batch.
Decision 5: the morning reconcile by custom_id
At 7 the results are in, but in a different order than you sent them. Some requests errored and one expired. Matching by position in the file can point a tag at the wrong letter. Running the whole batch again pays twice for letters that are already tagged. And ignoring the failures because they aren't billed misses the point: not billed doesn't mean done, those letters still have no tag.
So match every result by custom_id, keep the successes, and resend only the failures. Errored, canceled and expired requests aren't billed, so a resend of just those costs little.
"""Read the batch results, match them by custom_id, and list only what to resend."""
import json
NIGHT = (1, 2, 4, 5, 6, 7, 9, 10, 11, 12)
SENT = [f"clm-{n:04d}" for n in NIGHT]
def read(path="results_sample.jsonl"):
done, again = {}, {}
for line in open(path):
row = json.loads(line)
kind = row["result"]["type"]
(done if kind == "succeeded" else again)[row["custom_id"]] = kind
return done, again
done, again = read()
lost = [c for c in SENT if c not in done and c not in again]
print(len(done) + len(again), "of", len(SENT), "results read")
print(len(done), "succeeded, kept")
for cid, kind in sorted(again.items()):
print(" ", cid, "->", kind)
print("missing:", lost or "none")
print("resend only:", ", ".join(sorted(again)))
It reads a sample results file (made-up test data, so no key is needed). Each line looks like this:
{"custom_id":"clm-0012","result":{"type":"errored","error":{"type":"error","error":{"type":"invalid_request_error","message":"prompt is too long"}}}}
10 of 10 results read
7 succeeded, kept
clm-0004 -> expired
clm-0009 -> errored
clm-0012 -> errored
missing: none
resend only: clm-0004, clm-0009, clm-0012
Ten of ten results came back, out of order. Seven succeeded and are kept. One expired and two errored, found by custom_id, not by position. The missing line says every letter is accounted for, and the resend list holds only the three that failed.
Common mistakes
- Putting everything in real time "to be safe". You pay full price for speed on work nobody is waiting for.
- Putting the urgent letter first in the batch file. A batch has no promised order or time.
- A shared block that isn't quite shared. A per-letter id or date inside the guide breaks the prefix match on every request.
- Joining results by line number. Results come back in any order. The
custom_idis the join. - Treating "not billed" as "handled". A failed request still needs a resend.
Recap
| If the scene says | Do this |
|---|---|
| Nobody is waiting | One Message Batches job, a custom_id on every request |
| Every request starts the same | Shared part first, identical, cache_control with the 1-hour duration |
| The bill must come down | Test a cheaper tier on a fixed sample, move only if it passes |
| A few answers are needed now | Live calls for those, batch the rest |
| Results are back | Match by custom_id, resend only the failures |
Half price is for work that can wait. Everything else gets a live lane.
Try it yourself
Change nightly.py so a letter is also sent live when its text contains "phone". Then add a line to reconcile.py that writes the resend list as a new set of batch requests, reusing the same custom_id values, and check that the shared block is still byte-for-byte the same as in the first run.
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.