Sub topic 1
Why batch? Synchronous calls versus asynchronous jobs
Prerequisites
This chapter assumes you can do the following:
- Write basic Python, including reading and writing files and working with JSON.
- Call an LLM chat or messages API and read the response.
- Read JSON Lines, a format with one JSON object per line.
- Explain what a token is and what an API rate limit does.
You do not need any prior experience with batch APIs. The later chapters build the JSONL request file, the submit-and-poll loop, and the result handling. This chapter explains the model behind them, so you can decide when a batch is the right tool.
Two ways to run the same request
A synchronous call sends one request and holds the connection open until the model answers. Your code blocks on that call. When it returns, you have the result or an error. Most LLM tutorials use this style, and it is the right choice for chat interfaces, autocomplete, and any feature where a person is waiting.
A batch job is asynchronous. You collect many requests into a file and upload it. You then create a job that refers to the file, and the provider runs the requests on its own schedule. Your code does not wait on any single request. You check the job's status from time to time, and when the job finishes you download a file of results.
The request body is the same in both modes. A chat completion request that works in a synchronous call also works as a line in a batch file. What changes is the delivery contract: when you get the answer, how much you pay, and how you match answers to questions.
What you give up and what you get
Batch processing is a trade. You accept a looser timing guarantee and a more complex workflow. In return you get lower prices and room to run more work than a real-time rate limit would allow.
| Property | Synchronous call | Batch job |
|---|---|---|
| Time to first result | Seconds | Minutes to the full completion window |
| Completion guarantee | Immediate success or error | Within a window, such as 24 hours |
| Price | Standard rate | Often discounted. OpenAI lists 50% off |
| Rate limits | Per-minute limits on your account | Separate, larger queue limits |
| Result order | Matches your call order | Not guaranteed. Match by `custom_id` |
| Error handling | Exception per call | Per-request errors inside the job |
| Streaming | Supported | Not available |
Check the current pricing page before you plan a budget. Discounts and limits change, and they differ by model and provider.
Two points in the table deserve more detail.
First, the completion window is an upper bound, not a typical duration. Many small batches finish in minutes, but the provider promises only that the job will end within the window. If it does not, the job reaches an expired status. Design as if every job might take the whole window.
Second, batch capacity is separate from your synchronous rate limits. A job of 50,000 requests does not consume your per-minute request budget, so a batch does not slow down your live traffic. This separation is often as useful as the discount.
A decision rule
Ask three questions about a workload.
- Is anyone waiting on the answer? If a user is blocked until the response arrives, use a synchronous call.
- Can the result be late by hours without harm? If it can, batch is a candidate.
- Is the volume large enough to justify extra machinery? A batch has overhead: file preparation, polling, and result matching. Ten requests rarely repay that cost. Thousands often do.
Typical fits for batch:
- Classifying or tagging a backlog of documents.
- Summarizing an archive.
- Extracting structured fields from many records.
- Running an evaluation set against a model or a prompt change.
- Generating embeddings or synthetic training data overnight.
Typical misfits:
- Chat, where each turn depends on the previous answer and a user is waiting.
- Agent loops, where each step needs the output of the last step before the next request can be built.
- Workloads where the next request depends on a result, unless you can run the pipeline in stages, with one batch per stage.
The last case matters. A multi-step job can still use batches if each stage is independent across items. For example, you can summarize 10,000 documents in one batch, then classify the summaries in a second batch. The stages run one after another, but within each stage the items run in parallel.
A cost estimate
Suppose you must summarize 200,000 support tickets. Each request has 600 input tokens and produces 80 output tokens. That is 120 million input tokens and 16 million output tokens in total.
The following script estimates the cost under both modes. The prices are placeholders chosen to keep the arithmetic easy to follow. Replace them with the current prices for your model.
requests = 200_000
input_tokens_each = 600
output_tokens_each = 80
# Placeholder prices in dollars per million tokens. Use your provider's real prices.
input_price = 0.15
output_price = 0.60
batch_discount = 0.50
input_total = requests * input_tokens_each / 1_000_000
output_total = requests * output_tokens_each / 1_000_000
sync_cost = input_total * input_price + output_total * output_price
batch_cost = sync_cost * (1 - batch_discount)
print(f"Input tokens: {input_total:,.0f} million")
print(f"Output tokens: {output_total:,.0f} million")
print(f"Synchronous: ${sync_cost:,.2f}")
print(f"Batch: ${batch_cost:,.2f}")
print(f"Saved: ${sync_cost - batch_cost:,.2f}")With these numbers the synchronous run costs $27.60 and the batch run costs $13.80. The saving is real but small in absolute terms. At larger scale, or with a more expensive model, the same 50% applies to a much larger bill. The discount is a fixed fraction, so the benefit grows in proportion to your spend.
The calculation leaves out engineering cost. If a batch pipeline takes a day to build and your job runs once, the saving may not pay for the time. If the job runs every night, it will.
Why you cannot treat a batch as a slow loop
A common first attempt at offline work is a for loop that makes one synchronous call per item. It is simple, and for a few hundred items it is fine. It breaks down in several ways at scale.
- Rate limits. The loop runs into per-minute request and token limits. You must add sleeps, backoff, and retry logic, and you still share the budget with live traffic.
- Process lifetime. A loop that runs for six hours must survive crashes, network drops, and deploys. If it dies at item 41,000, you need your own record of progress.
- Cost. You pay the full synchronous price for work that could have waited.
- Concurrency code. To go faster you add threads or async code, which brings its own bugs: dropped results, duplicate calls, and unbounded queues.
A batch job moves these problems to the provider. The provider owns the queue, the scheduling, and the retries of its own infrastructure. Your code shrinks to three steps: build a file, submit it, and collect the results. The job continues to run if your process exits, because the job lives on the provider's side and you hold only its id.
That last property changes how you design the code. A batch pipeline is a sequence of short, restartable steps with state saved between them, not one long-running process. The final chapters of this tutorial build on that idea.
The shape of a batch workflow
Every provider's batch API follows the same outline, although names differ. The stages below map to the chapters that follow.
- Build the request file. Write one request per line. Give each request a unique
custom_idthat you choose. - Upload the file. The provider stores it and returns a file id.
- Create the batch. You name the file, the target endpoint, and the completion window. The provider returns a batch id.
- Wait. The job passes through statuses such as
validating,in_progress, andfinalizing, and ends in a terminal status. - Collect. You download an output file of successful results and, if some requests failed, an error file.
- Reconcile. You match every result to its input by
custom_id, find what is missing, and resubmit only that.
The state diagram shows the status path for an OpenAI batch. Other providers use different names for the same ideas.
Note that failed and completed describe the job, not each request. A job can be completed while some of its requests failed. Treat the job status as a gate that tells you when to read the results, and then inspect every request individually.
Edge cases to know early
Results arrive out of order. The output file does not follow the order of the input file. Never rely on line position. The custom_id field is the only supported link between a request and its result, which is why the next chapters spend time on it.
Partial success is normal. A batch of 10,000 requests can finish with 9,950 results in the output file and 50 entries in the error file. Some requests may also be missing from both files if the job expired before they ran. A correct pipeline accounts for all three groups.
Validation happens up front. The provider checks the file format and some limits when you create the batch. A malformed line or a duplicate custom_id can cause the whole job to fail in validating before any request runs. A small test run catches most of these problems cheaply.
One endpoint per batch. A batch targets a single endpoint, and every line must use it. You cannot mix chat completions and embeddings in the same job.
No streaming and no interaction. You cannot see a partial answer while it is generated, and you cannot change a request after it is submitted. To change it, cancel the job or submit a corrected one.
Data is stored. The uploaded file and the results sit on the provider's side until you delete them or they expire. If your data has retention rules, check them before you upload.
Summary of the decision
Use a synchronous call when a person or a program is waiting and the answer must arrive in seconds. Use a batch when the work is large, independent across items, and tolerant of delay. The saving in price and the separate capacity are the reasons. The cost is a workflow with more states: uploading, waiting, collecting, matching, and retrying. The rest of this tutorial shows how to build that workflow so it survives partial failure.
Exercise
A team has 40,000 product descriptions to translate into five languages. The results are needed by next Monday. Another feature on the same account answers customer questions in a live chat widget. Should the translations use a batch API or synchronous calls, and give two reasons beyond price?
Show answer
Use a batch API. The work is large and each item is independent. The deadline is days away, so a completion window of up to 24 hours is acceptable. Reasons beyond price: (1) batch capacity is separate from synchronous rate limits, so the translation run does not consume the request budget that the live chat widget needs; (2) the provider manages the queue and scheduling, so the job survives a crash or restart of your own process, and you do not write concurrency and backoff code. The chat widget should stay synchronous because users are waiting on each reply.
Exercise
Your job status is completed. The output file has 9,940 lines and the input file had 10,000 requests. Name two places the other 60 requests could be, and say how you would find out which one applies to each request.
Show answer
They could be in the error file, which lists requests that failed individually, or they could be missing from both files, for example because they did not run before a deadline or the job ended early. Build the set of all custom_id values you submitted, then subtract the ids found in successful output lines and the ids found in the error file. Ids in the error file failed with a recorded reason. Ids left over are missing. Resubmit both groups after deciding which errors are worth retrying.