Home / AI Architecture & System Design / AI System Design

AI System DesignMidQuestion 2 of 20

How would you reduce the latency of an LLM feature that currently takes 8 seconds?

30-second answer

First measure the breakdown: retrieval, queueing, time-to-first-token, decode. Then: stream output; cut output length; use a smaller or faster model for some or all steps; parallelize retrieval and tool calls; trim the prompt and use prompt caching for static prefixes; cache frequent responses. If self-hosting, use continuous batching, quantization and speculative decoding.

Try answering out loud before reading on. The walkthrough below is paced for a 40-minute interview round.

New to these terms? 16 terms on this page are explained in the glossary

0–5 min Functional requirements

"Make it faster" isn't a requirement. Find out which number is 8 seconds, what the feature must keep doing, and what "fast enough" means.

You Is 8 seconds the time until the user sees anything, or until the full answer is done?

Interviewer Both, right now. The answer appears all at once after about 8 seconds.

You What does the pipeline do?

Interviewer It's a docs assistant. A large model rewrites the question, we retrieve 12 chunks, a large model writes the answer, and a checker verifies citations.

You What's the target, and is quality allowed to drop?

Interviewer First text under 1.5 seconds and the full answer under 4 seconds at p95. Quality can't drop.

You Hosted APIs or our own GPUs?

Interviewer Hosted APIs.

So the job is to change how the feature runs while keeping what it does:

# Functional requirement Why it matters
F1 Keep the same capabilities: rewriting follow-ups, retrieval, cited answers, citation checks Speed can't come from silently removing safety or quality steps
F2 Show progress early: streamed text, or status while tools run Perceived latency is what users feel
F3 Keep answers complete for users who need detail (e.g. "show more") Shorter default answers shouldn't lose information
F4 Record per-step timing for every request You can't optimize what you don't measure

5–10 min Non-functional requirements and estimates

You Before changing anything, I want a breakdown from traces. Here's what I'd expect to find, and the arithmetic behind each part.

Requirement Target What it forces in the design
Time to first text ≤ 1.5 s p95 Streaming; short critical path before the answer model starts
Full answer ≤ 4 s p95 Fewer output tokens or faster decoding
Quality No regression on the evaluation set Every change is evaluated, not just timed
Cost No more than +10% Prefer changes that also save money (shorter prompts, smaller models)
Tail latency p99 ≤ 2× p95 Timeouts, retries with budgets, capacity headroom

Where the 8.2 seconds goes (from traces):

Step Time Why
Network + queue 0.2 s Gateway, auth
Query rewrite (large model) 0.9 s A large model for a small job
Retrieval 0.4 s Hybrid search
Prefill (time to first token) 1.2 s ~6,000-token prompt: 12 chunks plus instructions
Decode 5.2 s 520 output tokens at ~100 tokens/s
Citation check 0.3 s Runs after the full answer

Two numbers matter most:

  • Decode time = output tokens ÷ tokens per second. 520 tokens at 100 tokens/s is 5.2 s. Cutting the answer to ~180 tokens saves ~3.4 s, more than everything else combined.
  • Time to first token grows with prompt length. A 6,000-token prompt cut to ~2,500 tokens roughly halves prefill time, from ~1.2 s to ~0.6 s.

10–18 min High-level design

You Here's the before-and-after timeline I'm aiming for. Then I'll show what changes in the pipeline to get there.

Scroll sideways to see the whole diagram.

Latency breakdown before and after optimizationBefore · sequential, no streaming: Network + queue 0.2 s, Query rewrite (large) 0.9 s, Retrieval 0.4 s, Prefill (TTFT) 1.2 s, Decode 520 tokens 5.2 s, Verification 0.3 s; first text at 8.2 s; total 8.2 s. After · small rewrite model, 4 chunks, short answers, streaming: Network + queue 0.2 s, Query rewrite (small) 0.2 s, Retrieval 0.4 s, Prefill (TTFT) 0.6 s, Decode ~180 tokens 1.8 s, Verification 0.3 s; first text at 1.4 s; total 3.5 s.Before · sequential, no streamingtotal 8.2 sNetwork + queue0.2 sQuery rewrite (large)0.9 sRetrieval0.4 sPrefill (TTFT)1.2 sDecode 520 tokens5.2 sVerification0.3 sfirst text 8.2 s0s1s2s3s4s5s6s7s8sAfter · small rewrite model, 4 chunks, short answers, streamingtotal 3.5 sNetwork + queue0.2 sQuery rewrite (small)0.2 sRetrieval0.4 sPrefill (TTFT)0.6 sDecode ~180 tokens1.8 sVerification0.3 sfirst text 1.4 s0s1s2s3s4s5s6s7s8s
Latency breakdown before and after optimization. Before, every step ran in sequence and nothing showed until 8.2 s. After a small rewrite model, fewer reranked chunks, shorter answers and streaming, text appears at 1.4 s and the answer finishes at 3.5 s.

Scroll sideways to see the whole diagram.

The pipeline before and afterComponents: Question; Rewrite (large · 0.9 s); Retrieve (12 chunks); Answer LLM (6k-token prompt); Citation check (after full answer); User (all at 8.2 s); Question; Rewrite (small · skip turn 1); Retrieve (50 candidates); Rerank (keep best 4); Answer LLM (2.5k tokens, cached); User (streamed); Citation check (while streaming). Flow: Question to Rewrite; Rewrite to Retrieve; Retrieve to Answer LLM; Answer LLM to Citation check; Citation check to User; Question to Rewrite; Rewrite to Retrieve; Retrieve to Rerank; Rerank to Answer LLM; Answer LLM to User; Answer LLM to Citation check; Citation check to User (flags).BEFORE · 8.2 S, NOTHING SHOWN UNTIL DONEAFTER · FIRST TEXT AT 1.4 SQuestionRewritelarge · 0.9 sRetrieve12 chunksAnswer LLM6k-token promptCitation checkafter full answerUserall at 8.2 sQuestionRewritesmall · skip turn 1Retrieve50 candidatesRerankkeep best 4Answer LLM2.5k tokens, cachedUserstreamedCitation checkwhile streamingflags
The pipeline before and after. Before: a large model rewrites every question, 12 chunks make a long prompt, and the user waits for the full answer and the citation check. After: a small rewrite (skipped on first turns), reranking to 4 chunks, a cached prompt prefix, streaming, and a citation check that runs while text streams.

What changes, and the expected saving:

  1. Stream the answer. Users see text when the first token arrives instead of after the last one. This alone moves first text from 8.2 s to ~2.7 s, and costs nothing.
  2. Shorter answers by default. Instruct a concise format (~150 words) with a "show more" option. Decode drops from 5.2 s to ~1.8 s.
  3. Small model for the rewrite, and skip it entirely on the first turn of a conversation, when there's no history to resolve. 0.9 s → 0.2 s (or 0).
  4. Fewer, better chunks. Rerank 50 candidates to the best 4 instead of sending 12. The prompt shrinks from ~6,000 to ~2,500 tokens, and prefill from 1.2 s to ~0.6 s.
  5. Prompt caching for the static instructions at the start of the prompt, which further cuts prefill on cache hits.
  6. Citation check runs while text streams, finishing just after the last token. If it fails, the UI marks the unsupported sentence instead of holding the whole answer back.

Instrumentation the design needs:

span: request                    attrs: feature, user_tier, model, prompt_version
  span: rewrite                  attrs: model, skipped (bool)
  span: retrieval                attrs: candidates, k
  span: rerank                   attrs: candidates_in, chunks_out
  span: llm.generate             attrs: input_tokens, cached_tokens, output_tokens,
                                        ttft_ms, tokens_per_s
  span: citation_check           attrs: claims, unsupported

Dashboards show p50, p95 and p99 for each span, plus output-token distributions, because tail latency usually comes from the longest answers.

How it works: a worked example

A study aid: the same request traced before and after the changes, with each span's timing, so you can see exactly where the 8.2 seconds went.

The request: "Why was my last invoice higher than usual?" on the support assistant.

Before (8.2 s until the full answer appears, nothing visible until then):

trace 7a1f…  total 8,200 ms
├─ gateway + auth ............................   200 ms
├─ rewrite (large model) .......................   900 ms   input 1,100 tok, output 30 tok
├─ retrieval (hybrid, k=12) ....................   400 ms
├─ llm.generate (large model) ..................  6,400 ms
│    ttft 1,200 ms   input 6,050 tok (0 cached)   output 520 tok @ 100 tok/s
└─ citation_check ..............................   300 ms   (after generation)
UI: spinner for 8.2 s, then the whole answer at once

After (first text at ~1.2 s, complete at ~3.3 s):

trace 9c42…  first text 1,180 ms   complete 3,320 ms
├─ gateway + auth ............................   150 ms
├─ rewrite: skipped (first turn) ...............     0 ms
├─ retrieval (hybrid, k=50) ....................   250 ms
├─ rerank 50 → 4 ...............................   150 ms
├─ llm.generate (large model, streamed) ........  2,430 ms
│    ttft 630 ms     input 2,480 tok (1,400 cached)   output 180 tok @ 100 tok/s
└─ citation_check (in parallel with streaming) .   finishes 320 ms after the last token
UI: first words at ~1.2 s, answer complete at ~3.3 s

What made each difference:

Change Before → after Why it works
Stream tokens 8.2 s → ~1.2 s to first text Users start reading at the first token, not the last
Shorter default answers 520 → 180 tokens; decode 5.2 s → 1.8 s Decode time = output tokens ÷ tokens per second
Skip/shrink the rewrite 900 ms → 0–200 ms First turns have no history to resolve; a small model suffices otherwise
Rerank to 4 chunks prompt 6,050 → 2,480 tokens; TTFT 1.2 s → ~0.6 s Prefill time grows with prompt length
Prompt caching 1,400 of 2,480 input tokens cached Cached prefixes skip most of the prefill work and cost less
Citation check during streaming removed 300 ms from the critical path Run checks on sentences as they complete

Where each piece runs and what to watch:

Component Metric to alert on Typical fix when it regresses
Gateway p95 queue time > 100 ms Scale out; check connection limits for long-lived streams
Retrieval + rerank p95 > 400 ms Smaller candidate set, warm caches, reranker on GPU
Model call TTFT p95 > 1 s, tokens/s drop Check prompt-size drift (cached tokens falling), provider status, route to another region
Output length p95 output tokens > 300 A prompt change made answers longer; revert or tighten the format instruction

The output-token distribution is the metric teams forget: one prompt edit that adds "be thorough" can quietly add two seconds to every answer.

18–32 min Deep dive

You I'd go deeper on three things: measuring correctly, the output-side levers, and the input and pipeline levers including tail latency.

Interviewer Start with measurement. What could mislead you?

Deep dive 1 · Measuring the right thing

  • Separate time to first text from total time. They have different causes (prompt and pipeline length vs. output length) and different fixes.
  • Look at percentiles, not averages. p95 is often driven by a minority of requests: long answers, retries after rate limits, or cold caches.
  • Break p95 down by cause: output length bucket, cache hit or miss, model, region. A p95 problem caused by 5% of requests with 1,500-token answers needs a different fix from one caused by queueing.
  • Measure quality alongside every change on the same evaluation set. A latency win that drops answer quality isn't a win.

Interviewer You leaned on shorter answers. Isn't that just giving users less?

Deep dive 2 · Output-side levers

  • Length control is product design, not a hack. Most answers were long because of filler: restating the question, generic caveats. Ask for "the answer first, then up to three bullet points" and measure on the evaluation set that completeness doesn't drop. Offer "show more detail" for users who want it.
  • Streaming changes perception more than anything else. People start reading at the first token. Render Markdown progressively, and show status lines for tool steps ("Searching docs…").
  • Smaller models where they're good enough. Route simple questions to a faster model; small models often generate 2–3× more tokens per second.
  • If self-hosting: speculative decoding, quantization and models with grouped-query attention all raise tokens per second. With hosted APIs, choose the provider's lower-latency model tiers or regions.

Deep dive 3 · Input and pipeline levers

Shrinking the critical path. The critical path is the chain of steps that must finish before the first token. Work that doesn't need to block it shouldn't:

  • Skip the rewrite on first turns, and use a small model otherwise.
  • Speculative retrieval: start retrieving with the raw question while the rewrite runs; if the rewritten query differs a lot, run a second retrieval and merge. Usually the first is good enough.
  • Parallelize independent work: retrieval from different sources, tool calls that don't depend on each other.

Caching at several layers:

Scroll sideways to see the whole diagram.

Caching at several layersComponents: Request; Response cache (exact repeats, scoped); Retrieval (rewrite · search · rerank); Answer LLM; Response; Embedding cache (frequent queries); Retrieval cache (same query, 10 min); Prompt cache (provider: static prefix). Flow: Request to Response cache; Response cache to Retrieval (miss); Retrieval to Answer LLM; Answer LLM to Response; Retrieval to Embedding cache; Retrieval to Retrieval cache; Prompt cache to Answer LLM (prefix hit).RequestResponse cacheexact repeats, scopedRetrievalrewrite ·search · rerankAnswer LLMResponseEmbedding cachefrequent queriesRetrieval cachesame query, 10 minPrompt cacheprovider: static prefixmissprefix hithit: skip everything
Caching at several layers. An exact response cache can skip everything. On a miss, retrieval uses embedding and retrieval caches, and the provider's prompt cache speeds up the static prefix of the prompt. Each layer has its own key and invalidation rule.
  • Response cache for exact repeated questions (with careful scoping).
  • Provider prompt caching for the static prefix: instructions and tool definitions. Keep it byte-identical and first.
  • Retrieval cache for repeated queries within a short window.
  • Embedding cache for frequent query strings.

Tail latency:

  • Timeouts with fallbacks: if retrieval takes longer than 300 ms, use what has arrived.
  • Retry budgets: a retry after a 429 can double latency; prefer capacity headroom and fallback models over blind retries.
  • Hedged requests for idempotent calls with long tails (send a second request after the p95 time and use whichever returns first), within cost limits.
  • Region placement: run retrieval and the gateway in the same region as the model endpoint.

32–37 min Trade-offs

Change Saves Cost or risk Mitigation
Streaming ~5 s to first text Can't hold text for checks Check while streaming; mark unsupported sentences
Shorter answers ~3.4 s total Less detail "Show more"; completeness check in evaluation
Small rewrite model ~0.7 s Slightly worse rewrites Evaluate retrieval recall with the new rewrites
4 reranked chunks instead of 12 ~0.6 s Lower recall if the reranker misses Rerank 50 candidates; monitor "not found" rate
Speculative retrieval ~0.2 s Extra retrieval calls Only when the rewrite is slow
Hedged requests Tail latency More calls and cost Only for idempotent, cheap calls
Smaller answer model Faster tokens Quality on hard questions Route by difficulty, not globally

Order of work: streaming (cheap, biggest perceived gain), then answer length, then the rewrite model, then reranking to fewer chunks, then caching and tail work. Re-measure after each step.

37–40 min Wrap-up and likely follow-ups

Close with: "From traces, decode time dominates, so I'd stream, shorten default answers and move the rewrite to a small model, then rerank to four chunks and cache the static prompt. That moves first text from 8.2 s to about 1.4 s and completion to about 3.5 s, with every change checked against the evaluation set."

Likely follow-ups:

  • What if quality drops with shorter answers? Find which question types need detail and allow longer answers for those, or route them to a different prompt.
  • How would this change if we self-hosted? Add continuous batching, quantization, speculative decoding and right-sized batches for the latency target; measure TTFT and tokens/s per GPU.
  • How do you stop regressions? A latency budget per span in CI on a replayed traffic sample, and alerts on p95 per span in production.

What interviewers listen for

  • Asking which latency (first text or total) before proposing fixes.
  • Decomposing time with real numbers and knowing decode time scales with output tokens.
  • Streaming and output length as the first levers.
  • Checking quality after each optimization.

Red flags

  • "Use a faster GPU" or "switch providers" before measuring.
  • Removing the citation check to save 300 ms.
  • Talking only about averages.

Discussion

Help us improve our content — give feedback. Spotted an error, have a better explanation, or got asked a follow-up in a real interview? Share it here.