AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How Software Engineers Use the Anthropic Claude Message Batches API to Process High-Volume Asynchronous Workloads at Half the Cost

심동규 · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Real-time API endpoints are an expensive misallocation for offline data pipelines. When data engineers and backend architects run text categorization over millions of customer transcripts, perform nightly model evaluations, or clean synthetic training datasets through synchronous Claude Messages API calls, they inevitably collide with two walls: strict concurrency rate limits (429 Too Many Requests) and full-price on-demand token billing.

At 365Finds, our commercial assessment is straightforward: sending non-latency-sensitive workloads through synchronous endpoints is an engineering anti-pattern. Anthropic's native Message Batches API cuts token expenses by exactly 50% across both input and output while routing workloads through an isolated processing pool. Understanding how to orchestrate this API—from schema construction and idempotent keying to polling and partial-failure streaming—transforms batch processing from an ad-hoc scripting headache into a hardened, high-throughput pipeline.


The Economic and Architectural Mechanics of Message Batches

The premise of the Message Batches API (POST /v1/messages/batches) is built on unbundling immediate availability from model compute. By granting Anthropic an asynchronous delivery window—up to 24 hours, though most standard batches complete in under 60 minutes—the platform schedules inference during capacity valleys. In exchange, users receive a flat 50% price reduction across all supported Claude models.

Model TierReal-Time Input / Output (per MTok)Message Batches Input / Output (per MTok)Direct Savings
Claude Opus 5.5$4.00 / $20.00$2.00 / $10.0050%
Claude Sonnet 5.5$2.00 / $10.00$1.00 / $5.0050%
Claude Haiku 5.5 (≤100k prompt)$0.10 / $0.50$0.05 / $0.2550%
Claude Haiku 4.5$1.00 / $5.00$0.50 / $2.5050%

Beyond pure financial savings, the architectural gain is throughput decoupling. Message Batches do not consume your standard Messages API request-per-minute (RPM) or tokens-per-minute (TPM) limits. Instead, batches run against separate batch queue thresholds. A pipeline submitting 80,000 document extraction tasks at midnight will not starve or degrade user-facing production chatbots operating on the synchronous Messages API.

Core Constraints and Limits

To design around the Batches API effectively, engineers must account for several rigid boundaries:


Constructing the Ingestion Pipeline: Custom IDs and Schema Rules

Unlike synchronous requests where HTTP connections preserve request-response affinity, batch inference processes individual records out of order. Establishing idempotency and downstream alignment demands a deterministic keying strategy via custom_id.

Anthropic enforces a strict regex for custom_id: ^[a-zA-Z0-9_-]{1,64}$. 365Finds recommends using composite surrogate keys encoding the entity type, database primary key, and pipeline execution hash (e.g., doc_v2_usr9482_b8f10a). Never use raw arbitrary text or non-deterministic counters.

Parameter Restrictions

Almost all Messages API capabilities carry over directly to batch mode—including Vision, complex system messages, multi-turn dialogue histories, server tools, and extended thinking. However, four specific parameters trigger immediate validation failures if present in a batch item:

  1. stream: true (Batch returns consolidated newline-delimited JSON, not SSE token streams)
  2. speed (Fast mode synchronous latency tuning is invalid for asynchronous queuing)
  3. fallbacks (Server-side immediate failover does not apply to batch tasks)
  4. max_tokens: 0 (Cache pre-warming is rejected inside batches because ephemeral cache keys may expire before subsequent requests execute)
import anthropic
from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
from anthropic.types.messages.batch_create_params import Request

client = anthropic.Anthropic()

# Constructing a typed, decoupled batch payload
requests_payload = [
    Request(
        custom_id="extract_inv_20261108_001",
        params=MessageCreateParamsNonStreaming(
            model="claude-sonnet-5-5",
            max_tokens=1024,
            system="Extract structured invoice metadata as strict JSON.",
            messages=[
                {"role": "user", "content": "Raw invoice payload: Invoice #1042, Total: $482.10, Vendor: Acme Corp."}
            ]
        )
    ),
    Request(
        custom_id="extract_inv_20261108_002",
        params=MessageCreateParamsNonStreaming(
            model="claude-sonnet-5-5",
            max_tokens=1024,
            system="Extract structured invoice metadata as strict JSON.",
            messages=[
                {"role": "user", "content": "Raw invoice payload: Invoice #1043, Total: $1,290.00, Vendor: Stark Ltd."}
            ]
        )
    )
]

# Dispatch the batch job
batch = client.messages.batches.create(requests=requests_payload)
print(f"Batch dispatched. Batch ID: {batch.id} | Status: {batch.processing_status}")

Polling, Lifecycle States, and Memory-Safe Result Streaming

Once dispatched, a batch enters the in_progress state. Because validation of individual request bodies is performed asynchronously on Anthropic's worker fleet, a 200 OK on batches.create only guarantees that the outer envelope passed sanity checks.

Lifecycle State Machine

import time

def await_batch_completion(client: anthropic.Anthropic, batch_id: str, poll_interval: int = 30):
    """
    Polls the batch retrieval endpoint with exponential backoff or standard intervals.
    Inspection of batch_status.request_counts provides real-time progress.
    """
    while True:
        status = client.messages.batches.retrieve(batch_id)
        counts = status.request_counts
        print(
            f"Status: {status.processing_status} | "
            f"Processing: {counts.processing} | "
            f"Succeeded: {counts.succeeded} | "
            f"Errored: {counts.errored}"
        )
        
        if status.processing_status == "ended":
            return status
            
        time.sleep(poll_interval)

Streaming JSONL Output Without OOM Spikes

When batches process 50,000 to 100,000 records, downloading the raw JSONL results payload into memory will crash standard application instances. 365Finds strongly advises against parsing results via monolithic HTTP GET buffers. Instead, use the SDK's built-in memory-efficient line iterator client.messages.batches.results(batch_id):

def process_batch_stream(client: anthropic.Anthropic, batch_id: str):
    """
    Iterates through the .jsonl results stream line-by-line.
    Handles success and error states defensively without holding the entire payload in RAM.
    """
    for item in client.messages.batches.results(batch_id):
        custom_id = item.custom_id
        outcome = item.result
        
        match outcome.type:
            case "succeeded":
                # Message response object matches standard Messages API structure
                message = outcome.message
                text_response = "".join(
                    block.text for block in message.content if block.type == "text"
                )
                input_tokens = message.usage.input_tokens
                output_tokens = message.usage.output_tokens
                # Persist to database using custom_id as primary lookup
                commit_record(custom_id, text_response, input_tokens, output_tokens)
                
            case "errored":
                # Anthropic categorizes errors: invalid_request_error vs server_error
                error_obj = outcome.error.error
                if error_obj.type == "invalid_request_error":
                    # Non-retryable without payload alteration (e.g. prompt token overflow)
                    log_fatal_item(custom_id, error_obj.message)
                else:
                    # Ephemeral 5xx backend error; enqueue for targeted single retry
                    enqueue_retry(custom_id, error_obj.message)
                    
            case "expired":
                # Hit the 24-hour limit; not billed, must be re-batched
                log_timeout_item(custom_id)
                
            case "canceled":
                log_canceled_item(custom_id)

Error Handling: Triage Between Invalid Requests and Ephemeral Failures

In high-volume batch processing, partial failure is an operational certainty. Treating an entire 50,000-item batch as failed because 12 items errored is a severe operational mistake.

When outcome.type == "errored", inspect outcome.error.error.type:


Stacking Prompt Caching and Server-Side Capabilities

A common misconception is that batching precludes prompt caching. In reality, Prompt Caching and Message Batches can be combined. When thousands of requests in a batch share an identical 10,000-token system prompt, classification rubric, or legal document, developers can mark the invariant prefix with cache_control: {"type": "ephemeral"}.

The Asynchronous Caching Caveat

Because the batch engine schedules sub-requests concurrently across disparate server nodes, cache hits in Message Batches are delivered on a best-effort basis. In production workloads, cache hit rates fluctuate between 30% and 95%.

Server Tools and Extended Outputs


365Finds Decision Matrix: Batch vs. Real-Time API

Engineers frequently struggle with where to draw the boundary between real-time Messages and asynchronous Batches. We recommend this architectural split:

Workload Classification Decision Tree:
│
├── User waiting in interactive session (< 5 sec SLA)?
│   └── YES ──> Synchronous Messages API (Full cost, low latency)
│
├── Hard downstream pipeline deadline < 1 hour?
│   └── YES ──> Synchronous Messages API with managed concurrency pools
│
└── Tolerant to completion within 1 - 24 hours?
    └── YES ──> Anthropic Message Batches API (50% Cost Savings, Zero RPM Impact)

If an asynchronous task can accommodate a variable 15-minute to 4-hour completion window, leaving it on synchronous endpoints burns double the infrastructure budget and adds unnecessary retry handling for transient HTTP 429 errors.

Anthropic's Message Batches API provides an explicit, deterministic contract: half the cost, complete workload isolation from real-time traffic, resilient partial-failure reporting, and zero billing on unfulfilled queries. For modern AI backend engineering, adopting it is not just an optimization; it is baseline operational hygiene.


References