Claude Message Batches API in Python: 50% Cheaper Bulk Jobs

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 7 min read🎯 D2 Messages API Mechanics · D5 Cost Diagnosis and Optimization

👋 In plain words: When you have thousands of requests and do not need answers right away, you can send them all as one batch. Anthropic processes them in the background at half the normal price. This lesson walks you through a whole batch job step by step: create, wait, collect and retry.

Advertisement

Labelling a backlog of bug reports, summarising a month of CI logs, generating test ideas for every user story: these jobs are large and not urgent, which is exactly what the Message Batches API is for. In this lesson you will create a batch, poll it until it ends, read results by custom_id, handle errored and expired items, and calculate the saving against real-time calls.

📖 What You’ll Learn: You will be able to decide when to use batches, create and poll a Message Batch in Python, map results back by custom_id, handle every result type, and estimate the cost saving.

🔑 Key terms

  • Message Batch: a group of Messages API requests processed asynchronously.
  • custom_id: your own ID for each request in the batch. Results come back with it.
  • processing_status: the batch state: in_progress, canceling or ended.
  • Result type: per request, one of succeeded, errored, canceled or expired.

🪜 Step 1: Decide whether a batch fits

Use this quick check:

Question Batch Real-time
Does a person wait for the answer? No Yes
Can results arrive within hours? Yes No
Are there many independent requests? Yes Either
Is cost the main concern? Yes: 50% off all tokens Normal price

Key facts from Anthropic’s documentation:

  • Up to 100,000 requests or 256 MB per batch.
  • Most batches finish within 1 hour; the maximum is 24 hours, after which unfinished requests expire.
  • Results are available for 29 days.
  • 50% cost reduction on all token usage.
  • Most Messages API features work in batches (vision, tools, prompt caching), but a batch request cannot set stream, speed, fallbacks or max_tokens: 0.

🪜 Step 2: Create the batch

Each request has a custom_id and the normal params you would pass to messages.create:

📄 create_batch.py

import json

import anthropic
from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
from anthropic.types.messages.batch_create_params import Request

client = anthropic.Anthropic()

bugs = {
    "BUG-101": "Export to CSV crashes when the table is empty",
    "BUG-102": "Typo on the About page",
    "BUG-103": "Card charged twice when the user double-clicks Pay",
}

SYSTEM = "Classify bug severity as critical, major or minor. Reply with one word."

batch = client.messages.batches.create(
    requests=[
        Request(
            custom_id=bug_id,
            params=MessageCreateParamsNonStreaming(
                model="claude-opus-5-5",
                max_tokens=10,
                system=SYSTEM,
                messages=[{"role": "user", "content": text}],
            ),
        )
        for bug_id, text in bugs.items()
    ]
)
print("batch id:", batch.id)
print("status  :", batch.processing_status)
json.dump({"batch_id": batch.id}, open("batch.json", "w"))

⌨️ Terminal

python create_batch.py

🖥️ Output (sample run)

batch id: msgbatch_0193K7gU6Rbq6ZyqoiUs3nV5
status  : in_progress
  • Save the batch ID. A real batch can take a while, and your script may stop before it ends.
  • Reuse the same system prompt in every request. With a cache breakpoint, batches can also benefit from prompt caching (Lesson 43).
Advertisement

🪜 Step 3: Poll until it ends

📄 poll_batch.py

import json
import time

import anthropic

client = anthropic.Anthropic()
batch_id = json.load(open("batch.json"))["batch_id"]

while True:
    batch = client.messages.batches.retrieve(batch_id)
    if batch.processing_status == "ended":
        break
    print("still processing:", batch.request_counts.processing)
    time.sleep(60)  # poll gently; most batches finish within an hour

c = batch.request_counts
print(f"ended: succeeded={c.succeeded} errored={c.errored} canceled={c.canceled} expired={c.expired}")

⌨️ Terminal

python poll_batch.py

🖥️ Output (sample run)

ended: succeeded=3 errored=0 canceled=0 expired=0
💡 Tip: In production, do not keep a Python process sleeping for hours. Store the batch ID, and check it from a scheduled job (cron, a CI schedule, a queue worker).

🪜 Step 4: Read results by custom_id

Results arrive in any order. Always key them by custom_id, never by position:

📄 read_results.py

import json

import anthropic

client = anthropic.Anthropic()
batch_id = json.load(open("batch.json"))["batch_id"]

severity = {}
for item in client.messages.batches.results(batch_id):
    if item.result.type == "succeeded":
        text = next(b.text for b in item.result.message.content if b.type == "text")
        severity[item.custom_id] = text.strip()
    else:
        severity[item.custom_id] = f"<{item.result.type}>"

for bug_id in sorted(severity):
    print(bug_id, "->", severity[bug_id])

⌨️ Terminal

python read_results.py

🖥️ Output (sample run)

BUG-101 -> major
BUG-102 -> minor
BUG-103 -> critical
⚠️ Watch out: Zipping results with your input list (“result 1 belongs to bug 1”) silently assigns the wrong answers to the wrong items, because results are not in input order. This is a favourite exam scenario.
Advertisement

🪜 Step 5: Handle every result type

Result type Meaning What to do
succeeded The request ran Read result.message
errored with invalid_request The request itself was invalid Fix it; do not resubmit unchanged
errored (other) A server-side problem Safe to resubmit
canceled You cancelled the batch before it ran Resubmit if still needed
expired Not processed within 24 hours Resubmit in a new batch

This helper sorts results into “done”, “fix” and “resubmit” lists. It runs locally on sample result objects so you can see the logic:

📄 triage_results.py

from types import SimpleNamespace as NS

results = [
    NS(custom_id="BUG-101", result=NS(type="succeeded")),
    NS(custom_id="BUG-104", result=NS(type="errored", error=NS(type="invalid_request"))),
    NS(custom_id="BUG-105", result=NS(type="errored", error=NS(type="api_error"))),
    NS(custom_id="BUG-106", result=NS(type="expired")),
]

done, fix, resubmit = [], [], []
for r in results:
    kind = r.result.type
    if kind == "succeeded":
        done.append(r.custom_id)
    elif kind == "errored" and r.result.error.type == "invalid_request":
        fix.append(r.custom_id)
    else:  # other errors, canceled, expired
        resubmit.append(r.custom_id)

print("done    :", done)
print("fix     :", fix)
print("resubmit:", resubmit)

⌨️ Terminal

python triage_results.py

🖥️ Output

done    : ['BUG-101']
fix     : ['BUG-104']
resubmit: ['BUG-105', 'BUG-106']
Advertisement

🪜 Step 6: Calculate the saving

Batch pricing is 50% of standard pricing for both input and output. Using the Opus 5.5 list price ($4 input / $20 output per MTok):

📄 batch_saving.py

INPUT, OUTPUT = 4.00, 20.00  # Claude Opus 5.5, $ per million tokens
requests, tokens_in, tokens_out = 20_000, 1_500, 200

realtime = requests * (tokens_in * INPUT + tokens_out * OUTPUT) / 1_000_000
batch = realtime * 0.5
print(f"real-time: ${realtime:,.2f}")
print(f"batch    : ${batch:,.2f}")
print(f"saving   : ${realtime - batch:,.2f} per run")

⌨️ Terminal

python batch_saving.py

🖥️ Output

real-time: $200.00
batch    : $100.00
saving   : $100.00 per run
🎯 Exam focus: Batches combine with prompt caching for even larger savings on a shared prefix. The exam’s cost scenarios often ask you to pick the optimisation that matches the dominant cost: batching when work is not latency-sensitive, caching when a large prefix repeats, token budgets/effort when output or thinking dominates.

🌍 Real-world example: Ravi’s backlog

Ravi had 18,000 old bug reports to label by component. A real-time job would have cost about $230 and needed rate-limit handling. As a batch it cost about half, finished in under an hour, and the 12 items that came back errored with invalid_request turned out to be empty reports, which he removed instead of resubmitting.

🧪 Practice Questions

Question 1. A batch job writes results to a spreadsheet by zipping the results iterator with the input list. Some rows show the wrong severity. What is the defect?

  • A. The model is inconsistent
  • B. Batch results arrive in any order; they must be matched by custom_id
  • C. max_tokens is too small
  • D. Batches do not support system prompts
Show answer

Answer: B. Results are not guaranteed to be in input order. Each result carries the custom_id you assigned.

Question 2. Which workload fits the Message Batches API best?

  • A. A chatbot answering users in real time
  • B. Summarising 30,000 archived test reports by tomorrow
  • C. Streaming a code review into an IDE
  • D. A voice assistant
Show answer

Answer: B. Batches suit large, independent, non-urgent jobs and cost 50% less. Interactive features need real-time calls.

Question 3. A batch result has type “errored” with error type “invalid_request”. What should you do?

  • A. Resubmit it unchanged in a new batch
  • B. Fix the request before resubmitting
  • C. Wait 24 hours
  • D. Ignore it; it will succeed later
Show answer

Answer: B. An invalid request fails the same way every time. Server-side errors and expired items can be resubmitted.

Question 4. Which two are true for Message Batches? (Choose 2.)

  • A. Most batches finish within an hour; the maximum is 24 hours
  • B. Batch requests can stream their responses
  • C. Results are available for 29 days
  • D. Batches cost the same as real-time requests
Show answer

Answer: A and C. Batches are asynchronous, cannot stream, keep results for 29 days and are billed at 50%.

📝 Assignment

  1. Task 1: Turn one of your own repetitive Claude tasks into a batch with at least 20 requests and meaningful custom_id values.
    ✅ Done when: every result is saved against its custom_id.
  2. Task 2: Extend read_results.py to write done, fix and resubmit lists to a JSON file.
    ✅ Done when: the file has all three keys.
  3. Stretch: Write a script that creates a new batch from the resubmit list only.
    ✅ Done when: the new batch contains exactly those custom IDs.
Advertisement

❓ Frequently Asked Questions

🤔 How much cheaper is the Claude Batch API?

Batch processing is billed at 50% of standard prices for input and output tokens.

🤔 How long does a Claude message batch take?

Most finish within an hour. Requests not processed within 24 hours expire.

🤔 Can I use tools or images in a batch?

Yes. Most Messages API features, including vision, tools and prompt caching, work in batches. Streaming does not.

🤔 How many requests can one batch hold?

Up to 100,000 requests or 256 MB, whichever comes first.

🏁 Summary

  • Batches suit large, independent, non-urgent jobs and cost 50% less.
  • Create with client.messages.batches.create, poll retrieve until ended, then stream results.
  • Match results by custom_id; they arrive in any order.
  • Fix invalid_request errors; resubmit other errors, canceled and expired items.
  • Combine batches with prompt caching for a shared prefix.
📝 Test yourself: D2 Applications and Integration practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Claude Prompt Engineering Basics: Clarity, Roles and XML Tags.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.