Batch Inference
Send work nobody is waiting on through the provider's batch endpoint at about half price, and make the job safe to resume, with results matched by ID and only real failures retried.
cd examples && pytest inference_and_serving/test_batch_inference.pyWhat It Is
Most model providers offer a batch endpoint. You submit thousands of requests in one job, the provider runs them when it has spare capacity, and you collect results later, typically within hours, at a large discount (half price on Anthropic's and OpenAI's batch APIs). The pattern is to route every workload that doesn't have a person waiting on it through that path, and to build the job around it so it can be resumed and its results trusted.
The Problem It Solves
A surprising share of LLM spend is work nobody watches in real time: nightly ticket classification, backfilling embeddings or summaries over a corpus, running an eval suite, bulk extraction from documents. Teams usually run it through the same synchronous API as the chat feature. That means full price, rate limits shared with interactive traffic, and a home-made loop of retries and sleeps that falls over at item 40,000 and starts again from zero.
How It Works
flowchart TD
J["Jobs: custom_id → params"] --> C["Skip ids already in checkpoint"]
C --> B["Split into batches
(count and size limits)"]
B --> S["Submit batch"]
S --> P{"Ended?"}
P -->|"no"| W["Wait, poll again"] --> P
P -->|"yes"| R["Read results, match by custom_id
(order is not guaranteed)"]
R --> OK["succeeded → checkpoint"]
R --> RT["expired / overloaded / no result → retry next round"]
R --> NR["invalid request → report, don't retry"]
RT -->|"rounds left"| B
- Pick the right work. Anything where a result in an hour is as good as one in a second. Keep interactive traffic on the synchronous API.
- Give every request a stable
custom_idfrom your own data (ticket ID, document ID). Results come back in any order, so never match them by position. - Respect the limits. Batches have a maximum request count and payload size (100,000 requests or 256 MB on Anthropic's API). Split large jobs.
- Checkpoint finished IDs somewhere durable. A rerun after a crash or a deploy resubmits only what isn't done.
- Sort the failures. Expired requests (the batch window closed before they ran), overload errors and missing results are retryable. Invalid requests fail again identically, so report them for a person to fix.
- Bound the retry rounds. Some requests will never succeed. After a few rounds, stop and report them instead of retrying forever.
- Combine with prompt caching. Requests in a batch that share a long prefix (the same instructions, the same document) can still benefit from Prompt Prefix Caching on providers that support both.
When to Use It
- Offline and scheduled jobs: classification, extraction, enrichment, summarization over a corpus.
- Evaluation runs: regression suites, LLM-as-Judge scoring of thousands of transcripts.
- Backfills after a prompt or model change.
When NOT to Use It
- Anyone is waiting. Batches usually finish well within the window, but the window is up to a day. That's not an SLA for a user.
- Multi-step work where each call depends on the previous answer. An agent loop can't wait an hour per turn. Run the loop synchronously, or batch only its independent leaves.
- Tiny jobs. For twenty requests, the bookkeeping costs more than the discount saves.
Trade-offs
- Latency for cost. You trade minutes-to-hours of delay, with no firm deadline below the window, for roughly half price and separate capacity.
- More moving parts. Polling, result files, checkpoints and partial failure handling replace a simple loop. That's worth it at thousands of requests, not at dozens.
- Not every feature is available. Some providers exclude certain features from batch requests (fast or priority modes, streaming). Check before moving a workload.
Failure Modes
Matching results by position. The code zips the inputs with the outputs, the provider returns them in a different order, and every label is attached to the wrong ticket, with no error. Always key by custom_id.
Retrying invalid requests forever. A malformed request fails identically every round, and the job never finishes. Separate retryable errors from request errors and cap the rounds.
No checkpoint. The job crashes at 90% and reruns everything, paying twice. Persist finished IDs as results arrive.
Batching side effects. The batch output triggers emails or writes directly, and a resumed job repeats them. Make the step that consumes results idempotent (Idempotent Tool Calls).
Implementation Example
A provider-neutral job runner: count- and size-aware chunking, polling, results matched by custom_id, a checkpoint that makes reruns skip finished work, and bounded retries for expired, overloaded and missing results only. The tests use a fake batch API that shuffles results, expires some requests, drops others and rejects one as invalid.
cd examples && pytest inference_and_serving/test_batch_inference.py"""Batch Inference.
Work nobody is waiting on (nightly classification, backfills, eval runs,
bulk extraction) goes through the provider's batch endpoint: submit many
requests at once, collect results hours later, pay a large discount.
The model part is easy. The engineering is around it:
- every request has a stable custom_id, results come back in any order and
are matched by id, never by position;
- batches respect the provider's size limits;
- a checkpoint of finished ids makes re-running the job skip done work;
- only retryable failures and expired requests are resubmitted, a bounded
number of rounds; invalid requests are reported, not retried forever.
`BatchAPI` is the provider surface (submit, status, results). Wire it to the
real batch endpoint; the tests use a fake that shuffles and fails things.
"""
from __future__ import annotations
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
from typing import Protocol
class BatchAPI(Protocol):
def submit(self, requests: list[dict]) -> str: ... # each request: {"custom_id", "params"}
def status(self, batch_id: str) -> str: ... # "in_progress" | "ended"
def results(self, batch_id: str) -> Iterable[dict]: ... # {"custom_id", "type", "output"|"error"}
RETRYABLE = {"expired", "overloaded", "server_error", "rate_limited"}
@dataclass
class Report:
succeeded: dict[str, object] = field(default_factory=dict)
failed: dict[str, str] = field(default_factory=dict) # custom_id -> reason
rounds: int = 0
batches: int = 0
def chunk(requests: list[dict], max_requests: int, max_bytes: int, size: Callable[[dict], int]) -> list[list[dict]]:
batches, current, current_bytes = [], [], 0
for r in requests:
n = size(r)
if current and (len(current) >= max_requests or current_bytes + n > max_bytes):
batches.append(current)
current, current_bytes = [], 0
current.append(r)
current_bytes += n
if current:
batches.append(current)
return batches
def run(
jobs: dict[str, dict], # custom_id -> request params
api: BatchAPI,
done: dict[str, object] | None = None, # checkpoint from a previous run, persisted by the caller
wait: Callable[[], None] = lambda: None, # sleep between polls; injected so tests don't sleep
max_rounds: int = 3,
max_requests: int = 10_000,
max_bytes: int = 100_000_000,
size: Callable[[dict], int] = lambda r: len(repr(r)),
) -> Report:
report = Report(succeeded=dict(done or {}))
pending = {cid: params for cid, params in jobs.items() if cid not in report.succeeded}
while pending and report.rounds < max_rounds:
report.rounds += 1
requests = [{"custom_id": cid, "params": params} for cid, params in pending.items()]
retry: dict[str, dict] = {}
for batch in chunk(requests, max_requests, max_bytes, size):
batch_id = api.submit(batch)
report.batches += 1
while api.status(batch_id) != "ended":
wait()
seen = set()
for result in api.results(batch_id): # any order: key by custom_id
cid = result["custom_id"]
seen.add(cid)
if result["type"] == "succeeded":
report.succeeded[cid] = result["output"]
report.failed.pop(cid, None)
elif result["type"] in RETRYABLE or result.get("error") in RETRYABLE:
retry[cid] = pending[cid]
report.failed[cid] = f"retryable: {result.get('error', result['type'])}"
else:
report.failed[cid] = f"not retried: {result.get('error', result['type'])}"
for item in batch: # a request with no result at all is treated as lost and retried
if item["custom_id"] not in seen:
retry[item["custom_id"]] = item["params"]
report.failed[item["custom_id"]] = "retryable: no result returned"
pending = retry
return reportTool Landscape
| Tool | Notes |
|---|---|
| Anthropic Message Batches API | 50% of standard price; up to 100,000 requests or 256 MB per batch; most finish within an hour, maximum 24 hours |
| OpenAI Batch API | Discounted asynchronous jobs from a JSONL file with a 24-hour completion window |
| Google Gemini batch mode, Vertex AI batch prediction | Asynchronous batch jobs at a discount |
| vLLM offline inference, Ray Data | Batch generation when you self-host |
Related Patterns
- Quota-Aware Model Pool handles synchronous traffic under caps. Moving offline work to batch frees that quota for users.
- Prompt Prefix Caching stacks with batch discounts when requests share a long prefix.
- Idempotent Tool Calls: whatever acts on batch results must be safe to rerun.
- LLM-as-Judge evaluation runs are a natural batch workload.
Further Reading
- Batch processing, Anthropic documentation
- Batch API, OpenAI documentation
- Batch Mode, Google Gemini documentation
Spotted something wrong or have a production story? Edit this page on GitHub.