Batch Inference
Offline jobs that process large corpora cheaper with higher latency tolerance.
In plain words
Instead of asking the AI one question at a time and waiting, you hand it a huge pile of questions to work through overnight at a lower price.
Think of it like…
Mailing a million letters through a bulk-mail service: slower and cheaper than courier delivery, sorted and sent in big batches, with a process for the few that bounce.
Where you’ve seen it
A team must classify 10 million documents (800 input and 60 output tokens each) into a taxonomy: 8 billion input and 0.6 billion output tokens. On a small model priced at an illustrative $0.15 per million input and $0.60 per million output, real-time cost is 8,000 × $0.15 + 600 × $0.60 = $1,200 + $360 = $1,560; the batch tier at 50% off costs $780. Deduplicating the inputs first removes 12% of documents (8.8 million left), cutting the bill to $686. Real-time processing within 24 hours would need 8.6B ÷ 1,440 minutes ≈ 6 million tokens per minute, far above typical rate limits, while the batch queue has separate, much larger quotas. The job runs as 200 JSONL files of 50,000 requests each with a custom_id per document; 0.3% of requests fail validation (invalid JSON) and are resubmitted with a stricter prompt, and results are written idempotently keyed by custom_id so reruns don't duplicate rows.
Words you’ll hear
- Batch API / offline job
- An asynchronous interface that accepts many requests and returns results within a completion window.
- custom_id
- A caller-supplied identifier on each request used to match results, since order isn't guaranteed.
- Idempotent write
- Storing a result so repeating the operation doesn't create duplicates.
- Completion window
- The maximum time (for example 24 hours) the provider takes to finish a batch.
Visual diagram
Theory & deep dive
Provider batch APIs and self-hosted offline inference
Hosted batch APIs take a file of requests (one JSON per line with a custom_id, model and body), run them asynchronously within a completion window (up to 24 hours) and return an output file plus an error file. They usually cost about half the real-time price, have separate rate limits from the synchronous API and are ideal for classification, extraction, summarisation, embeddings backfills and evaluation runs. Constraints: per-file request and size limits (so split large jobs), no streaming, results returned out of order (join on custom_id), batches can expire or partially fail and features may differ from the real-time API.
Self-hosted offline inference (vLLM's offline engine, or a distributed framework such as Ray Data feeding vLLM) uses the throughput-optimal part of the curve: large batches, long-running GPU jobs and no latency SLO. Sort requests by length to reduce padding waste, share prefixes (a common instruction block) via prefix caching, checkpoint progress periodically so a crash doesn't restart the job, and use cheaper preemptible or spot GPUs with automatic requeueing. Offline jobs are also good for generating embeddings and for LLM-as-judge evaluation over large sets.
{"custom_id": "doc-0001873", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "small-model", "messages": [...], "max_tokens": 100}} The result line returns the same custom_id with the response or an error.
Making large jobs safe and cheap
Pilot before the full run: test the prompt and schema on a few hundred diverse samples, measure token counts and failure rate and extrapolate cost (8.8M documents × tokens × price) so you can set a budget and abort threshold. Deduplicate inputs and cache results by content hash so repeated documents aren't processed twice; shard into files sized under provider limits; and set max_tokens so a runaway output can't inflate cost. Use structured outputs and validate every response against a schema; route failures (invalid JSON, refusals, truncation) into a retry queue with an adjusted prompt, and a small manual-review bucket for those that keep failing.
Treat the pipeline as idempotent and resumable: track state per shard (pending, submitted, completed, failed), store results with an upsert keyed by custom_id and make resubmission safe. Poll with backoff or use webhooks, handle expired batches and respect quotas on the number of concurrent batches. Monitor cost per document, failure categories and output distribution (a sudden shift in label proportions can reveal a prompt bug), and sample-audit results against human labels before consuming them downstream. If results feed a product, version the prompt, model and job id in the output so you can reproduce and compare runs.
Pilot of 500 documents averages 812 input and 58 output tokens: per document $0.000122 + $0.0000348 = $0.000157 at real-time prices. For 8.8M documents that is about $1,378 at real-time prices and about $690 on the batch tier; a 0.3% failure rate means about 26,400 documents to retry.
How it works, step by step
Step 1 of 41. Prepare and estimate
Deduplicate inputs, build JSONL with custom_id, run a pilot and extrapolate cost and failure rate.
- Set
- budget and abort rule
When to use it & trade-offs
What it is
Batch inference runs a large set of LLM requests offline (classifying a document archive, summarising a backlog, generating embeddings or synthetic data, running evals) where nobody waits for each answer. Because latency doesn't matter, you can pack requests for maximum throughput, use cheaper batch tiers (hosted providers commonly offer around 50% discounts in exchange for a completion window of up to 24 hours; check current terms) or run your own GPUs at high batch sizes. A good pipeline handles chunking, submission, polling, partial failures, retries, validation and idempotent result writes.
Why it matters: Many valuable LLM workloads are bulk jobs, and running them through the real-time path is slow and expensive: you hit rate limits, compete with interactive traffic and pay full price. Batch processing cuts cost, avoids throttling and isolates user-facing latency from background work, but it needs engineering around failure, cost estimation and data quality because a single bad prompt template can waste a day and a large bill.
When to reach for it
- Classifying or extracting from large archives
- Embedding backfills and synthetic data generation
- Running evals and LLM judges over large sets
When to avoid or be careful
- Launching a full job without a pilot
- Assuming results come back in order
- Putting bulk traffic through the same limits as the user-facing path
Ways to run bulk LLM work
Strengths: About half price; separate quotas; no GPUs to run.
Watch out: Up to 24 h turnaround; limited control.
Strengths: Maximum throughput; control; cost at scale.
Watch out: You manage GPUs and fault tolerance.
Strengths: Simple; immediate results.
Watch out: Rate limits; full price; competes with interactive traffic.
Interview signals & numbers to know
When this topic comes up
- “We need to process millions of documents”
- “We keep hitting rate limits”
- Batch API discount
- Offline throughput
- Resumable jobs
Benchmarks & rules of thumb
- $1,560 → $780 → $686
- real-time, batch tier and batch plus dedupe cost
- ~6M tokens/min
- rate needed to finish 8.6B tokens in 24 h in real time
- 0.3%
- example failure rate to retry
Common mistakes & follow-ups
Common interview mistakes
- Skipping validation and loading malformed outputs into a database.
- Not capping max_tokens and paying for rambling outputs.
- Rerunning a whole job after one shard fails instead of resubmitting only failures.
Likely interviewer follow-ups
- How would you process 10 million documents with an LLM?
- How do you handle partial failures in a batch job?
- When is a batch API better than self-hosting?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Batch Inference with generative AI interview Q&A and hands-on practice.