CONTENTS
Cost, latency and reliability at scale
The system works, it's measured and it's safe. Now traffic grows, and three new questions dominate: what does it cost, how fast is it, and what happens when a provider has a bad day? This chapter covers the components Chip Huyen's platform build-up adds for these: caches, routers and gateways.
Prompt caching
Chapter 3 explained the physics: reusing a cached prefix skips prefill work. Providers pass the savings on.
The details vary by provider and change often, so check current docs, but the shape in late 2026 is:
- Anthropic lets you mark cache breakpoints (or use an automatic mode). Writing to the cache costs a bit more than normal input (1.25× for the default 5-minute lifetime, 2× for a 1-hour lifetime), and reading from it costs a small fraction: 0.1× of the base input price on most models and less on the newest ones. The cache lifetime refreshes each time it's hit.
- OpenAI caches automatically for prompts above a minimum length, with cached input discounted by 90% or more depending on the model; newer models also offer longer retention options, priced separately.
The design rules follow directly from Chapter 4: stable content first, volatile content last, append rather than edit, deterministic serialization. Measure your cache hit rate per feature. A drop usually means someone put something volatile near the top of a prompt.
Batch processing
If no one is waiting for the answer (nightly classification, backfilling embeddings, generating evals, contextualizing chunks), use batch APIs. Anthropic's Message Batches and OpenAI's Batch API both charge 50% of normal prices, in exchange for results within 24 hours (often much sooner). Discounts can stack with caching.
Design consequence: separate interactive work from background work in your architecture, so background work can go to the cheaper path.
Model routing and cascades
Not every request needs your most expensive model. Two strategies exploit that.
Routing classifies each request and sends it to an appropriate model. LMSYS's RouteLLM (2024) trained routers on human preference data and reported cost reductions of over 85% on MT-Bench, 45% on MMLU and 35% on GSM8K compared with always using GPT-4, while keeping about 95% of GPT-4's performance.
Cascades try a cheap model first and escalate only if a check says the answer isn't good enough. FrugalGPT (Chen, Zaharia and Zou, 2023) reported matching the best individual model's performance with up to 98% cost reduction on its benchmarks.
These are research results on benchmarks; your numbers will differ. The practical form is usually simpler: a rule- or classifier-based router (by task type, input length, user tier) and a cascade wherever you have a reliable check (schema validation, tests, a confidence threshold). The key requirement is the same as everywhere else: an eval that tells you the cheaper path is good enough.
Exact and semantic caching
Exact caching stores responses keyed by the full input. Safe and simple, but it only helps when identical requests repeat: FAQ-style queries, deterministic pipelines, repeated eval runs.
Semantic caching embeds the request and returns a cached response for any similar past request. It's tempting and risky. "How do I cancel my order?" and "How do I cancel my subscription?" may be close in embedding space and need different answers. GPTCache's own documentation acknowledges false positives on hits and false negatives on misses. Huyen's platform post notes that semantic caching's value is the least certain of the cache types. If you use one, keep it to non-personalized content, set a strict similarity threshold, and evaluate wrong-hit rates like any other quality metric.
Common confusion: "Prompt caching" and "response caching" are different things. Prompt caching (provider-side) reuses computation on a shared prefix and still generates a fresh answer. Response caching (your side) skips the model and returns an old answer. The first is almost always safe; the second can serve wrong or stale answers.
The gateway
As soon as you have more than one model, provider or team, put a gateway between your code and the providers. It's the AI version of an API gateway, and it centralizes:
- one API across providers, so switching models is configuration, not code;
- authentication and key management;
- rate limiting and per-team or per-user budgets;
- retries, timeouts and fallbacks;
- logging, tracing and cost attribution;
- caching and guardrails, if you want them centralized.
Open-source options include LiteLLM and Portkey's gateway; managed ones include Cloudflare AI Gateway and Vercel AI Gateway. Or build a thin one yourself; the important part is that there's exactly one path out to model providers.
Reliability: retries, timeouts and fallbacks
Model APIs fail in ordinary ways: rate limits (HTTP 429), overload (Anthropic uses 529), server errors (500s) and timeouts. Your design needs a policy for each.
Retry with exponential backoff and jitter. Wait longer after each failure, and randomize the wait. Marc Brooker's AWS Architecture Blog post "Exponential Backoff and Jitter" showed why jitter matters: without it, many clients that failed at the same moment retry at the same moment and fail again together. "Full jitter" (wait a random time between zero and the exponential cap) is simple and effective.
import random, time
def call_with_retry(fn, attempts=5, base=0.5, cap=20.0):
for attempt in range(attempts):
try:
return fn()
except RetryableError as e:
if attempt == attempts - 1:
raise
wait = e.retry_after or random.uniform(0, min(cap, base * 2 ** attempt))
time.sleep(wait)
Respect retry-after headers when the provider sends them. Don't retry errors that won't change (bad requests, auth failures, exceeded spending caps). The official SDKs already retry some errors by default, so check before stacking your own retries on top and multiplying load.
Timeouts. Set them per step, based on your latency budget. Prefer streaming for long generations: a stream that's still producing tokens is alive, while a non-streaming call that's been silent for two minutes may or may not be.
Fallbacks. When the primary model fails or times out, try another: a different region, a different provider, or a smaller model with a degraded but acceptable answer. Fallbacks need evals too: a fallback model with a different prompt format can quietly produce worse answers. Test your fallback path regularly, or it won't work when you need it.
Graceful degradation. Decide what the product does when the AI part is unavailable: show search results without a summary, queue the request and notify later, or hand off to a human.
Cost trends and when to re-architect
Inference prices for a given level of capability have fallen fast. Guido Appenzeller at a16z estimated in 2024 ("LLMflation") that the cost for equivalent performance was falling about 10× per year. Epoch AI's 2025 analysis found declines ranging from 9× to 900× per year depending on the capability threshold, while cautioning that the fastest drops were recent and might not last.
Two design implications:
- Don't over-optimize cost too early. An architecture that's twice as complex to save 50% may be obsolete in a year. Optimize for quality and speed of iteration first, then cost once volume makes it matter.
- Re-run your evals on new models regularly. Today's expensive model is next year's cheap one, and a step that needed a large model may move to a small one. The eval suite is what makes that switch safe.
Key takeaways
- Prompt caching is the biggest cost lever for most systems. Design prompts for it and track hit rate.
- Use batch APIs (50% off) for anything non-interactive.
- Route and cascade across models, guided by evals.
- Response caching, especially semantic, can serve wrong answers. Use it narrowly and measure it.
- Put one gateway between your code and all providers.
- Retry with backoff and jitter, respect
retry-after, set timeouts, test fallbacks, and plan graceful degradation. - Prices fall fast. Don't over-optimize early; keep evals ready to switch models.
Exercises
- Recompute Chapter 2's napkin math with prompt caching on the 1,500-token system prompt (assume a cache read costs 0.1× input and a 95% hit rate). What's the new daily cost?
- Design a cascade for a SQL-generating assistant. What's the cheap model's check, and what triggers escalation?
- Write the fallback policy for a chat product with one primary and one backup provider. Include timeouts, retry counts and what the user sees.