Skip to content
AgenticAIWiki
  1. Learn
  2. Part 13
  3. 68. Serving patterns
  4. 68.4

Lesson 68.4 · 4 of 5 · 4 min read · Reviewed 24 Nov 2026

Batch processing for offline work

By the end, you can

  • Use batch processing for offline work.
  • Decide what belongs in batch versus real time.

Not every model call has a person waiting. For those, batch processingMessage Batches: An asynchronous API for submitting many requests at once, processed at a discount, with results collected later. is usually cheaper and simpler.

Good batch jobs

  • Backfilling labels, summaries or embeddingsEmbedding: A list of numbers (a vector) that represents the meaning of a piece of text, so similar meanings land close together. for old data
  • Nightly reports and digests
  • Running eval suitesEval suite: A versioned collection of eval cases, graders and thresholds run on every prompt, model or code change. (Part 3)
  • Bulk content moderationContent moderation: Classifying inputs or outputs for harmful or policy-violating content. review
  • Translating a document archive

Design

Concern Approach
Identity Give each item a stable custom id, such as the ticket id
Size Split into batches within the provider’s limits
Partial failure Results come back per item; collect failures and resubmit only those
Ordering Don’t assume results come back in order; join on the id
Idempotency Writing a result twice must be harmless
Cost tracking Tag the job so its spend shows up as its own line

Batch versus real time

A simple test: if the answer arrived in a few hours instead of a few seconds, would anyone notice? If not, it’s a batch job.

Some features split: answer the user in real time with a fast model, then run a deeper batch analysis overnight.

On other providers

OpenAI’s Batch API and Gemini’s batch mode work the same way: upload many requests, collect results within about a day, at roughly half the standard price. Check the current discount, size limits and turnaround on each provider’s pricing page before you plan capacity around them.

Key points

  • Work nobody is waiting on (nightly tagging, backfills, eval runs) can go through a batch interface.
  • Batch trades latency for lower cost and higher throughput.
  • Design for partial failure: each item has its own id and result, and failed items are retried alone.
Hands-on labRuns in the Playground

Retry only the failed batch items

Process a batch where some items fail, matching results by id and retrying just the failures.

You will have: A batch loop that finishes all 100 items with the fewest calls.

Steps

  1. Run the starter and note how many calls it sends.
  2. Read why results are keyed by custom_id rather than position.
  3. Resubmit only the items that failed in the previous attempt.
  4. Run again and compare the number of calls sent.
  5. Add a sixth failing id and check it is retried alone.

Done when

  • The output says done 100 of 100 items.
  • The solution sends 106 calls, not hundreds.
  • ticket-003 is labelled billing, matched by id even though results arrive reversed.

Open in the Playground No API key needed.

Starter code (Python)
# Run a batch, match results by custom_id, and resubmit only the failures.
class TransientError(Exception):
    pass


FAILS = {"ticket-017": 1, "ticket-034": 1, "ticket-051": 2, "ticket-068": 1, "ticket-085": 1}
calls = {"sent": 0}


def classify(item, attempt):
    calls["sent"] += 1
    if FAILS.get(item["custom_id"], 0) >= attempt:
        raise TransientError("overloaded")
    return "billing" if "charge" in item["text"] else "other"


def run_batch(items, attempt):
    """Returns results keyed by custom_id, in no particular order."""
    results = {}
    for it in reversed(items):  # results do not come back in the order sent
        try:
            results[it["custom_id"]] = {"ok": True, "label": classify(it, attempt)}
        except TransientError as e:
            results[it["custom_id"]] = {"ok": False, "error": str(e)}
    return results


ITEMS = [{"custom_id": f"ticket-{i:03d}", "text": "double charge" if i % 3 == 0 else "late parcel"} for i in range(1, 101)]
final, pending = {}, ITEMS
for attempt in (1, 2, 3):
    if not pending:
        break
    res = run_batch(pending, attempt)
    final.update({cid: r for cid, r in res.items() if r["ok"]})
    failed = [it for it in pending if not res[it["custom_id"]]["ok"]]
    # TODO: resubmit only the failed items. This resends everything until nothing fails.
    pending = ITEMS if failed else []
    print(f"attempt {attempt}: failed {len(pending)}")

print(f"done {len(final)} of {len(ITEMS)} items, {calls['sent']} calls sent")
print("ticket-003 ->", final["ticket-003"]["label"])
Show a solution
# Run a batch, match results by custom_id, and resubmit only the failures.
class TransientError(Exception):
    pass


FAILS = {"ticket-017": 1, "ticket-034": 1, "ticket-051": 2, "ticket-068": 1, "ticket-085": 1}
calls = {"sent": 0}


def classify(item, attempt):
    calls["sent"] += 1
    if FAILS.get(item["custom_id"], 0) >= attempt:
        raise TransientError("overloaded")
    return "billing" if "charge" in item["text"] else "other"


def run_batch(items, attempt):
    """Returns results keyed by custom_id, in no particular order."""
    results = {}
    for it in reversed(items):  # results do not come back in the order sent
        try:
            results[it["custom_id"]] = {"ok": True, "label": classify(it, attempt)}
        except TransientError as e:
            results[it["custom_id"]] = {"ok": False, "error": str(e)}
    return results


ITEMS = [{"custom_id": f"ticket-{i:03d}", "text": "double charge" if i % 3 == 0 else "late parcel"} for i in range(1, 101)]
final, pending = {}, ITEMS
for attempt in (1, 2, 3):
    if not pending:
        break
    res = run_batch(pending, attempt)
    final.update({cid: r for cid, r in res.items() if r["ok"]})
    pending = [it for it in pending if not res[it["custom_id"]]["ok"]]
    print(f"attempt {attempt}: failed {len(pending)}")

print(f"done {len(final)} of {len(ITEMS)} items, {calls['sent']} calls sent")
print("ticket-003 ->", final["ticket-003"]["label"])
Quick checkYou need to classify 2 million old support tickets by next week. What is the best approach?
How sure are you?
Pick an answer and how sure you are