Skip to content

Batch API in LLM Providers: Asynchronous Processing of Large Volumes

Cover: Batch API in LLM Providers: Asynchronous Processing of Large Volumes Batch API is a mode where requests to the model are sent not individually but in batches as a job file. The provider processes the batch asynchronously over hours and returns the result in a separate file. Compared to synchronous mode, the discount is usually 40–50%, but the cost is a delay: the response comes not in seconds but in minutes or hours.

When Batch API is Justified

The key criterion is the absence of a user waiting for a real-time response. If the task is scheduled or requested by an operator, the asynchronous mode provides direct savings.

Scenario Synchronous Mode Batch API
Chat with user Yes No
Mass classification of 10,000 records Expensive Optimal
Generation of meta-tags for a catalog Expensive Optimal
Dataset labeling for eval Expensive Optimal
Agent with tool calling Yes No

Limitation: Batch API does not support streaming and, as a rule, does not support tool calls. This is a pure request-response mode.

Input File Format

Most providers accept JSONL: one line—one task. Each line has a unique identifier, which is later used to match responses.

{"custom_id":"item-0001","method":"POST","url":"/v1/chat/completions","body":{"model":"model-name","messages":[{"role":"system","content":"Classify the product by category."},{"role":"user","content":"Product: wireless mouse"],"max_tokens":64}}
{"custom_id":"item-0002","method":"POST","url":"/v1/chat/completions","body":{"model":"model-name","messages":[{"role":"system","content":"Classify the product by category."},{"role":"user","content":"Product: mechanical keyboard"],"max_tokens":64}}

File requirements:

  • UTF-8 encoding without BOM;
  • each line is a valid JSON, without line breaks inside objects;
  • custom_id is unique within the file;
  • file size is limited (usually 100–200 MB), number of lines—tens of thousands.

Job Lifecycle

stateDiagram-v2
    [*] --> Validating: file uploaded
    Validating --> Failed: format error
    Validating --> InProgress: validation passed
    InProgress --> Completed: all lines processed
    InProgress --> Cancelling: cancellation
    Cancelling --> Cancelled
    Completed --> [*]
    Failed --> [*]

The job goes through states: validation, execution, completion. The provider returns a job identifier, which can be queried. Querying is the only way to know the status; webhooks are not supported by all.

Preparation and Submission

Python script: forming JSONL, uploading the file, creating the job, waiting for the result.

import json
import time
from pathlib import Path

from openai import OpenAI

class Client:
    def __init__(self):
        self.client = OpenAI()

    def build_jsonl(self, items: list[dict], path: Path) -> None:
        with path.open("w", encoding="utf-8") as f:
            for item in items:
                record = {
                    "custom_id": item["id"],
                    "method": "POST",
                    "url": "/v1/chat/completions",
                    "body": {
                        "model": "model-name",
                        "messages": [
                            {"role": "system", "content": "Classify the product."},
                            {"role": "user", "content": item["text"]},
                        ],
                        "max_tokens": 64,
                    },
                }
                f.write(json.dumps(record, ensure_ascii=False) + "\n")

    def submit(self, path: Path):
        uploaded = self.client.files.create(file=path.open("rb"), purpose="batch")
        job = self.client.batches.create(
            input_file_id=uploaded.id,
            endpoint="/v1/chat/completions",
            completion_window="24h",
        )
        return job.id

    def wait(self, job_id: str, interval: int = 60):
        while True:
            job = self.client.batches.retrieve(job_id)
            if job.status in {"completed", "failed", "cancelled", "expired"}:
                return job
            time.sleep(interval)

The polling interval should not be less than a minute: the status changes rarely, and extra requests consume limits.

Processing Results

The result is also JSONL. Each line contains custom_id and either a response or an error object. Lines can come in any order, so matching is necessary by custom_id.

import json

def parse_results(path: str) -> dict[str, str | None]:
    out: dict[str, str | None] = {}
    with open(path, encoding="utf-8") as f:
        for line in f:
            row = json.loads(line)
            cid = row["custom_id"]
            resp = row.get("response") or {}
            if resp.get("status_code") == 200:
                body = resp["body"]
                out[cid] = body["choices"][0]["message"]["content"]
            else:
                out[cid] = None
    return out

Lines with errors need to be collected separately and re-sent in a second batch. Error reasons are typical: exceeding max_tokens, invalid request, security filters triggered.

Errors and Retransmission

Error Type Cause Action
invalid_request_error Invalid request body Fix and resend
context_length_exceeded Input is too long Shorten input
rate_limit_error Limit exceeded Resend later
server_error Provider-side failure Resend

Retransmission is a new batch only with problematic custom_id. The logic should be built so that the result of each element is saved in the database by custom_id, not tied to the position in the file.

Limitations and Pitfalls

  • Completion Window. The provider gives a timeframe (usually 24 hours). If the job does not complete in time, it is marked as expired, and some lines may not be processed.
  • No Streaming. Partial output cannot be obtained.
  • No Tool Calling. Agent scenarios do not work in Batch API.
  • Prompt Caching. Prompt caching in asynchronous mode may not apply or work differently—this needs to be checked separately.
  • Idempotency. Resending the same custom_id creates a new record, not updates the old one.

Economics

A 50% discount looks attractive, but it needs to be calculated together with overhead costs: file preparation, intermediate result storage, retransmissions. For volumes less than a few thousand requests, the benefit may be eaten up by engineering time.

Practical rule: if the task is performed regularly and the volume exceeds 5,000 requests, Batch API pays off. For one-off runs on hundreds of records, synchronous mode with parallelism limitation is simpler.

Relation to Other Approaches

Batch API is not a replacement for batching within one request and not a replacement for caching. This is a separate mode that combines with both: cache reduces volume, batching reduces the number of calls, Batch API reduces the cost of the remaining ones.

For overall cost management, see practical cost optimization for LLM API and cost forecasting.