Sub topic 2
Workloads that fit offline processing
This chapter assumes you can call a chat completions API from Python, read and write JSON Lines files, and know roughly what tokens and rate limits are. It does not cover the request file format or job submission. Those come in later chapters. Here the question is which of your workloads should go through a batch API at all.
The test: who is waiting, and for how long?
A batch API accepts a file of many requests and returns results later. In the OpenAI example used in this tutorial, the job is given a 24-hour completion window. Many jobs finish sooner, but the window is the only timing you can plan around. Your workload fits if nobody needs any single answer within that window.
Four questions decide most cases:
- Is a person or a live system waiting on the response? If so, use a synchronous call.
- Can the whole job finish up to a day late without harm? If not, batch is the wrong tool.
- Are the requests independent of each other? A batch runs all requests without waiting on one another. Request B cannot use the output of request A in the same batch.
- Is the job large enough to justify the extra moving parts? Uploading files, polling, and matching results add code. A handful of requests does not repay it.
Workloads that fit well
The common thread is a pile of work that already exists and has no deadline per item.
Classification and labeling
You have a backlog of support tickets, product reviews, or emails and want each tagged with a category, sentiment, or priority. Every item is processed by the same prompt, items do not depend on each other, and the result goes into a table. This is the standard batch workload.
Summarization of existing content
Summarizing archived meeting transcripts, knowledge base articles, or research papers is a good fit. The documents already exist, and the summaries are read later. The example in this tutorial, one-sentence summaries of documents keyed by ID, is a small version of this.
Structured extraction
Pulling fields such as dates, amounts, names, or addresses out of invoices, contracts, or free-text forms. Extraction often runs over a large historical corpus once, then incrementally over new documents. Both patterns suit batch.
Evaluation runs
Running a test set through a candidate model or prompt, or using a model as a judge to grade outputs, rarely needs instant results. Evaluation suites often contain thousands of cases, and you compare several prompt variants against each other. Batch makes these runs cheaper, so you can afford to run them more often.
Synthetic data and dataset enrichment
Generating paraphrases, test inputs, or training examples, or adding a generated description to every row of a catalog. Each row is independent, and the output goes to storage, not to a user.
Backfills after a prompt or model change
If you change your prompt or move to a newer model, existing records may need reprocessing. A backfill is a large job with a natural deadline of "sometime this week", which suits batch well.
Workloads that do not fit
Interactive features
Chat assistants, autocomplete, and inline suggestions need a response in seconds. A batch has no latency guarantee shorter than its window, so it cannot serve them.
Dependent, multi-step chains
Suppose step two needs the output of step one, as in "extract the claims, then verify each claim". You cannot put both in one batch, because step two's input does not exist when the batch starts. You can still batch each stage separately. Submit all step-one requests, wait for the results, build the step-two file from them, and submit again. Each stage adds up to one completion window, so a five-stage chain can take days in the worst case. Decide whether that delay is acceptable before you commit.
Agent loops and tool use
An agent decides its next call based on the last result. That is the dependent chain problem at its most severe. Batch does not suit agent loops that run one request at a time.
Time-sensitive decisions
Fraud checks at payment time, moderation before a post goes live, and alerts that must fire quickly cannot wait a day. Moderation is a useful case to think through. Live moderation needs synchronous calls. A nightly re-review of older content for policy updates can use batch.
Small or exploratory jobs
When you are iterating on a prompt with a dozen examples, you want immediate feedback. Use synchronous calls while you design the prompt, then switch to batch to run the full set.
Edge cases that change the answer
Mixed workloads. Many products have both halves. A support tool classifies a ticket synchronously when it arrives so it can route it, and it batches the weekly re-analysis of all tickets for trend reports. Treat these as two workloads with two code paths, and share the prompt text between them so the labels stay consistent.
Deadline-driven jobs. "Not urgent" is different from "has a deadline". If a report is due Monday morning and you submit Sunday night, a slow batch will miss it. Submit with margin: plan on the full window, and leave time for retries of failed requests, which add another round trip.
Rate-limit-bound jobs. If a synchronous run would take hours because of rate limits, with retries and backoff code to manage, batch can be simpler. The provider schedules the work for you. Check the batch quotas too, because they are separate from your real-time limits and are covered in a later chapter.
Data that goes stale. If the input changes while the job is queued, results may describe outdated data. Store a version or timestamp with each input so you can detect this when results return.
Prompt changes mid-flight. A submitted batch uses the prompts in its file. If you discover a prompt bug after submitting, you must cancel and resubmit, not patch the job. Testing on a small sample first, the subject of a later chapter, reduces this risk.
Sensitive or regulated data. Batch input files are uploaded and stored by the provider for a period. Check your data handling terms before sending anything restricted, the same as you would for synchronous calls.
Encoding the decision
Teams often make this choice informally and inconsistently. Writing the rules down as code makes them reviewable, and you can reuse the function in a job launcher that refuses to submit work that does not fit. The thresholds below are starting points, so adjust them for your own overhead.
from dataclasses import dataclass
@dataclass
class Workload:
name: str
user_waiting: bool
max_delay_hours: float
requests: int
independent: bool
def recommend(w: Workload, window_hours: float = 24, min_requests: int = 100) -> str:
if w.user_waiting:
return "synchronous: a user is waiting"
if w.max_delay_hours < window_hours:
return "synchronous: delay budget is shorter than the batch window"
if not w.independent:
return "batch one stage at a time: requests depend on each other"
if w.requests < min_requests:
return "synchronous: too small to justify batch overhead"
return "batch"
workloads = [
Workload("chat assistant", True, 0.0, 1, True),
Workload("tag 50,000 archived tickets", False, 72, 50_000, True),
Workload("fraud check at checkout", False, 0.01, 1, True),
Workload("extract then verify claims", False, 96, 2_000, False),
Workload("prompt tryout on 12 samples", False, 48, 12, True),
]
for w in workloads:
print(f"{w.name}: {recommend(w)}")Running this prints one verdict per workload. The ticket-tagging job gets "batch". The chat assistant, the fraud check, and the 12-sample tryout stay synchronous. The claims pipeline is split into stages.
Summary
Choose batch when the work already exists, items are independent, and a delay of up to the completion window harms nobody. Typical cases are classification, summarization, extraction, evaluation runs, dataset enrichment, and backfills. Choose synchronous calls for anything interactive, time-critical, small, or dependent on earlier outputs. For multi-stage work, you can batch stage by stage if you accept the added delay.
Exercise
A team wants to (a) show an instant summary when a user uploads a PDF, (b) summarize 200,000 archived PDFs for a search index, and (c) run a three-step pipeline where step two uses step one's output on 5,000 documents. For each, say whether it fits batch and why.
Show answer
(a) Does not fit. A user is waiting, so use a synchronous call. (b) Fits well. The documents already exist, requests are independent, the volume is large, and no one needs any single summary within a day. (c) Fits only stage by stage. Step two's input does not exist until step one finishes, so you submit step one as a batch, build the step-two file from its results, then submit that. Each stage can take up to the full completion window, so accept the added delay before choosing this design.
Exercise
Your report is due Monday at 09:00. You plan to submit a 10,000-request batch on Sunday at 22:00 with a 24-hour window. What is the risk, and what would you change?
Show answer
The window runs until Monday 22:00, well past the deadline, and failed requests would need a second round trip on top of that. Either submit earlier with margin for the full window plus retries, or split the work so the part the report needs is processed synchronously or submitted much sooner.