Skip to content
LLM application engineering Core 26 min read

Shipping AI products: latency, cost, routing, UX

A demo needs one good answer; a product needs millions of them, fast enough that people wait, cheap enough that the business survives, and honest enough that people trust them. This page is the engineering of that gap: where the seconds and the dollars go, how to route each request to the cheapest model that is good enough, and how to design an interface around a component that is sometimes wrong.

10,000 ft

Model quality gets the headlines, but most LLM features that fail in production fail on something else: a reply that takes twelve seconds, a cost per user above the revenue per user, a provider outage with no fallback, or an interface that presents a guess as a fact. These are systems and product problems, and they have systems and product answers: latency budgets, caching, routing and cascades, streaming, release gates, observability and careful UX. Under the hood, the token-level economics come from how models are served (serving LLMs, compute maths); the quality bar comes from your evals; the risk bar from guardrails and security. This page ties them into one production system.

2,000 ft

Every request passes through the same handful of components, and each one is a lever on latency, cost or quality.

The request path of an LLM feature
The request path of an LLM feature. Client streams, shows progress, captures feedback, Gateway auth, rate limits, budgets, timeouts, Caches exact, prompt prefix, retrieval results, Router rules, classifier or cascade, Small model cheap, fast, Large model hard cases, Validators schema, grounding, policy, Traces and metrics latency, cost, quality per version, streamThe request path of an LLM feature. Client streams, shows progress, captures feedback, Gateway auth, rate limits, budgets, timeouts, Caches exact, prompt prefix, retrieval results, Router rules, classifier or cascade, Small model cheap, fast, Large model hard cases, Validators schema, grounding, policy, Traces and metrics latency, cost, quality per version, stream

  1. Latency is time to first token plus output tokens times time per token, summed over the calls on the critical path. Cut output tokens, cut serial calls, run work in parallel, and stream.
  2. Cost is tokens times price, times calls, times retries. Cache the static prefix, pick the cheapest model per job, batch what can wait.
  3. Routing sends each request to the cheapest model that passes your evals for that kind of request; cascades escalate only when a check fails.
  4. Reliability comes from timeouts, deadlines, fallbacks and budgets, because providers rate-limit, run out of quota and go down.
  5. UX sets expectations, shows provenance, fails honestly and lets the user correct the system.
  6. Release engineering (flags, shadow, canary, A/B) and observability (a trace per request) keep all five measurable.

Ground level

Anatomy of latency

A single model call has two phases with very different costs (the details are on serving LLMs and KV cache):

  • Prefill: the model reads the whole prompt in one parallel pass. It is compute-bound and fast per token. Its result is the time to first token (TTFT), together with network and queueing time.
  • Decode: the model generates one token at a time, each step re-reading the weights and the KV cache. It is memory-bandwidth-bound and slow per token. The cost is the time per output token (TPOT), typically tens of milliseconds.

So for one call,

\[ T_\text{call} \approx \text{TTFT} + (n_\text{out} - 1)\cdot \text{TPOT} , \]

and the input length barely matters by comparison. OpenAI's latency optimisation guide gives the rule of thumb: cutting 50% of output tokens may cut about 50% of latency, while cutting 50% of input tokens typically improves it by only 1–5%. Step through a generation to see why each new token costs a full pass:

Worked example: TTFT 0.6 s, TPOT 12 ms. A 250-token answer takes \(0.6 + 249 \times 0.012 \approx 3.6\) s; an 80-token answer takes 1.6 s. Asking for "two to four sentences" instead of "a thorough answer" is a latency optimisation.

A product request is several calls. A typical assistant turn might classify the request, retrieve or route, fetch data, then generate. If these run one after another, their latencies add:

\[ T_\text{turn} = \sum_{\text{stages on the critical path}} T_\text{stage} . \]

The critical path is the lever. Anything that does not depend on an earlier stage's output can run alongside it, and then only the longest branch counts: \(\max(T_a, T_b)\) instead of \(T_a + T_b\).

sequentialclassifyroutenarrate (tokens)speculativeclassifyroute (started at once)narrate (tokens)first words, streamed0 s12345pale red = time to first token · green = data fetch
The same four stages, sequential (5.5 s) and with routing started speculatively alongside classification (4.3 s). If the classifier disagrees, the speculative work is thrown away. Streaming then shows the first sentence at about 2.8 s. Parallelism shortens the critical path; streaming shortens the wait the user perceives.

What users perceive

Jakob Nielsen's three response-time limits still frame interaction design: about 0.1 s feels instantaneous, about 1 s keeps the flow of thought, and about 10 s is the limit of keeping attention on the task. LLM answers usually land between 1 and 10 s, so the craft is in managing that interval:

  • Stream: show tokens or sentences as they are ready. Perceived latency becomes time to first useful content, not time to completion. If outputs must be checked before display (numbers, policy), stream in checked units such as sentences rather than raw tokens.
  • Show something real early: a structured card computed by code, the retrieved sources, or a progress line that says what is happening ("Looking up your goals…").
  • Make long work asynchronous: for tasks over ~10 s (reports, agent runs), give a job with a status and a notification, not a spinner.
  • Measure the right latency: p50 for the typical experience, p95 and p99 for the experience that drives complaints, and time-to-first-token separately from total time.

The seven latency levers

OpenAI's guide lists seven principles. Here is each, with the techniques it implies:

Principle Techniques
Process tokens faster Smaller or distilled model for the job; quantised self-hosted models; faster provider tiers
Generate fewer tokens Concise output formats; JSON with short keys; "answer first"; hard max_tokens; let code render tables
Use fewer input tokens Trim retrieved context; summarise history; but expect only small gains
Make fewer requests Merge classify + route + extract into one structured call
Parallelise Independent calls concurrently; speculative execution; prefetch data at turn start
Make your users wait less Streaming, progressive disclosure, optimistic UI
Don't default to an LLM Code, lookups, regex, classical classifiers, cached answers

The last row deserves emphasis. A deterministic function is faster, cheaper, testable and never hallucinates. Use the model for what only a model can do (understanding language, choosing among options, phrasing), and code for everything else.

Tail latency and reliability

Averages hide the experience that loses users. Jeffrey Dean and Luiz André Barroso's The Tail at Scale (2013) showed how fan-out amplifies the tail: if each sub-request is slow 1% of the time, a request that waits on 100 of them is slow 63% of the time (\(1 - 0.99^{100}\)). LLM pipelines fan out too: several model calls, retrieval shards, tool calls, an agent's many steps.

Defences:

  • Timeouts on every call, set from measured p99 plus margin, and a deadline for the whole request that each stage respects. A client library's default timeout can be ten minutes.
  • Retries with exponential backoff and jitter, only for idempotent operations, and only within the deadline. Never blindly retry a call that writes.
  • Hedged requests: if a call has not returned by its p95, send a second copy and take the first answer (for idempotent reads; it costs extra tokens).
  • Circuit breakers that stop calling a failing dependency and fail fast.
  • Fallbacks: a second provider or model for the same role, a cached answer, or an honest degraded response.
  • Quota and budget alarms: providers return rate-limit (429) and quota errors. An exhausted prepaid balance looks like an outage. Alert on the first quota error, not on user complaints.

Speculation, prefetching and a credit outage in Jarvis

Finny's assistant used to run classify, route, fetch and narrate in series: 5.2 s at the median, 9.1 s at p95 on its test suite. Because most questions are about the user's plan, it now starts the routing call and the plan reads at once, alongside classification, and throws them away if the classifier disagrees. The median fell to 3.6 s and p95 to 5.8 s, for about 1.2–1.6% more model spend per average turn. The same team learned the reliability lesson the hard way: evals billed the same provider account as production, the balance ran out, and every user's question was refused until it was topped up. Evals now can run on their own key, and the first quota error raises an alert. See the case study.

Anatomy of cost

Per call, cost is linear in tokens:

\[ C = \frac{n_\text{in}^\text{uncached}\, p_\text{in} + n_\text{in}^\text{cached}\, p_\text{cache} + n_\text{out}\, p_\text{out}}{10^6} , \]

with prices quoted per million tokens. Output tokens are typically several times the price of input tokens, and cached input a fraction of it. Per task, multiply by the number of calls (including judge calls, repairs and retries) and divide by the success rate: the honest unit is cost per successful task, not cost per call. An agent that takes 15 steps with a growing context can cost two orders of magnitude more than a single call.

Worked example, with illustrative prices of USD 2.50 per million input tokens and USD 15 per million output tokens for a large model: a request with 3,000 input tokens and 250 output tokens costs \((3000 \times 2.5 + 250 \times 15)/10^6 = \text{USD } 0.01125\). At 100,000 requests a day, that is about USD 1,125 a day, or USD 34,000 a month. Now look at where the cost is: 7,500 of the 11,250 millionths come from input, and most of that input (system prompt, instructions, examples) is identical on every request.

Cost levers

Prompt caching. Providers cache the processed prefix of a prompt and bill re-use at a steep discount. As of 2026, Anthropic bills cache writes at 1.25× and cache reads at 0.1× the base input price with a default five-minute lifetime (docs), and OpenAI caches long prompts automatically, discounting reused tokens by up to 95% depending on the model (docs). Caching only matches an exact prefix, so order the prompt from most static to most dynamic: system prompt, tool definitions, few-shot examples, long reference documents, then the conversation, then the current question. Putting today's date or the user's name at the top defeats it. In the example above, caching 2,500 of the 3,000 input tokens halves the cost to USD 0.0056, and also cuts TTFT.

Batch processing. Work that can wait (nightly summaries, evals, backfills, embeddings) can go through batch APIs: OpenAI's Batch API gives a 50% discount for results within 24 hours.

The right model per job. A pipeline has several jobs with different difficulty: classify, extract, route, write, judge. Give each its own model setting and choose each by running its own eval on candidates. A small model that routes as well as a large one at a sixth of the price is a pure win; a small model that writes noticeably worse prose is not, however cheap.

Fewer and shorter outputs. Ask for the answer, not an essay. Let code render tables, lists and numbers from structured data instead of having the model type them out.

Context discipline. Long histories and over-retrieved context cost on every turn. Summarise or window the history, retrieve fewer, better chunks (see RAG and context engineering).

Caching answers. Exact-match caches of whole responses work for repeated deterministic queries. Semantic caches (return a stored answer when a new question's embedding is close enough) are tempting and risky: "What is my balance?" from two different users, or "Can I cancel?" before and after a policy change, embed almost identically. Use them only where answers are not personal and not time-sensitive, and evaluate their false-hit rate.

Fine-tune or distil when a large model's behaviour on a narrow task is stable and the volume is high: a small model trained on the large model's outputs can match it on that task (see distillation and LoRA).

Routing and cascades

Routing chooses a model per request; it is the biggest single cost lever when traffic is mixed.

Three ways to route a request
Three ways to route a request. Request, Rules feature, tier, length, language, Learned router predicts which model will be good enough, Cascade cheap model first, verifier escalates, Small model, Large model, always, if rejectedThree ways to route a request. Request, Rules feature, tier, length, language, Learned router predicts which model will be good enough, Cascade cheap model first, verifier escalates, Small model, Large model, always, if rejected
  • Rules first: by feature (autocomplete vs. report writing), by user tier, by input length or language. Free, transparent, and often enough.
  • A learned router predicts, before calling anything, whether the cheap model's answer will be good enough. RouteLLM (Ong et al., 2024) trained such routers on human preference data and reduced costs by over 2× in some settings without hurting quality, and the routers kept working when the pair of models was swapped.
  • A cascade calls the cheap model first and escalates when a check rejects its answer: a verifier model, a confidence score, a schema or unit test, a grounding check. FrugalGPT (Chen, Zaharia and Zou, 2023) learned cascades that matched the best individual model with up to 98% lower cost on their benchmarks.

A cascade's economics are easy to write down. With cheap-model cost \(c_s\), verifier cost \(c_v\), large-model cost \(c_\ell\) and escalation rate \(e\),

\[ \mathbb E[C] = c_s + c_v + e\, c_\ell , \]

which beats always-large when \(e < 1 - (c_s + c_v)/c_\ell\). Quality depends on how good the verifier is at accepting right answers and rejecting wrong ones: every wrong answer it accepts is shipped. Build it simulates a cascade that keeps 92% accuracy at 36% of the always-large cost; the verifier's error rates are the knob that matters.

Routing silently changes your product

Once requests go to different models, your eval must be run per route, and your traces must record which model answered. A router that sends 30% of traffic to a weaker model for a month will not show up in an average-quality chart if that 30% are easy questions, until the traffic mix shifts.

Designing the experience

Microsoft's Guidelines for Human-AI Interaction (Amershi et al., CHI 2019) distilled 18 guidelines from two decades of work, and Google's People + AI Guidebook covers the same ground with worked patterns. The ones that matter most for LLM products:

  • Make clear what the system can do, and how well. Say what it covers and what it won't do. Suggest example questions. Users over-trust fluent text; set expectations before the first answer.
  • Show provenance. Cite sources, link to the record, label estimates as estimates and figures computed by code as such. A number with a visible basis is checkable; one without is a claim.
  • Answer first. Lead with the figure or the decision, then the explanation. Long preambles are slow and bury the point.
  • Fail honestly. "I couldn't confirm that figure, so I've left it out" is better than a confident wrong number. Design refusal and partial-answer states as carefully as success states.
  • Support efficient correction. Edit-and-resend, regenerate, "that's not what I meant", undo for any action the system took.
  • Keep humans in charge of consequential steps. Andrej Karpathy's Software Is Changing (Again) talk argues for partial autonomy: an "autonomy slider" from suggestion to action, with a fast loop in which the model generates and the human verifies. Make verification cheap (diffs, previews, highlighted changes).
  • Don't force everything through chat. A form, a button or a chart is often clearer than a paragraph. Many good LLM products return structured cards filled by code, with prose around them.
  • Capture feedback where it is cheap (thumbs, edits, copy events) and route it to the eval loop, not just a dashboard.

Observability

You cannot improve what you cannot see. For every request, store a trace: the user input, the prompt template and its version, the model per call, retrieved items, tool calls and results, validator outcomes, tokens (cached and uncached), cost, latency per stage, the final output and any user feedback. With traces you can:

  • break latency down by stage and find the real bottleneck;
  • compute cost per feature, per user and per successful task;
  • replay a bad turn exactly, and turn it into an eval case;
  • compare versions on live traffic.

Version everything that changes behaviour: prompts, model identifiers (pin dated versions rather than floating aliases), retrieval indexes, feature flags. Most "the model got worse" incidents are an unrecorded change somewhere in this list.

Release engineering

From change to full rollout
From change to full rollout. Offline evals golden set, paired with last release, Shadow new version runs on real traffic, unseen, Canary 1-5% of users, watch guardrail metrics, A/B test pre-registered metric, fixed sample size, Full rollout flag stays, old version kept warm, Rollback flip the flagFrom change to full rollout. Offline evals golden set, paired with last release, Shadow new version runs on real traffic, unseen, Canary 1-5% of users, watch guardrail metrics, A/B test pre-registered metric, fixed sample size, Full rollout flag stays, old version kept warm, Rollback flip the flag
  • Every behaviour change goes behind a flag, so rollback is a configuration change, not a deploy.
  • Evaluate the configuration you ship. If production runs with different flags, model versions or settings than your eval run, the eval measured a different product. Record the effective configuration with every eval run and every trace.
  • Shadow mode runs a new version on real inputs without showing its output, so you can compare outputs, latency and cost on true traffic.
  • Canary to a small slice and watch guardrail metrics (refusal rate, validator failures, latency, cost) before user metrics move.
  • A/B test decisions that matter, with the metric and sample size fixed in advance (see the online-experiment section of statistics for evals).
  • Model upgrades are releases. A new model version changes behaviour everywhere at once. Run the full eval suite per route, compare paired, and roll out like any other change.

In practice

  • Set budgets per feature before building: target p50 and p95 latency, cost per request, and minimum eval pass rate. Every design choice is then a trade within the budget.
  • Measure before optimising. Per-stage latency and per-call token counts usually show one dominant cost: often output length or a serial call that could run in parallel.
  • Keep the static prompt first and long: it is cheaper and faster once cached.
  • Give each call a timeout, the whole request a deadline, and the account a spend alert.
  • Separate production and eval budgets so testing can never starve users of quota.
  • Pin model versions, and treat a provider's model update like your own code change.
  • Design the failure states (timeout, refusal, partial answer, provider down) with the same care as the happy path; users will see them.

Common misconceptions

  • "Shorter prompts make it faster." Mostly not: output length and the number of serial calls dominate. Shorter prompts save cost, and cache hits save both.
  • "The biggest model is the safe choice." It is the slowest and most expensive. For most jobs in a pipeline a smaller model passes the same eval; you only know by running it.
  • "Average latency is fine." Users remember the slow tail, and fan-out makes the tail common.
  • "Streaming is a frontend detail." If outputs need checking before display, streaming changes your validation design: you must check incrementally or accept retractions.
  • "Semantic caching is free money." For personal or time-sensitive answers it serves wrong answers with high confidence.

First principles

Why decode dominates. Generating each token requires reading every weight of the model from memory once (plus the KV cache), while doing only a few FLOPs per byte read. The GPU is waiting on memory bandwidth, so time per token is roughly model size in bytes divided by bandwidth, regardless of how much compute is available. Prefill processes all prompt tokens in one pass, sharing each weight read across many tokens, so it uses the compute well. That asymmetry, worked through on how a GPU works and serving LLMs, is why output tokens cost more in both time and price, and why speculative decoding (Leviathan et al., 2022) and batching (PagedAttention, Kwon et al., 2023) pay off on the serving side.

Little's law sizes your concurrency. In steady state, the average number of requests in the system equals the arrival rate times the average time each spends there: \(L = \lambda W\). At 20 requests per second and 4.7 s per request, about 94 requests are in flight at once. That number sets connection pools, worker counts and the provider rate limits you need, and it grows with latency: making requests faster also makes the system smaller.

Queues punish high utilisation. In the simplest queueing model (M/M/1), the mean time in system is \(W = 1/(\mu - \lambda)\), which diverges as utilisation \(\rho = \lambda/\mu\) approaches 1: at \(\rho = 0.5\) a request spends twice its service time in the system; at \(\rho = 0.9\), ten times. Rate limits are a server you share with other customers; running close to them turns small traffic bursts into large latency spikes. Keep headroom.

The economics of a pipeline are additive; the economics of quality are multiplicative. Costs of calls add up. But if a turn needs five stages to all succeed, and each succeeds 98% of the time, the turn succeeds \(0.98^5 \approx 90\%\) of the time. Fewer, more reliable stages beat many clever ones, which is the same argument as Sculley et al.'s Hidden Technical Debt in Machine Learning Systems (2015) made for ML pipelines: glue code and entanglement, not models, become the cost.

The maths

Latency of a turn

For a call, \(T = \text{TTFT} + (n_\text{out} - 1)\,\text{TPOT}\). For a pipeline whose stages form a directed acyclic graph, the turn's latency is the length of the longest path:

\[ T_\text{turn} = \max_{\text{paths } P} \sum_{s \in P} T_s . \]

Running independent stages \(a\) and \(b\) in parallel replaces \(T_a + T_b\) with \(\max(T_a, T_b)\). Because stage times are random, \(\mathbb E[\max(T_a, T_b)] \ge \max(\mathbb E[T_a], \mathbb E[T_b])\): parallel branches still feel each other's tails.

Tail amplification

If a request waits for \(n\) independent sub-calls, each exceeding a threshold with probability \(q\), then

\[ P(\text{request exceeds it}) = 1 - (1 - q)^n \approx nq \quad (nq \ll 1) . \]

With \(q = 0.01\): 1% at \(n = 1\), 4.9% at \(n = 5\), 18.2% at \(n = 20\), 63.4% at \(n = 100\). The p99 of a component becomes the median experience of a wide enough fan-out.

Cost of a cascade

Cheap model cost \(c_s\), verifier \(c_v\), large model \(c_\ell\). Let the cheap model be right with probability \(a\), and let the verifier accept a right answer with probability \(\alpha\) and a wrong one with probability \(\beta\). Then the escalation rate is \(e = 1 - [a\alpha + (1-a)\beta]\), the expected cost is \(c_s + c_v + e\,c_\ell\), and the accuracy is

\[ A = a\alpha + a(1-\alpha)\,q_{\ell \mid s\checkmark} + (1-a)(1-\beta)\,q_{\ell \mid s\times} , \]

where \(q_{\ell \mid \cdot}\) is the large model's accuracy on those questions. The term \((1-a)\beta\) is the error the cascade ships without ever asking the large model: the verifier's false-accept rate sets the quality ceiling.

Prompt-cache savings

With \(n_c\) of \(n_\text{in}\) input tokens served from cache at a fraction \(r\) of the input price (0.1 is typical), the input cost falls by the factor

\[ \frac{(n_\text{in} - n_c) + r\,n_c}{n_\text{in}} . \]

For \(n_\text{in} = 3000\), \(n_c = 2500\), \(r = 0.1\): \((500 + 250)/3000 = 0.25\), a 75% cut on input. The first request after the cache expires pays a write premium, so the saving depends on traffic arriving within the cache lifetime.

Build it

NumPy. A four-stage assistant turn, sequential against speculative, and the streamed time to first words; tail amplification; cost per request with and without prompt caching; a three-way comparison of always-small, always-large and a cascade; and Little's law. Stage latencies are lognormal, with medians loosely modelled on a real assistant's pipeline.

import numpy as np
rng = np.random.default_rng(1)
N = 20_000
def ln(median, spread):                       # lognormal stage latency, seconds
    return median * np.exp(spread * rng.standard_normal(N))

# 1. One chat turn: classify, route, fetch, then narrate (TTFT + tokens x time-per-token).
classify, route, fetch = ln(1.2, 0.25), ln(1.7, 0.30), ln(0.2, 0.5)
ttft, tpot = ln(0.6, 0.3), 0.012              # 12 ms per output token, about 83 tokens/s
out_tokens = rng.integers(80, 260, N)
narrate = ttft + out_tokens * tpot
sequential = classify + route + fetch + narrate
speculative = np.maximum(classify, route + fetch) + narrate      # route starts with classify
first_words = np.maximum(classify, route + fetch) + ttft + 25 * tpot  # first sentence, streamed
show = lambda x: f"p50 {np.median(x):.2f} s   p95 {np.percentile(x, 95):.2f} s"
print("sequential   ", show(sequential))
print("speculative  ", show(speculative))
print("first words  ", show(first_words))

# 2. Tail amplification: a request waits for n parallel calls, each slow 1% of the time.
for n in (1, 5, 20, 100):
    print(f"fan-out {n:3d}: P(request hits a slow call) = {1 - 0.99**n:.3f}")

# 3. Cost per request, USD per 1M tokens (input, output); cached input billed at 10%.
price = {"small": (0.10, 0.50), "large": (2.50, 15.00)}
def cost(model, tin, tout, cached=0):
    pin, pout = price[model]
    return ((tin - cached) * pin + cached * pin * 0.1 + tout * pout) / 1e6
print(f"large, 3000 in / 250 out:          ${cost('large', 3000, 250):.5f}")
print(f"large, 2500 of the input cached:   ${cost('large', 3000, 250, cached=2500):.5f}")
print(f"small, 3000 in / 250 out:          ${cost('small', 3000, 250):.5f}")

# 4. A cascade: small model first, a cheap verifier escalates doubtful answers to the large model.
small_ok = rng.random(N) < 0.80
large_ok = np.where(small_ok, rng.random(N) < 0.97, rng.random(N) < 0.72)  # large is right 92%
accept = np.where(small_ok, rng.random(N) < 0.85, rng.random(N) < 0.15)    # verifier's call
cascade_ok = np.where(accept, small_ok, large_ok)
c_small, c_large, c_verify = cost('small', 3000, 250), cost('large', 3000, 250), cost('small', 3300, 5)
c_cascade = c_small + c_verify + (~accept) * c_large
for name, ok, c in [("all small", small_ok, c_small), ("all large", large_ok, c_large),
                    ("cascade", cascade_ok, c_cascade)]:
    print(f"{name:9s} accuracy {ok.mean():.3f}   cost/request ${np.mean(c):.5f}   escalated "
          f"{(~accept).mean() if name == 'cascade' else 0:.2f}")

# 5. Little's law: requests in flight = arrival rate x time in system.
for rps in (5, 20, 50):
    print(f"{rps:2d} req/s x {np.mean(speculative):.1f} s = {rps * np.mean(speculative):5.0f} requests in flight")

Output:

sequential    p50 5.86 s   p95 7.44 s
speculative   p50 4.66 s   p95 6.10 s
first words   p50 2.87 s   p95 4.01 s
fan-out   1: P(request hits a slow call) = 0.010
fan-out   5: P(request hits a slow call) = 0.049
fan-out  20: P(request hits a slow call) = 0.182
fan-out 100: P(request hits a slow call) = 0.634
large, 3000 in / 250 out:          $0.01125
large, 2500 of the input cached:   $0.00562
small, 3000 in / 250 out:          $0.00042
all small accuracy 0.800   cost/request $0.00042   escalated 0.00
all large accuracy 0.922   cost/request $0.01125   escalated 0.00
cascade   accuracy 0.920   cost/request $0.00405   escalated 0.29
 5 req/s x 4.7 s =    23 requests in flight
20 req/s x 4.7 s =    94 requests in flight
50 req/s x 4.7 s =   234 requests in flight

Three things to read off. Starting the route alongside classification saves about 1.2 s at the median, and streaming halves the perceived wait again, without touching any model. Prompt caching halves the large model's cost, because input was two-thirds of it. And the cascade keeps the large model's accuracy (0.920 against 0.922) at 36% of its cost, escalating 29% of requests; the 3% of requests where the verifier accepts a wrong cheap answer are the price.

Things to try

  • Make the verifier worse (accept wrong answers 30% of the time) and better (5%). Plot accuracy against cost for each and find where the cascade stops being worth it.
  • Add a hedged request to the route stage: if it has not returned by its p95, start a second copy and take the first. How much does p95 improve, and how many extra calls does it cost?
  • Add a 2% chance per call of a 30-second stall with no timeout, then add a 6-second timeout with one retry. Compare p99.
  • Replace out_tokens with a distribution half as long. Which helps p50 more: that, or speculation?

Check yourself

Why does cutting output tokens reduce latency far more than cutting input tokens?

Input is processed in one parallel prefill pass; output is generated one token at a time, each a sequential, memory-bound forward pass. Halving the output roughly halves decode time; halving the input shaves a little off TTFT.

Your p50 is 3 s but complaints mention 15-second waits. Where do you look?

At the tail: p95/p99 per stage from traces. Typical causes are retries after rate limits, provider stalls with no timeout, a slow tool or retrieval call, long outputs on some question types, or a repair or second pass that only runs sometimes. Fan-out makes rare slowness common.

When does a cascade cost less than always using the large model?

When the escalation rate \(e < 1 - (c_s + c_v)/c_\ell\). With a cheap model at 4% of the large model's cost and a verifier at 3%, the cascade wins on cost whenever fewer than 93% of requests are escalated; whether it wins on quality depends on the verifier's false-accept rate.

Why should the system prompt come before the user's data in the prompt?

Prompt caches match an exact prefix. Static content first means every request shares the same prefix and hits the cache; putting dynamic content (date, name, retrieved text) first changes the prefix on every request and defeats caching.

What does Little's law tell you about the effect of a latency improvement on infrastructure?

\(L = \lambda W\): at fixed traffic, cutting time in system cuts the number of concurrent requests proportionally, so you need fewer workers, connections and rate-limit headroom.

Hard: you route 40% of traffic to a cheaper model and the overall eval score is unchanged. Why might the product still have got worse?

The eval may not be stratified the way traffic is: if the router sends easy questions to the cheap model, the average can hold while a particular segment (harder or rarer questions the router misclassifies) degrades. Evaluate per route and per segment, record the model in every trace, and watch for drift in the router's decisions as traffic changes.

Hard: why can parallelising two stages make the p95 worse than you expect from their medians?

The turn waits for the slower of the two. \(\max(T_a, T_b)\) has a heavier upper tail than either alone, especially when both are right-skewed. Speculative work also adds load, which can raise queueing delay for everyone near a rate limit.

Go deeper

Papers

Videos and lectures

  • Software Is Changing (Again) — Andrej Karpathy, 2025. Partial autonomy, the autonomy slider and fast generate-verify loops.
  • State of GPT — Andrej Karpathy, Microsoft Build 2023. The second half is practical advice on building with LLMs.

Articles and docs

Courses and books

  • AI Engineering — Chip Huyen, O'Reilly, 2025. Evaluation, inference optimisation and architecture for foundation-model applications.
  • People + AI Guidebook — Google PAIR. Design patterns for trust, feedback and errors in AI products.

Where this leads