Aller au contenu

Leçon 20 · Reliability and Cost

Batch API, Background Mode and Webhooks

Run large or slow OpenAI jobs with the Batch API and background mode: build JSONL files, match results by custom_id, poll status and verify webhooks.

Not every request has a person waiting. You may want to classify 20,000 old support tickets overnight, or run a long research task that takes many minutes. For these jobs, OpenAI offers two tools: the Batch API for many requests at once, and background mode for single long responses. Webhooks can tell your server when work is done.

Choose a tool

Need Tool
User is waiting Normal or streaming request
One slow response Background mode
Many independent requests, not urgent Batch API
Notification when done Webhooks, or polling

The Batch API

A batch is a JSONL file: one JSON request on each line. As of December 2026, the guide says batch requests cost 50% less than synchronous ones, and the completion window is 24 hours. Many finish sooner, but unfinished requests can expire.

Each line has a unique custom_id, a method, a url and a body.

JSON
{"custom_id": "ticket-1", "method": "POST", "url": "/v1/responses", "body": {"model": "gpt-6.2-sol", "input": "Classify: My card was charged twice."}}

A file can target only one model. The guide lists limits of up to 50,000 requests and 200 MB per file, and supported endpoints include /v1/responses, /v1/chat/completions, /v1/embeddings and /v1/moderations. There are also queued-token limits.

Python
# Read-only
batch_file = client.files.create(file=open("requests.jsonl", "rb"), purpose="batch")

batch = client.batches.create(
    input_file_id=batch_file.id,
    endpoint="/v1/responses",
    completion_window="24h",
)

batch = client.batches.retrieve(batch.id)
if batch.status == "completed":
    content = client.files.content(batch.output_file_id)

Also handle other final states, such as failed, expired or cancelled. Failed requests are listed in the error file, given by error_file_id.

Results can be out of order

The order of output lines may not match the input order. Match each result with its custom_id, never with its line number. Choose IDs that connect to your own records.

This runnable script builds the request lines and then merges made-up results that arrive out of order. The "outputs" are hand-written and simpler than real output lines.

Python Stand-in: build a batch and match results

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The loop goes through your list of tickets. So a request that is missing from both files is also noticed.

Make batch work safe

  • Test the prompt on a few normal requests first. A mistake repeated 50,000 times is expensive.
  • Save the batch ID and file IDs right away.
  • Make result processing idempotent, so running it twice causes no duplicate writes.
  • Resubmit only failed or missing items.
  • Delete input and output files when you no longer need them, especially if they contain personal data.

Background mode

For a single long request, set background=True. You get a response ID right away.

Python
# Read-only
import time

response = client.responses.create(
    model="gpt-6.2-sol",
    input="Write a detailed migration plan for our database.",
    background=True,
)

while response.status in ("queued", "in_progress"):
    time.sleep(5)
    response = client.responses.retrieve(response.id)

print(response.status)

Other final states include failed, incomplete and cancelled, so check before you use the result. You can cancel a background response by its ID.

Background mode has to keep the response for a while so that you can fetch it. The documentation says it stores response data temporarily even with store=False or Zero Data Retention. Check the data controls page before you send sensitive data.

As of December 2026, the guide also describes completion windows. The default runs as soon as possible. A 2-hour window gives a 30% discount and an 8-hour window a 40% discount on supported models, as a public beta. Those windows cannot be streamed. Check the current conditions.

Polling every few seconds with a growing delay and a final time limit is a reasonable start.

Webhooks

Instead of polling, you can register a webhook endpoint. OpenAI sends an HTTP POST to it when an event happens, such as a completed response. Anyone on the internet could send a fake request to your URL, so verify the signature.

Python
# Read-only: Flask-style handler
try:
    event = client.webhooks.unwrap(request.data, request.headers,
                                   secret=WEBHOOK_SECRET)
except openai.InvalidWebhookSignatureError:
    return "bad signature", 400

Follow these rules from the webhook guide:

  • Verify the raw request body, before you parse it.
  • Reply with a 2xx status quickly, and do slow work in a queue.
  • Expect retries: delivery can be repeated for up to 72 hours.
  • Use the webhook-id header to ignore duplicates.

A stored set of processed IDs, with a unique database constraint, handles duplicates well.

Keep polling as a backup. If a webhook is lost because your server was down for a long time, a scheduled job can check unfinished work.

Track jobs in your database

Do not keep job state only in memory. A restart would lose it, and you might submit the same work again and pay twice. Store a row for each batch or background response with your own job ID, the remote ID, the status, the time you created it and the number of attempts.

Store a second set of rows for the individual items, with their custom_id and state: pending, done or failed. A scheduled task can then check unfinished jobs, fetch results, mark items and alert a person when something has waited too long.

Split very large jobs into several smaller batches. A mistake then affects less work, partial results arrive sooner and you stay within limits. Before the full run, estimate the cost from a small sample: average tokens per item, multiplied by the number of items and the batch price. Compare the real usage afterwards.

Decide what happens to late results. If the source record changed or was deleted while the job ran, do not blindly write the old result over it.

Common mistakes

  • Using the same custom ID twice, so one result overwrites another.
  • Reading only the output file and never opening the error file.
  • Submitting a huge batch before testing a few lines of the same request body.
  • Doing slow work inside the webhook handler, which causes timeouts and repeated deliveries.

Finally, open a sample of the finished results yourself. A batch can complete without any error and still give poor answers, so apply the same validation rules that you use for live requests before you save anything.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. How should you match batch results to requests?

    Output order may differ from input order.
  2. 2. What discount does the Batch API give, as of December 2026?

    The batch guide states a 50% discount.
  3. 3. Why verify webhook signatures?

    Without verification, anyone could post fake events to your endpoint.
  4. 4. What should your webhook handler do with duplicate deliveries?

    Retries can deliver an event more than once.

Summary

  • Use batch for many non-urgent requests and background mode for slow single ones.
  • Match results by custom_id, and handle errors and expiry.
  • Test small, save IDs and make processing idempotent.
  • Verify webhook signatures, answer quickly and ignore duplicates.
  • Discounts and windows change, so check the current docs.

Next: Safety and Moderation

Votre progression est enregistrée dans ce navigateur. Aucun compte nécessaire.