Batch inference
When nobody waits on a single answer, submit the whole job offline: provider batch APIs give ~50% off with results within 24 h, and self-hosted runs push GPUs to peak throughput.
Analogy: Shipping freight instead of couriers: you give up a delivery time slot and get half the price per package.
How it works
- Batch APIs run on separate limits from your real-time quota, so a backfill doesn't starve production.
- Self-hosted, with no latency SLO, raise batch sizes until decode stops being memory-bound.
- Give every item a stable id (
custom_id) so reruns skip finished work and results join back reliably. - Checkpoint in shards of ~10k–50k requests with their batch ids, so a crash costs one shard.
- Items can fail or expire: reconcile input against output and resubmit only the gaps.
Check yourself
Answer to mark it learned; your answers aren't scored.
A 10M-item classification job ran through a provider batch API. One batch came back expired, and the outputs hold ~9.6M results in total. A teammate proposes resubmitting the whole job. What do you do?
Go deeper
Full explanation
Batch inference runs a large set of LLM calls where no user waits on any single result: classify 10M tickets, backfill embeddings after a model change, run nightly evals, generate synthetic data. You optimize cost and throughput, not latency.
Two ways to run it:
- Provider batch APIs: submit requests in bulk (OpenAI Batch takes a JSONL file, Anthropic Message Batches a list in one API call) and get per-item results back as JSONL within 24 h at ~50% off. Both run on limits separate from your real-time quota, so a backfill doesn't starve production.
- Self-hosted max throughput: vLLM in offline mode (
LLM.generateover the whole list) or a Ray Data pipeline. With no latency SLO you can raise batch sizes until decode stops being memory-bound, which is where tokens per GPU-dollar peak (Continuous batching, API vs self-hosting).
The rest is classic data-pipeline engineering:
- Idempotency: a stable
custom_idper item, likedoc123-prompt_v3(Anthropic allows only[A-Za-z0-9_-], max 64 chars), so reruns skip finished work and results join back reliably (Idempotency). - Checkpointing: shard into files of ~10k–50k requests and record each shard's batch id and status. A crash costs one shard, not the job.
- Partial failure: batches return per-item errors and can expire with work unfinished. Reconcile input against output and resubmit only the gaps.
- Provenance: store model id and prompt version on every output row.
Code Submit one shard to the OpenAI Batch API
import json
from openai import OpenAI
MODEL = "gpt-4.1-mini" # any chat model
PROMPT_V = "v3"
client = OpenAI()
def submit_shard(name: str, docs: list[dict]) -> str:
with open(f"{name}.jsonl", "w") as f:
for d in docs:
if is_done(d["id"], PROMPT_V): # idempotent rerun: skip finished items
continue
f.write(json.dumps({
"custom_id": f"{d['id']}-{PROMPT_V}", # join key; keep it to [A-Za-z0-9_-]
"method": "POST", "url": "/v1/chat/completions",
"body": {"model": MODEL, "max_completion_tokens": 5,
"messages": [{"role": "system", "content": LABEL_PROMPT},
{"role": "user", "content": d["text"]}]},
}) + "\n")
file = client.files.create(file=open(f"{name}.jsonl", "rb"), purpose="batch")
batch = client.batches.create(input_file_id=file.id,
endpoint="/v1/chat/completions",
completion_window="24h")
save_checkpoint(name, batch.id) # after a crash, resume by polling this id
return batch.id
def collect(batch_id: str) -> None:
b = client.batches.retrieve(batch_id)
if b.status not in ("completed", "expired"): # expired keeps partial output
return
if b.output_file_id:
for line in client.files.content(b.output_file_id).text.splitlines():
r = json.loads(line)
store(r["custom_id"], r["response"]["body"]["choices"][0]["message"]["content"])
# missing custom_ids (b.error_file_id, expiry) go back through submit_shardReal example
Re-label 8M support tickets with a new 12-class taxonomy: ~400 input and ~5 output tokens each, so ~3.2B input tokens. At an illustrative $0.40/M input and $1.60/M output, real time costs ~$1,350 and would fight production for TPM for days. The batch API halves it to ~$670 on a separate quota. A 1k-ticket pilot first catches a label typo. The run is 160 shards of 50k requests; most finish within hours, and ~0.3% of items error and are resubmitted by custom_id.
Trade-offs +3 · −3
+ You gain
- ~Half the price of the same model in real time, for little more than a JSONL file.
- Separate quota: backfills and evals don't eat production rate limits.
- Self-hosted offline runs keep GPUs saturated: no SLO, big batches, peak tokens per dollar.
− You pay
- No latency guarantee: up to 24 h, so useless for users or step-by-step agent loops.
- Slow feedback: a prompt bug surfaces hours later, across millions of items.
- Extra plumbing: sharding, polling, joins and partial-failure reconciliation.
Use it when
Any job where nobody waits on one result: bulk classification or extraction, embedding backfills, nightly evals, LLM-as-judge over logs, synthetic data.
Avoid it when
User-facing requests, agent loops where each step depends on the last, or jobs that must finish within the hour: use real-time calls with rate-limit-aware concurrency.
Numbers to know 4
- OpenAI Batch and Anthropic Message Batches: ~50% off standard prices, results within 24 h, often much sooner.
- Per batch: OpenAI up to 50,000 requests and 200 MB; Anthropic up to 100,000 requests or 256 MB.
- Anthropic keeps batch results for 29 days, and its batch discount stacks with prompt caching.
- Cost math: items × (input tokens × input price + output tokens × output price) × 0.5. Output tokens usually cost ~4–8× input.
Common pitfalls 4
- Submitting all 10M items before validating the prompt on a ~1k sample with an eval.
- Non-idempotent writes: a rerun duplicates rows. Upsert on
custom_id. - Assuming all-or-nothing: always diff input ids against output ids and resubmit errors and expirations.
- Ignoring the batch queue limit (enqueued tokens per model): submit in waves or batches get rejected.
Interview questions 2
Answer out loud first, then reveal.
You need to classify 50M documents with an LLM. Walk me through it.Show answer
First I shrink the problem: dedupe, and check whether a small fine-tuned model or embeddings plus a classifier meets the accuracy bar, because at 50M items per-item cost dominates. Then a 1k pilot scored against labels. For the run: shards of up to 50k requests, custom_id as doc_id plus prompt version, submitted through the batch API at half price, a checkpoint table mapping shard to batch id, then poll, join by custom_id and resubmit errors. Every row stores model and prompt version.
Provider batch API or self-hosted vLLM for a recurring bulk job?Show answer
It's a cost and data-control question. The batch API is zero infra and half price, but per-token pricing scales linearly and the data leaves my boundary. Self-hosted, I pay for GPU-hours, and offline mode with big batches gets close to peak throughput, so at sustained high volume on an open model it can win, but only if I keep the GPUs busy and someone owns the cluster. I'd start on the API, measure tokens per GPU-hour on vLLM, and switch at the measured crossover or when data residency forces it.