Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Claude
  • CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
  • Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
  • One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
  • Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin
  • Rolling Out Claude Code to a Team: Settings Precedence, dontAsk in CI, a Hook for Every-Time Rules and a Plugin for Five Repos
  • A Claude Code Review Bot in CI: Headless -p, JSON Findings, Team Rules in Git and a Person on the Merge
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • The Claude Messages API: Your First Call, Field by Field
  • Claude Tool Use: How tool_use and tool_result Work in the Messages API
  • Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
  • Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
  • Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
  • Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
  • Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
  • Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives
  • Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
  • Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
  • Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
  • Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
  • Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door
  • The Life Cycle of a Claude App: Six Phases, a Model That Retires, and a Release Gate for Every Change
  • Pinning Claude Model IDs and Upgrading Safely: One Change at a Time, a Golden-Set Replay and a Staged Rollout
  • Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
  • The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
  • The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript
  • Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line
  • Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
  • Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
  • Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
  • Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
  • Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
  • Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
  • Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet
  • Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
  • Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First
  • Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits
  • System Prompt or User Turn: Where Each Instruction Goes, and Output Limits Your Code Enforces
  • Refine the Prompt One Line at a Time, Then Clean and Fence the Customer's Text
  • Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
  • Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
  • Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
  • Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values
  • Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
  • Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
  • Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
  • Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
  • Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop
  • Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
  • Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
  • Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
  • Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
  • Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

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.

Chaand Sheikh

·27 November 2026Building with the Claude API

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

Batch lane and real-time lane Work that can wait Message Batches API Nightly invoice extraction Overnight report Weekly document audit 50% of the standard price up to 24 hours, no exact time Someone is waiting real-time Messages API Live chat reply to a customer Autocomplete while typing standard price answers now
Sort each job by who is waiting. Batch is for work that can wait; anything a person waits on goes real time.

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-0002 and so on. That id is how you will find this invoice's answer later.
  • The params are the usual Messages call: model, max_tokens and messages. 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, poll, read 1. Create status: in_progress the call returns at once 2. Poll until status: ended window: up to 24 hours 3. Read results in any order one result type each succeeded | errored | canceled | expired match by custom_id, never by position
A batch is asynchronous: you don't hold the line while it runs.
  1. Create. One call to client.messages.batches.create sends all the requests. The status starts as in_progress and the call returns at once.
  2. 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.
  3. Read. Fetch the results with client.messages.batches.results(batch.id). They don't come back in request order. Each result is succeeded, errored, canceled or expired.

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 new custom_id (inv-0004-p1 to -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

JobWho waits, and when it is dueLane
Nightly invoice extractionNobody waits; due by morningBatch
Chat reply to a customerA customer; due in secondsReal time
Weekly document auditNobody waits; due next weekBatch
Autocomplete while typingThe user; due right nowReal 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

IdeaWhat to remember
The choiceWho is waiting, and how soon is it due?
Batch facts50% of the standard price, up to 24 hours, no exact time
Each requestA custom_id plus the usual params
Life cycleCreate (in_progress), poll until ended, read results
ResultsAny order; succeeded, errored, canceled or expired; match by custom_id
FailuresResend only those; fix bad requests first
DeadlineWait 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().)

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Claude · 22 of 66

Previous
Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
Next post
Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door

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.

On this page

  • The laundry service and the dryer at home
  • Two lanes of work
  • build_batch.py: one request per invoice
  • The life cycle of a batch
  • resubmit.py: resend only what failed
  • The deadline sum
  • Four jobs, sorted
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.