Sub topic 12
Batch non-urgent work
This chapter assumes you can call an LLM API from Python, read JSON and JSONL, and know that input and output tokens are priced separately. It builds on the cost arithmetic from the tokens and pricing chapter.
Many LLM workloads have no user waiting on the answer. Examples are nightly classification of support tickets, embedding-style enrichment of a catalog, summarizing last week's documents, and running an evaluation set. For this work you can trade latency for price and throughput.
Three things called "batching"
The word covers three different techniques, and mixing them up leads to wrong expectations.
| Technique | What it does | Where it runs | Main benefit |
|---|---|---|---|
| Provider batch API | You upload many requests. The provider processes them asynchronously and returns results later. | Provider | Lower price per token and separate rate limits |
| Request packing | You put several items into one prompt and ask for several answers. | Your code | Shared instructions are paid for once |
| Continuous batching | A server groups concurrent requests on the same GPU. | Self-hosted serving stack | Higher hardware utilization |
This chapter covers the first two. Continuous batching is a serving-side technique, covered in the last chapter.
Provider batch APIs
Several major providers offer a batch endpoint. The pattern is the same across them:
- Write one request per line to a JSONL file. Each line carries a
custom_idthat you choose. - Upload the file and create a batch job.
- Poll the job status, or wait for a notification.
- Download an output file and match results to inputs by
custom_id.
Providers typically offer a discount on token prices in exchange for a completion window. That window is often up to 24 hours, though many batches finish sooner. They also often count batch traffic against a separate rate-limit pool, so a large backfill does not starve your live traffic. Exact discounts, windows, size limits, and supported models differ by provider and change over time. Check current documentation before you plan around a number.
The key trade-off is that you give up control of when results arrive. Treat the completion window as the worst case, and design the pipeline so that nothing downstream blocks on it.
Estimating the saving
Take the placeholder prices from earlier chapters: 1.00 USD per million input tokens and 4.00 USD per million output tokens. Suppose a nightly job processes 10,000 documents at about 800 input tokens and 150 output tokens each.
- Input: 10,000 × 800 = 8,000,000 tokens, which costs 8.00 USD.
- Output: 10,000 × 150 = 1,500,000 tokens, which costs 6.00 USD.
- Live total: 14.00 USD per run.
With a 50% batch discount (an assumption, not a promise), the same run costs 7.00 USD. Over 30 nights that saves about 210 USD. The saving is proportional to volume, so batching matters most for large, recurring jobs and little for a few hundred requests a day.
Building a batch file
The line format below follows a common convention: a custom_id, then a request body. Field names vary by provider, so adapt it to the one you use.
import json
def build_batch_file(items, model, system_prompt, path, max_tokens=200):
"""Write one request per line. items maps custom_id -> input text."""
with open(path, "w", encoding="utf-8") as f:
for custom_id, text in items.items():
request = {
"custom_id": custom_id,
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": model,
"max_tokens": max_tokens,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": text},
],
},
}
f.write(json.dumps(request) + "\n")
items = {f"doc-{i}": f"Text of document {i}" for i in range(3)}
build_batch_file(items, "example-model", "Classify the sentiment.", "batch_input.jsonl")
print(open("batch_input.jsonl", encoding="utf-8").read())Use stable, meaningful IDs such as a database primary key. Output order is generally not guaranteed to match input order, so the custom_id is the only reliable link back to your data.
Handling partial failure
A batch of 10,000 requests will rarely succeed uniformly. Some lines may fail with errors, expire, or return output that does not parse. Your collector must separate successes from failures and resubmit only the failures.
import json
def collect_results(lines):
"""Split output lines into results by custom_id and a list of ids to retry."""
ok, retry = {}, []
for line in lines:
row = json.loads(line)
if row.get("error") or not row.get("response"):
retry.append(row["custom_id"])
else:
ok[row["custom_id"]] = row["response"]
return ok, retry
sample = [
'{"custom_id": "doc-0", "response": {"text": "positive"}, "error": null}',
'{"custom_id": "doc-1", "response": null, "error": {"code": "timeout"}}',
'{"custom_id": "doc-2", "response": {"text": "negative"}, "error": null}',
]
ok, retry = collect_results(sample)
print(len(ok), "succeeded; retry:", retry)Also compare the set of IDs you submitted with the set you received. A missing ID with no error line is a failure too. Resubmitting is safe only if the work is idempotent, meaning that running it twice gives an acceptable result and does not duplicate side effects such as sending an email.
Request packing
Packing puts several items in one request:
Classify each review below. Reply with a JSON list of objects
{"id": ..., "label": ...}, one per review.
[1] The battery died in a day.
[2] Fast shipping, works as described.The saving is the repeated instruction. If your instructions and examples take 500 tokens and each item takes 200, ten separate requests send 10 × 700 = 7,000 input tokens. One packed request sends 500 + 2,000 = 2,500. If the shared prefix is long and stable, provider prompt caching can recover much of the same saving without packing.
Packing has costs of its own:
- Quality can drop. Models may mix up items, skip one, or be influenced by neighboring items. Run your evaluation set on the packed format before adopting it.
- Failures are coarser. One malformed answer can invalidate the whole response, so validate the output and fall back to single-item calls.
- Output limits apply. The total answer must fit within your
max_tokenssetting. Output tokens cost more, so the saving is mostly on the input side. - Latency grows. One long generation takes longer than several short ones run in parallel.
Packing and a provider batch job can be combined, but test each change separately so you can tell which one affected quality.
When not to batch
- A person or a calling service is waiting for the result.
- Results must arrive within minutes, and the batch window is hours.
- The job is small, and the engineering cost outweighs the discount.
- Each step depends on the previous answer, as in an agent loop. You cannot batch dependent calls without splitting the work into stages.
For work that is not urgent but is too time-sensitive for a batch window, use bounded concurrency with retries, as in the concurrency chapter.
Checklist
- Confirm that no user is waiting and that the batch window fits your deadline.
- Run a ten-line live sample and check the output format.
- Re-run your evaluation set, because batch jobs use the same models and the same quality risks.
- Submit with stable
custom_idvalues. - Reconcile submitted and received IDs, and retry only the failures.
- Record tokens and cost per batch, so the saving shows up in your monitoring baseline.
Exercise
A nightly job sends 20,000 requests, each with a 600-token input and a 100-token output. Prices are 1.00 USD per million input tokens and 4.00 USD per million output tokens. The provider's batch API gives a 50% discount. What does one run cost live and as a batch? Then name one reason you might still keep part of the job on live calls.
Show answer
Input is 20,000 × 600 = 12,000,000 tokens, which costs 12.00 USD. Output is 20,000 × 100 = 2,000,000 tokens, which costs 8.00 USD. The live cost is 20.00 USD and the batch cost is 10.00 USD. You might keep some requests live if they have a tight deadline shorter than the batch window, or if a failed batch line must be fixed and returned quickly. A job where later steps depend on earlier answers also cannot be sent as one batch.
Exercise
You pack 20 short items into each request to save on a 400-token instruction. Accuracy on your evaluation set falls from 94% to 88%. What should you do?
Show answer
Do not adopt the packed format as it stands. Try fewer items per request, such as 5, and re-measure. Or return to one item per request and rely on prompt caching or a batch API discount for the savings. Compare the cost saved against the accuracy lost, using the threshold you set for the task.