Sub topic 11
Respecting limits and splitting large workloads
A batch that is rejected at submission, or that stalls in a queue, costs you time without producing any output. This chapter covers the limits that cause this and a way to split a large job so each piece fits.
This chapter assumes you can build a JSONL request file, submit and poll a batch, and read output and error files, as covered in earlier chapters. It also assumes you know what a token is and what a rate limit does.
The limits you will meet
Batch APIs enforce several separate limits. A job can fit one and break another, so check all of them.
| Limit | What it caps | Typical failure |
|---|---|---|
| Requests per batch | Lines in one input file | Batch creation is rejected |
| Input file size | Bytes in one uploaded file | Upload or creation is rejected |
| Enqueued tokens per model | Total tokens waiting across all your active batches for one model | Batch moves to `failed` with a token-limit error |
| Concurrent batches or storage | Number of active jobs, or total stored files | Creation errors or old files blocking new ones |
| Completion window | Time the provider has to finish | Unfinished requests are `expired` |
At the time of writing, the OpenAI Batch API accepts up to 50,000 requests and 200 MB per input file. Anthropic's Message Batches API allows up to 100,000 requests or 256 MB per batch. Enqueued-token quotas vary by model and by account tier. Treat these numbers as examples and read the current documentation and your account's limits page before sizing a job.
Why the enqueued-token limit matters most
Request and size limits are fixed and easy to check before you submit. The enqueued-token limit is different, because it is shared. It counts every batch you currently have in flight for that model. If one batch already holds most of your quota, a second batch that would have fit alone can fail immediately.
The provider estimates tokens from your input, so you can't know the exact count in advance. The safest approach is to estimate tokens yourself, leave a margin, and submit chunks one at a time or in small groups.
Choosing a chunk size
A chunk is one input file that becomes one batch. Smaller chunks are safer, and larger chunks are simpler to manage. Consider these factors.
- Hard limits. Stay below the request and byte caps with a margin, for example 90 percent.
- Token quota. Keep each chunk well below the enqueued-token quota so that one chunk never blocks itself.
- Blast radius. If a whole batch fails or expires, you redo only that chunk. Smaller chunks mean less rework.
- Overhead. Each batch adds an upload, a creation call, polling, and two downloads. Thousands of tiny batches create more bookkeeping than they save.
- Turnaround. Chunks run independently. Several moderate chunks can finish sooner than one huge chunk, but only if quota allows them to run at the same time.
A practical default is a chunk of a few thousand to ten thousand requests, capped by estimated tokens. Adjust after a pilot run shows how long a chunk really takes.
Splitting a job in code
The function below reads requests from any iterable. It starts a new chunk when adding the next request would break any of three limits: request count, file size, or estimated tokens. It writes each chunk to a file with a deterministic name and records a manifest listing which custom_id values live in which file.
Deterministic names and a manifest matter. If the script crashes and restarts, it can tell exactly which chunks were already created and what each one contains.
import json
from pathlib import Path
MAX_REQUESTS = 45_000 # below a 50,000 cap
MAX_BYTES = 180 * 1024 * 1024 # below a 200 MB cap
MAX_TOKENS = 1_500_000 # set from your own enqueued-token quota
def estimate_tokens(request):
"""Rough estimate: about 4 characters per token, plus the output cap."""
body = request["body"]
prompt_chars = sum(len(m["content"]) for m in body["messages"])
return prompt_chars // 4 + body.get("max_tokens", 0)
def split_requests(requests):
"""Yield lists of (line, custom_id) pairs that each fit within the limits."""
chunk, size, tokens = [], 0, 0
for request in requests:
line = json.dumps(request) + "\n"
n_bytes = len(line.encode("utf-8"))
n_tokens = estimate_tokens(request)
if n_bytes > MAX_BYTES or n_tokens > MAX_TOKENS:
raise ValueError(f"{request['custom_id']} exceeds a chunk limit by itself")
would_overflow = (
len(chunk) >= MAX_REQUESTS
or size + n_bytes > MAX_BYTES
or tokens + n_tokens > MAX_TOKENS
)
if chunk and would_overflow:
yield chunk
chunk, size, tokens = [], 0, 0
chunk.append((line, request["custom_id"]))
size += n_bytes
tokens += n_tokens
if chunk:
yield chunk
def write_chunks(requests, out_dir="chunks"):
out = Path(out_dir)
out.mkdir(exist_ok=True)
manifest = {}
for index, chunk in enumerate(split_requests(requests)):
name = f"chunk-{index:04d}.jsonl"
with open(out / name, "w", encoding="utf-8") as f:
f.writelines(line for line, _ in chunk)
manifest[name] = [custom_id for _, custom_id in chunk]
(out / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
return manifest
if __name__ == "__main__":
sample = (
{
"custom_id": f"doc-{i:06d}",
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "Summarize the text in one sentence."},
{"role": "user", "content": f"Document number {i}."},
],
"max_tokens": 100,
},
}
for i in range(100_000)
)
manifest = write_chunks(sample)
print({name: len(ids) for name, ids in manifest.items()})With 100,000 small requests, the request-count cap decides the split, giving three chunks. With long documents, the token or byte limit decides it instead, and you get more chunks of fewer requests each.
A single request that is larger than a whole chunk can't be split by this function, so it raises an error. Handle that case in your own preprocessing, for example by truncating or splitting the document before it becomes a request.
Keep custom_id unique across chunks
Make custom_id unique across the whole job, not only inside one file. The provider only checks uniqueness within a batch, but your own result-merging code will key everything by custom_id. Ids such as doc-000417 derived from the source record work well. Ids derived from the chunk position, such as chunk3-line12, break as soon as you re-chunk.
Submitting chunks without blowing the quota
Submit chunks in a controlled way. The simplest safe strategy is to run one chunk at a time. A slightly faster one is to keep a small number of chunks active and start a new one when an earlier one reaches a terminal status.
import json
import time
from pathlib import Path
from openai import OpenAI
client = OpenAI()
TERMINAL = {"completed", "failed", "expired", "cancelled"}
def run_chunk(path):
with open(path, "rb") as f:
input_file = client.files.create(file=f, purpose="batch")
batch = client.batches.create(
input_file_id=input_file.id,
endpoint="/v1/chat/completions",
completion_window="24h",
metadata={"chunk": Path(path).name},
)
while batch.status not in TERMINAL:
time.sleep(60)
batch = client.batches.retrieve(batch.id)
return batch
manifest = json.loads(Path("chunks/manifest.json").read_text(encoding="utf-8"))
for name in manifest:
batch = run_chunk(Path("chunks") / name)
print(name, batch.id, batch.status, batch.request_counts)
if batch.status == "failed":
print("errors:", batch.errors)
breakThis loop stops on the first failed chunk so you can read batch.errors before spending more quota. A failed batch means the batch as a whole was rejected, usually for validation or quota reasons. This differs from individual request errors, which appear in the error file of a batch that reaches completed.
Edge cases and common mistakes
- Estimating tokens with a character count only. The
chars // 4rule is rough and works poorly for code, non-English text, and numbers. Use the provider's tokenizer, such astiktokenfor OpenAI models, when you are close to the quota. Otherwise keep a wide margin. - Forgetting the output side. Some providers count requested output tokens toward the quota, and others count only input. The function above adds
max_tokensso it errs on the safe side. Check how your provider counts. - Mixing models in one file. An OpenAI batch targets one endpoint, and each request names a model. Quotas are per model, so chunks that mix models are hard to size. Split by model first, then by size.
- Leaving old files behind. Uploaded input and output files count against storage limits. Delete files you have already downloaded and merged.
- Re-chunking after a partial run. If you change the chunk size after some chunks have run, the manifest no longer matches the results. Keep the manifest as the source of truth and build new chunks only from ids that have no result yet.
- Assuming all chunks finish in the same order. Chunks complete independently. Merge by
custom_id, never by chunk order. - Hitting the completion window. A batch that can't finish within its window ends as
expired, and the requests it did complete are still returned. Collect the partial output, then resubmit the rest as a new chunk.
A checklist before you scale
- Read the current request, size, and enqueued-token limits for your provider and model.
- Set chunk limits at about 90 percent of the hard caps, and below your token quota.
- Write a manifest that maps each chunk file to its
custom_idvalues. - Submit one chunk and confirm it completes before launching the rest.
- Delete downloaded files you no longer need.
Exercise
A batch you submit fails immediately with a token-limit error, although the file has only 8,000 requests and is far below the request and size caps. Name two likely causes and one fix for each.
Show answer
One cause is that other batches for the same model are still active and already use most of the enqueued-token quota. The fix is to wait for those batches to reach a terminal status, or submit chunks one at a time. A second cause is that the file's own estimated tokens, including long prompts or a large maxtokens, exceed the quota by themselves. The fix is to split the file into smaller chunks by estimated tokens, or lower maxtokens.
Exercise
Your manifest maps three chunk files to their custom_ids. Chunk 2 ended as expired, and its output file holds results for 70 percent of its requests. What do you do next?
Show answer
Download and merge the output and error files from chunk 2, keyed by custom_id. Compute the ids listed for chunk 2 in the manifest that have no result, then write those ids into a new chunk file and submit it as a new batch. Do not resubmit the whole chunk, because that would pay twice for the completed requests.