LLM apps: reliability, cost and rate limits¶
What you'll be able to do¶
- Classify an LLM call failure as retryable or not, and choose the response: back off, repair, fall back, or fail fast.
- Estimate a feature's daily spend from token counts and prices, and say what each cost lever saves and risks.
- Wrap a notebook-style API call in a client with timeouts, limits, a breaker, a fallback and a budget, and decide what to log on every call.
A provider is a remote dependency with a meter¶
A hosted model is a network service you do not control, with the failure modes from timeouts and retries and limits from rate limiting, plus three extras: a long tail of latency (2 s or 40 s for the same prompt), a meter (cost scales with tokens), and nondeterministic output (an HTTP success can still be unusable). The response depends on the failure:
| Failure | Retry? | What to do |
|---|---|---|
| Network error, connection reset | Yes, bounded | Backoff with jitter. The request may have reached the provider. |
| Timeout | Yes, bounded | Ambiguous: the provider may still finish, and you may be billed. |
| 429 rate limit | Yes, after waiting | Honor Retry-After. Sustained 429s mean lower your concurrency, not retry harder. |
| 5xx or "overloaded" | Yes, with backoff | Good trigger for the breaker and the fallback. |
| 4xx (bad parameters, prompt too long, auth) | No | The same request fails again if sent unchanged. Fix it. |
| Truncated (stopped at max tokens) | Not blindly | Raise the limit, shorten, or continue. Never cache it as complete. |
| Refusal or safety filter | No | The same prompt will usually be refused again. Show a useful message. |
| Malformed structured output | Yes, via repair | Validate, then retry a bounded number of times. |
| Valid but wrong | Not blindly | Evals, grounding and human checks, then fix the cause. |
Retrying a pure generation call is safe for your data, though you may pay twice. Retrying a call that triggers an action is different; see delivery guarantees and idempotency.
Calling discipline¶
Timeouts. Set one per call and one deadline per user request: if a user waits at most 10 s, three 8 s attempts cannot fit. Before each attempt, check the time left and pass the smaller of it and the per-call timeout. For streams, a total timeout fits poorly, since a healthy long answer takes long: use a time-to-first-token timeout, a maximum gap between chunks, and an overall deadline. Retry a stream only if nothing has reached the user.
Retries. Retry only retryable errors, with exponential backoff, full jitter, and Retry-After as a floor:
import random
def backoff(attempt, base=1.0, cap=20.0, rng=random):
return rng.random() * min(cap, base * pow(2, attempt)) # full jitter
The ceilings are 1, 2, 4, 8, 16, then 20 s (the cap); each wait is a random point below its ceiling, so clients that failed together are less likely to retry together. If the provider says 7 s, wait max(backoff, 7). Retry at one layer: 3 attempts at each of 3 layers is 27 calls.
Bounded concurrency. In-flight calls ≈ arrival rate × latency: 100,000 requests a day (about 1.16 per second) at 6 s per call is about 7 in flight on average. Cap them with a semaphore or worker pool (concurrency); unbounded fan-out turns a spike into 429s.
A client-side token limiter. Do not learn your limit from 429s. Keep a bucket in tokens per minute: reserve the estimated tokens (prompt plus the max_tokens you ask for) before a call and refund the unused part after. With a hypothetical limit of 600,000 tokens per minute and about 1,800 tokens used per call, that sustains about 333 calls per minute.
A bucket paces calls; it does not guarantee compliance. A full bucket allows a burst, and the provider may count windows differently, limit requests as well as tokens, or share one quota across your whole account. Share reservations across workers, and give each provider or model quota, including the fallback's, its own limiter.
Fallbacks, breakers and side effects¶
A circuit breaker stops calling a failing provider for a cooldown, then lets one probe through. When it is open, or retries run out, use a fallback: a cached answer where reuse is safe, a cheaper model, another provider, a non-LLM path (rules, templates), or an honest error that keeps the user's input.
Test the fallback, because an unused path rots, and run your evals on it: a prompt tuned for one model may behave differently on another. Do not cache its answers as normal ones. Do not send it a request the primary rejected unless it can actually handle the reason, for example a model with a longer context for a prompt that was too long.
Side effects. Suppose a model decides on a refund and your code then calls a refund API. Re-asking the model is safe but may return a different decision; repeating the refund is not. Record the decision before acting, and give the action an idempotency key, so a retry replays instead of repeating. Never wrap "ask model, then act" in one retry loop (agents).
Structured output is untrusted input¶
Validate every structured reply: it parses, required fields exist, types and enums match, ranges hold. A Python trap: isinstance(True, int) is True, so a boolean passes a naive integer check.
On failure, repair and retry with a hard limit (one or two repairs), feeding the validation error back. Each repair is a billed call, so the limit also bounds cost. Constrained decoding, where generation is restricted to a schema, reduces syntax failures but not wrong content: a well-formed refund amount still needs a range check.
Treat the output like user input: it can carry text injected from documents the model read. Never pass it to a shell, SQL, or eval; authorize actions by your rules, not the model's say-so (security basics). Cache only validated output. Another Python trap: json.loads accepts NaN and Infinity, which are not valid JSON, so reject them with its parse_constant hook.
Cost is arithmetic¶
Cost per call = input tokens × input price + output tokens × output price, plus any other billed features. Take a hypothetical feature: 100,000 requests a day, each with 1,500 input tokens (system prompt, retrieved context, question) and 300 output. Made-up prices: $1 per million input tokens and $4 per million output tokens for a small model, ten times that for a large one.
input : 100,000 x 1,500 = 150,000,000 tokens -> 150 M x $1 = $150
output: 100,000 x 300 = 30,000,000 tokens -> 30 M x $4 = $120
small model, per day: $270 (per request $0.0027)
large model, per day: 150 x $10 + 30 x $40 = $2,700
| Lever (hypothetical numbers) | Daily cost | Change |
|---|---|---|
| Baseline, small model | $270 | none |
| Trim retrieval by 400 tokens (1,100 in) | 110 + 120 = $230 | about 15% less |
| Exact-match cache, 30% hits | 0.7 × 270 = $189 | 30% less |
| Small first, 20% escalate to large | 270 + 0.2 × 2,700 = $810 | 70% below all-large |
Routing pays twice for escalated requests and needs an eval showing the cheap model suffices on what it keeps. Capping max_tokens bounds output cost. A semantic cache reuses an answer for a similar question; a false hit returns a confident wrong answer, so measure its error rate and keep it off personalized content. Exact-match keys must include the tenant, model, parameters, and the system and user prompts exactly as sent; even collapsing whitespace can merge two different questions (caching and CDNs). Some providers discount a repeated prompt prefix, so put stable instructions first.
Set a budget per tenant, tag calls to attribute spend, and alert at fractions of the budget. Checking the amount spent so far before a call is only a soft gate: concurrent requests and billed retries can overshoot it. A hard cap atomically reserves an estimated maximum cost before each attempt, across all workers, then reconciles with billed usage.
Observe it, then change it carefully¶
Log one structured line per call: request id, tenant, exact model identifier, prompt version, token counts, latency, attempts, outcome, cache hit, fallback used, cost. Prompts hold personal data, so log a hash or redacted sample. Trace multi-step chains under one id, and dashboard error rate by outcome, latency percentiles, and spend per tenant (observability and SLOs). Add quality proxies to the SLO: schema-valid rate, refusal rate, a sampled eval score. Valid-but-wrong answers never show in error rates (evals as tests).
Prompts and model identifiers are code: version and review them. Pin a specific model version, not a floating alias, or behavior can change without a deploy. Providers retire old versions, so plan migrations. Before switching, run regression evals, shadow the new version on copied traffic without serving it, then canary a small share.
For AI engineers¶
For AI engineers
Your notebook loops client.chat(...) over 50,000 rows. Overnight it hits 429s, one call hangs forever, and a retry bug inflates the bill. Production routes every call through a thin LLMClient; its shape:
def complete(self, req):
hit = self.cache.get(req) # key: tenant, model, params, prompts
if hit: return hit
self.budget.check(req.tenant) # soft gate, before spending
try:
resp = self.breaker.call(lambda: self.retry(self.provider, req))
except UNAVAILABLE: # retries used up, or breaker open
resp = self.fallback(req) # cheaper model, other provider, non-LLM
self.budget.record(req, resp) # tokens x price, tagged
resp = self.validate_or_repair(resp) # bounded repairs, each metered too
if resp.cacheable: # primary, complete and validated
self.cache.put(req, resp)
self.log(req, resp) # model, prompt version, tokens, outcome
return resp
Common mistakes¶
- No timeout. A hung call blocks a worker indefinitely.
- Retrying everything. A 4xx fails identically every time, and retries at several layers multiply load.
- Unlimited concurrency into a rate limit. Bound in-flight calls and meter tokens client-side.
- Incomplete cache keys. Omitting tenant or system prompt can serve one user's answer to another.
- No budget cap. A loop or retry bug spends until someone notices the invoice.
- Logging full prompts with personal data. Hash or redact them.
Check yourself¶
A 429 arrives with Retry-After: 20, and your backoff would wait 2 s. How long do you wait, and what do you change if it keeps happening?
At least 20 s: the hint is a floor. If 429s recur, lower concurrency and add a client-side token limiter.
After a prompt change, HTTP error rate is flat, JSON parse failures spike, and daily cost rises. Why, and what do you check?
Invalid outputs trigger billed repair calls, while HTTP errors stay flat because the calls succeed. Compare outcomes and attempts by prompt version, then roll back or fix the prompt.
A step calls the model, then a payment API, and the payment call times out. May you retry the whole step?
No. Re-asking may change the decision, and repeating the payment may charge twice. Replay the recorded decision and retry the payment with the same idempotency key.
Peak traffic is 10 requests per second at 6 s per call, but your semaphore allows 20 in flight. What happens?
You need 10 × 6 = 60 in flight. With 20 slots, throughput caps near 20 / 6 ≈ 3.3 requests per second, so the queue grows and deadlines are missed. Raise the cap within the provider limit, or shed load.
Lab¶
Build an LLMClient in code/llm-reliability-cost/ against a scripted FakeProvider and fake clock. Implement jittered retries with Retry-After, a token limiter, a tenant-safe TTL cache, budgets, and JSON repair, then wire in a breaker and fallback. Tests assert exact call counts and sleeps. Run: cd code/llm-reliability-cost && PYTHONPATH=starter python -m pytest tests -q Done means all tests pass; add -k task3 to run one task.
Go deeper¶
- Interactive: Designed to Scale: timeouts and retries, rate limiting, caching
- Google SRE books on overload and cascading failures.
- OpenTelemetry docs for tracing multi-step calls.
- Software Engineering Handbook, ch. 14 "Observability"