Batch Jobs, Budgets and Limits
Move work that can wait to a provider batch API and join its unordered results back by id, alert on budgets early enough to act by forecasting from recent spend, and stop one user or script from running up the bill with a per-user token bucket that reserves before each call and settles afterwards, using atomic reservations that hold across processes and survive calls that time out.
Contentsand lesson path
On this page
- Why it matters
- Batch APIs for work that can wait
- Budget alerts that arrive in time
- Per-user limits with a token bucket
- Reservations under concurrency and timeouts
- Check your understanding
- Apply it
- Review prompt
Lessons of Cost Control
- Where LLM Money Goes Concept · 15 min
- A Cost Report from Usage Logs Worked example · 20 min
- Lab: Prompt and Response Caching Lab · 25 min
- Lab: Choosing and Routing Models Behind an Evaluation Lab · 30 min
- Batch Jobs, Budgets and Limits Concept · 15 min
- Check: Cut Cost Without Breaking Quality Knowledge check · 10 questions
What you will learn
- Use batch processing for offline workloads and enforce budget alerts and per-user limits.
01. Why it matters
The levers so far make each request cheaper. This lesson is about the requests themselves: which need an answer now, how much a feature may spend in a month, and how much one user may use in a minute. In lesson 2, Lumen paid real-time prices for summaries nobody read until morning, saw its bill double without an alert, and found one script behind a quarter of the cost. The standard fixes are batch processing, budget alerts and per-user limits.
02. Batch APIs for work that can wait
A batch API accepts many requests at once, runs them when the provider has capacity and returns the results later, at a lower price. At the time of writing, Anthropic and OpenAI both charge half price for batches and promise results within 24 hours, usually much sooner; check the current documentation, because discounts and limits change.
Good candidates are nightly summaries, back-filling metadata and evaluation runs; anything a user waits for is not. Each request carries your own custom id, because results come back in any order and some fail: a request can error, be cancelled, or expire before the batch processes it.
"""Write one Message Batches request per ticket. Nothing is sent from here."""
import json
import os
MODEL = os.environ.get("BATCH_MODEL", "claude-haiku-5-5") # set your own
tickets = {f"ticket-{n:05d}": f"(text of support ticket {n})" for n in range(1, 501)}
with open("requests.jsonl", "w", encoding="utf-8") as f:
for ticket_id, text in tickets.items():
f.write(json.dumps({
"custom_id": ticket_id, # your key for joining results back
"params": {
"model": MODEL,
"max_tokens": 300,
"system": "Summarise the ticket in three short lines.",
"messages": [{"role": "user", "content": text}],
},
}) + "\n")
print(f"{len(tickets)} requests written to requests.jsonl")500 requests written to requests.jsonlWith the Anthropic Python SDK you pass these objects to client.messages.batches.create(requests=...), poll client.messages.batches.retrieve() until processing_status is ended, then read client.messages.batches.results(). OpenAI's Batch API takes an uploaded JSONL file instead, with custom_id, method, url and body on each line. To run the next step without a key, a stand-in writes a results file the way a provider would: shuffled, with a few failures.
"""Stand-in for the provider: results in a different order, some not succeeded."""
import json
import random
rng = random.Random(5)
with open("requests.jsonl", encoding="utf-8") as f:
ids = [json.loads(line)["custom_id"] for line in f]
rng.shuffle(ids) # results do not come back in request order
with open("results.jsonl", "w", encoding="utf-8") as f:
for n, custom_id in enumerate(ids):
kind = "errored" if n % 97 == 3 else "expired" if n % 131 == 7 else "succeeded"
result = {"type": kind}
if kind == "succeeded":
result["message"] = {"content": [{"type": "text", "text": "(summary)"}],
"usage": {"input_tokens": 410, "output_tokens": 62}}
f.write(json.dumps({"custom_id": custom_id, "result": result}) + "\n")"""Join batch results back to tickets by custom_id and list what to resubmit."""
import json
from collections import Counter
with open("requests.jsonl", encoding="utf-8") as f:
requests = {r["custom_id"]: r for r in map(json.loads, f)}
summaries, retry, kinds = {}, [], Counter()
with open("results.jsonl", encoding="utf-8") as f:
for line in f:
item = json.loads(line)
result, custom_id = item["result"], item["custom_id"]
kinds[result["type"]] += 1
if result["type"] == "succeeded":
summaries[custom_id] = result["message"]["content"][0]["text"]
else: # errored, expired or canceled: decide per type, then resubmit
retry.append(requests[custom_id])
missing = requests.keys() - summaries.keys() - {r["custom_id"] for r in retry}
print(dict(kinds))
print(f"{len(summaries)} summaries saved, {len(retry)} to resubmit, "
f"{len(missing)} missing")
print("first to resubmit:", sorted(r["custom_id"] for r in retry)[:3]){'succeeded': 490, 'errored': 6, 'expired': 4}
490 summaries saved, 10 to resubmit, 0 missing
first to resubmit: ['ticket-00023', 'ticket-00090', 'ticket-00091']Every request is accounted for: saved or queued for resubmission, none missing. Decide per failure type before resubmitting: an expired request can go into the next batch, while an errored one may carry a bug that a retry repeats. Batches combine with prompt caching, but they can run longer than five minutes, so Anthropic suggests the 1-hour cache lifetime for a prefix shared across a batch. Flag batch usage in your logs: its price differs.
03. Budget alerts that arrive in time
A budget is a monthly amount per feature, team or customer, computed from the same usage records as the cost report. Alerts help only if they arrive while there is time to act, so check two things daily: how much is spent, at thresholds such as 50%, 80% and 100%, and where the month will end at the current rate. Base that forecast on a recent window, because a month-long average reacts slowly to a change in the middle of the month. Send each alert once, to a named owner.
"""Budget alerts on spend so far and on a month-end forecast, each sent once."""
from dataclasses import dataclass, field
@dataclass
class BudgetMonitor:
name: str
monthly_budget: float
days_in_month: int
thresholds: tuple[float, ...] = (0.5, 0.8, 1.0)
daily: list[float] = field(default_factory=list)
sent: set[str] = field(default_factory=set)
def add_day(self, cost: float) -> list[str]:
self.daily.append(cost)
day, spent = len(self.daily), sum(self.daily)
recent = self.daily[-7:] # last week's rate reacts faster than the month's
forecast = spent + sum(recent) / len(recent) * (self.days_in_month - day)
due = [(f"{t:.0%} of budget used", spent >= t * self.monthly_budget)
for t in self.thresholds]
due.append(("forecast over budget", forecast > self.monthly_budget))
alerts = [label for label, hit in due if hit and label not in self.sent]
self.sent.update(alerts)
return [f"{self.name} day {day}: {a} (spent ${spent:,.0f}, "
f"forecast ${forecast:,.0f} of ${self.monthly_budget:,.0f})"
for a in alerts]
# One feature's daily spend in October: steady, then an agent launch on day 8.
monitor = BudgetMonitor("triage_agent", monthly_budget=500.0, days_in_month=31)
for cost in [9.0] * 7 + [21.0] * 24:
for alert in monitor.add_day(cost):
print(alert)triage_agent day 12: forecast over budget (spent $168, forecast $502 of $500)
triage_agent day 16: 50% of budget used (spent $252, forecast $567 of $500)
triage_agent day 24: 80% of budget used (spent $420, forecast $567 of $500)
triage_agent day 28: 100% of budget used (spent $504, forecast $567 of $500)The forecast warned on day 12, four days before the 50% alert and 16 days before the money ran out. Decide in advance what each alert triggers: more traffic to the small model, a lower max_tokens, offline work moved to a batch, or a pause for a feature that can wait; switching everything off at 100% is rarely right for a product people depend on. Provider spend limits per workspace are a last backstop: they stop every feature at once and, as Anthropic notes, batches can go slightly over them.
04. Per-user limits with a token bucket
A budget protects the month; a per-user limit protects you from one user in the next few minutes. The usual tool is a token bucket: each user's bucket holds up to a fixed number of tokens (the largest burst) and refills at a steady rate (the sustained use). A request proceeds only if the bucket holds enough tokens for it.
A request's real size is known only after the response, so reserve the worst case before the call (prompt tokens plus max_tokens) and settle afterwards, returning what the usage block shows was unused. When the bucket is short, answer HTTP 429 with a Retry-After header saying when enough tokens will be there.
"""Per-user token buckets: reserve before the call, settle with real usage after."""
import math
from dataclasses import dataclass
@dataclass
class TokenBucket:
capacity: float # the largest burst, in tokens
refill_per_s: float # the sustained rate
level: float = -1.0
updated: float = 0.0
def _refill(self, now: float) -> None:
if self.level < 0:
self.level = self.capacity # a new bucket starts full
self.level = min(self.capacity,
self.level + (now - self.updated) * self.refill_per_s)
self.updated = now
def reserve(self, tokens: int, now: float) -> float:
"""Take tokens and return 0, or return the seconds to wait."""
self._refill(now)
if tokens <= self.level:
self.level -= tokens
return 0.0
return (tokens - self.level) / self.refill_per_s
def settle(self, reserved: int, used: int) -> None:
self.level = min(self.capacity, self.level + reserved - used)
buckets: dict[str, TokenBucket] = {}
def admit(user: str, prompt_tokens: int, max_tokens: int, now: float) -> float:
bucket = buckets.setdefault(user, TokenBucket(capacity=20_000, refill_per_s=200))
return bucket.reserve(prompt_tokens + max_tokens, now)
# One script fires a 5,000-token request (4,000 prompt + 1,000 max output) every 2 s.
for n in range(8):
now = 2.0 * n
wait = admit("u-0042", 4_000, 1_000, now)
if wait:
print(f"t={now:>4.0f}s 429 Too Many Requests, Retry-After {math.ceil(wait)}s")
continue
used = 4_000 + 300 # the usage block says 300 output tokens were generated
buckets["u-0042"].settle(5_000, used)
print(f"t={now:>4.0f}s allowed, {buckets['u-0042'].level:>6,.0f} tokens left")t= 0s allowed, 15,700 tokens left
t= 2s allowed, 11,800 tokens left
t= 4s allowed, 7,900 tokens left
t= 6s allowed, 4,000 tokens left
t= 8s 429 Too Many Requests, Retry-After 3s
t= 10s 429 Too Many Requests, Retry-After 1s
t= 12s allowed, 900 tokens left
t= 14s 429 Too Many Requests, Retry-After 19sThe script gets its burst of four calls, then the refill rate of 200 tokens per second. Ordinary users never notice the limit; the script behind a quarter of Lumen's cost does. In production:
- Shared state. With several server processes, keep the buckets in shared storage and update them atomically, or each process grants its own full bucket; the next section shows how.
- Two limits. A bucket limits the rate; add a daily or monthly quota per user or plan for the total, and alert the account owner as it fills.
- Limit what is billed. Count tokens or cost, not requests: one request with a long document can cost as much as a hundred short ones.
05. Reservations under concurrency and timeouts
limits.py assumes one process handling one request at a time. Production breaks both assumptions:
- Concurrency. Two requests from one user arrive together; each reads the balance, sees enough for one call and subtracts, so both are admitted. In one asyncio process a check and a subtraction with no
awaitbetween them cannot interleave, and threads can share a lock, but several processes need the shared store to check and subtract in one step. - Unknown outcomes. A call times out, or the connection drops after the request was sent. The provider may still have run it and billed you, as the streaming lesson noted.
So give each call a reservation with an id and a state. Reserve atomically before the call, then move the reservation to one final state:
- reserved → settled when the response arrives: record the real usage and refund the rest.
- reserved → released only when you know the call never ran: the connection was refused, or the provider itself refused this one attempt before running it: a 400 validation error (not a content-filter refusal), a 429 rate limit, or an overload error (Anthropic 529
overloaded_error, OpenAI 503server_is_overloaded). Behind a gateway that retries or falls back to another model, or when an error arrives inside a stream that has started, you cannot know. - reserved → pending when the outcome is unknown. The full amount stays held until a reconciler settles or releases it.
"""Per-user token quota with atomic reservations for the processes on one host."""
import sqlite3
import time
import uuid
SCHEMA = """
CREATE TABLE IF NOT EXISTS quota (user_id TEXT PRIMARY KEY, remaining INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS reservations (
id TEXT PRIMARY KEY, user_id TEXT NOT NULL, amount INTEGER NOT NULL,
state TEXT NOT NULL, used INTEGER, created DOUBLE PRECISION NOT NULL
);
"""
def connect(path: str) -> sqlite3.Connection:
db = sqlite3.connect(path, timeout=5.0) # wait up to 5 s for another writer
db.executescript(SCHEMA)
return db
def reserve(db: sqlite3.Connection, user: str, amount: int) -> str | None:
"""Hold `amount` tokens and return a reservation id, or None when short."""
rid = uuid.uuid4().hex
with db: # one transaction: the check, the subtraction and the record
row = db.execute(
"UPDATE quota SET remaining = remaining - :n"
" WHERE user_id = :u AND remaining >= :n RETURNING remaining",
{"n": amount, "u": user},
).fetchall()
if not row:
return None
db.execute(
"INSERT INTO reservations VALUES (?, ?, ?, 'reserved', NULL, ?)",
(rid, user, amount, time.time()),
)
return rid
def mark_pending(db: sqlite3.Connection, rid: str) -> None:
"""Outcome unknown (timeout, dropped connection): keep the whole amount held."""
with db:
db.execute(
"UPDATE reservations SET state = 'pending'"
" WHERE id = ? AND state = 'reserved'",
(rid,),
)
def sweep_stale(db: sqlite3.Connection, max_age_s: float, now: float) -> int:
"""A worker died after reserve(): treat its old `reserved` rows as pending."""
with db:
return db.execute(
"UPDATE reservations SET state = 'pending'"
" WHERE state = 'reserved' AND created < ?",
(now - max_age_s,),
).rowcount
def settle(db: sqlite3.Connection, rid: str, used: int, state: str = "settled") -> bool:
"""Close a reserved or pending reservation once and refund what was not used."""
with db:
row = db.execute(
"UPDATE reservations SET state = ?, used = ?"
" WHERE id = ? AND state IN ('reserved', 'pending')"
" RETURNING user_id, amount",
(state, used, rid),
).fetchall()
if not row:
return False # already closed: running it again changes nothing
user, amount = row[0]
db.execute(
"UPDATE quota SET remaining = remaining + ? WHERE user_id = ?",
(amount - used, user),
)
return True
def release(db: sqlite3.Connection, rid: str) -> bool:
"""The call certainly never ran (see the rules above): refund it all."""
return settle(db, rid, 0, state="released")UPDATE … WHERE remaining >= :n RETURNING is the atomic step: of two concurrent calls, only one finds enough left; the other's update matches no row and reserve() returns None. The insert of the reservation is in the same transaction, so quota is never taken without a record. settle() changes only a reservation that is still reserved or pending and refunds in the same transaction, so it is idempotent on the reservation id: a second run, or a late response racing the reconciler, refunds nothing more. sweep_stale() covers a worker that crashed between reserve() and the outcome: run it every minute or so to turn reserved rows older than your longest call into pending.
SQLite suits processes on one machine with a local disk. If another writer holds the database past the 5-second busy timeout, reserve() raises sqlite3.OperationalError: treat that as a refusal, never as permission to call. Across servers, use PostgreSQL: this schema and these statements run there unchanged apart from the placeholder style of your driver (psycopg writes %(n)s and %s), at the default READ COMMITTED isolation level; at REPEATABLE READ or SERIALIZABLE the losing update raises a serialization error instead. The column is user_id because user is a reserved word in PostgreSQL. A short Redis Lua script is the other common choice.
The test below races two calls against a quota for exactly one, first with a check-then-write version and then with reserve(). Save it next to quota.py and run python test_quota.py:
"""Concurrent calls, a timeout, reconciliation, overload errors and a crashed worker."""
import os
import tempfile
import threading
import time
import quota
PATH = os.path.join(tempfile.mkdtemp(), "quota.db")
CALL = 4_000 + 1_000 # prompt tokens + max_tokens: the worst case of one call
def remaining(db) -> int:
sql = "SELECT remaining FROM quota WHERE user_id = 'u-0042'"
return db.execute(sql).fetchone()[0]
def naive_reserve(db, user, amount):
"""Check, then write: the race that atomic reservation removes."""
sql = "SELECT remaining FROM quota WHERE user_id = ?"
row = db.execute(sql, (user,)).fetchone()
time.sleep(0.05) # a slow request widens the gap between the check and the write
if row[0] < amount:
return None
with db:
db.execute("UPDATE quota SET remaining = remaining - ? WHERE user_id = ?",
(amount, user))
return "admitted"
def race(reserve_fn) -> list:
"""Run two calls at the same moment, each with its own connection."""
with quota.connect(PATH) as db:
db.execute("INSERT OR REPLACE INTO quota VALUES ('u-0042', ?)", (CALL,))
start, results = threading.Barrier(2), []
def worker():
db = quota.connect(PATH)
start.wait()
results.append(reserve_fn(db, "u-0042", CALL))
threads = [threading.Thread(target=worker) for _ in range(2)]
for t in threads:
t.start()
for t in threads:
t.join()
return [r for r in results if r]
db = quota.connect(PATH)
admitted = race(naive_reserve)
print(f"naive check-then-write: {len(admitted)} of 2 admitted, "
f"remaining {remaining(db)}")
admitted = race(quota.reserve)
assert len(admitted) == 1, admitted
print(f"atomic reserve: {len(admitted)} of 2 admitted, remaining {remaining(db)}")
rid = admitted[0]
quota.mark_pending(db, rid) # the provider call timed out: did it run?
state = db.execute("SELECT state FROM reservations WHERE id = ?", (rid,)).fetchone()[0]
assert state == "pending" and remaining(db) == 0
print(f"after a timeout: state {state}, remaining {remaining(db)}")
retry = quota.reserve(db, "u-0042", CALL) # a retry is a new call and needs its own
assert retry is None
print("retry while the first call is pending: refused")
for n in (1, 2): # the reconciler finds the call ran: 4,000 in, 300 out
changed = quota.settle(db, rid, used=4_300)
print(f"reconcile #{n}: changed={changed}, remaining {remaining(db)}")
assert remaining(db) == 700
for status in (529, 503): # "overloaded" from Anthropic and from OpenAI
user = f"u-{status}"
with quota.connect(PATH) as db2:
db2.execute("INSERT INTO quota VALUES (?, ?)", (user, CALL))
rid = quota.reserve(db, user, CALL)
quota.release(db, rid) # the provider refused this attempt: it never ran
retry = quota.reserve(db, user, CALL)
assert retry is not None
quota.settle(db, retry, used=4_300) # the retry succeeded
print(f"direct {status}: released, so the user's retry is admitted")
with quota.connect(PATH) as db2: # a worker reserves for another user, then crashes
db2.execute("INSERT INTO quota VALUES ('u-0099', ?)", (CALL,))
orphan = quota.reserve(db, "u-0099", CALL)
swept = quota.sweep_stale(db, max_age_s=120, now=time.time() + 300) # 5 minutes on
row = db.execute("SELECT state FROM reservations WHERE id = ?", (orphan,)).fetchone()
assert swept == 1 and row[0] == "pending"
print(f"crashed worker: {swept} stale reservation swept to {row[0]}")naive check-then-write: 2 of 2 admitted, remaining -5000
atomic reserve: 1 of 2 admitted, remaining 0
after a timeout: state pending, remaining 0
retry while the first call is pending: refused
reconcile #1: changed=True, remaining 700
reconcile #2: changed=False, remaining 700
direct 529: released, so the user's retry is admitted
direct 503: released, so the user's retry is admitted
crashed worker: 1 stale reservation swept to pendingThe check-then-write version admitted both calls and left the user 5,000 tokens in debt; the atomic version admitted one. After the timeout the reservation stayed pending with 5,000 tokens held, so the retry was refused, and reconciling twice changed the balance once. Direct 529 and 503 errors released their reservations, so the retries got through, and the sweep moved the crashed worker's reservation to pending.
A retry is a new provider call, so it needs its own reservation. The SDKs also retry on their own, twice by default for timeouts, 429 and 5xx errors, so one reservation could cover three billed attempts: create the client you use under reservations with max_retries=0, and retry in your own code with a new reservation, as in the retries lab.
A pending reservation needs an answer before a deadline that is longer than your usage report's delay. Look for evidence in this order:
- Your own record of the call: a gateway or proxy log, a response that a background task still received, or the request id you logged when a stream started. Settle at that usage.
- The provider's usage reports. They are totals per API key, model and time bucket, so they can confirm or rule out unexplained usage in a window but cannot name one request, and they lag: Anthropic's Usage and Cost Analytics API typically refreshes within 4 hours and can take 24. Release the reservation only when the report's
data_refreshed_atis later than the end of the window and the window shows no tokens beyond what you settled. - Nothing by the deadline, such as 48 hours: settle at the reserved amount and flag it in the cost report. Counting the worst case keeps the limit honest.
06. Check your understanding
07. Apply it
Finish the practice project for this skill:
- Run your evaluation set through your provider's batch API, join the results by custom id, and compare cost and pass rate with the real-time run from lesson 2.
- Put a per-user token bucket in front of your RAG API (in Redis if you run several processes), reserving prompt tokens plus
max_tokensand settling from the usage block; replay one user at ten times normal speed. - Give one user a one-call quota and prove, with a test like
test_quota.py, that two concurrent requests admit one, a timed-out call stayspendingand blocks a retry, and reconciling it twice counts it once. - Add a daily budget check with a seven-day forecast, and write down who is alerted and what degrades at each threshold.
- Report cost per 1,000 queries and evaluation pass rate before and after this skill's changes: caching, routing and batching.
08. Review prompt
Without looking back, answer in your own words:
- Which workloads suit a batch API, and why does every request need a custom id?
- What can a forecast alert tell you that a threshold alert cannot?
- What do a token bucket's capacity and refill rate each control?
- What do you reserve before a call, and what happens when the response arrives?
- Why must the quota check and the subtraction be one database step, when is a reservation released rather than left pending, and why must reconciling be safe to run twice?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.