AI Engineering Interview Questions: Latency & Cost in Production
Reviewed by Mark Dickie · Last updated
AI production latency-cost tradeoffs are the balance between how fast a model returns predictions and how much each inference costs in compute, memory, and infrastructure. For an AI engineering interview, you should know how token streaming, batch size, quantization, and model routing each shift the latency-versus-cost curve, and you should be able to reason about p50/p99 latency targets against per-request dollar cost. Interviewers want to see that you can name concrete knobs (KV-cache sizing, speculative decoding, dynamic batching) and explain when each one helps, hurts, or just moves the bottleneck. The questions below test that working knowledge under time pressure — the kind of quick, defensible reasoning you will need in a system-design round or a live troubleshooting scenario at the whiteboard.
What does an AI production interview test about latency and cost?
The core skill is reasoning about the full serving stack, not just the model. You are typically given a scenario — say, an LLM endpoint averaging 3.2 seconds per response at $0.02 per request — and asked to cut both numbers. Strong answers move through the stack in a specific order rather than jumping to the first optimization that comes to mind.
| Optimization | Latency Impact | Cost Impact | When to Reach For It |
|---|---|---|---|
| Dynamic batching | Amortizes kernel launch overhead; lowers p50 | Higher GPU utilization lowers cost per token | Traffic has enough concurrency to fill batches |
| Quantization (INT8/FP8) | Reduces memory bandwidth pressure; faster decoding | Smaller model footprint; can use cheaper GPUs | Accuracy budget allows it; inference-bound workloads |
| Speculative decoding | Cuts decode steps via a draft model; can halve latency | Extra forward passes for draft model; net cost depends on acceptance rate | Long output sequences where latency dominates |
| KV-cache tuning | Avoids recomputation of past tokens; large latency win on long contexts | Memory-greedy; oversizing wastes VRAM | Conversational or long-context workloads |
| Model routing (small model + fallback) | Small model answers fast for easy queries | Only expensive model fires on hard queries; cost drops | Query difficulty is separable at inference time |
| Prefix caching | Skips re-encoding shared system prompts | Near-free once cache is warm | Repeated system instructions or shared context prefixes |
How do you reason about latency vs. cost under pressure?
A structured approach keeps you from guessing. Work through the layers in order so the interviewer can follow your logic:
- Measure first — name the current p50, p99, and per-request cost before proposing anything.
- Identify the bottleneck — is latency dominated by prefill (prompt processing) or decode (token generation)? Is cost driven by GPU hours or token volume?
- Pick the cheapest lever that targets the bottleneck — caching and batching usually cost less than retraining or swapping hardware.
- State the tradeoff explicitly — quantization may drop accuracy; speculative decoding raises cost if the draft model's acceptance rate is low.
- Propose a fallback or guardrail — autoscaling rules, circuit breakers, or a cheaper model that can absorb overflow traffic when the primary endpoint saturates.
What mistakes do candidates make when answering latency-cost questions?
The most common error is naming an optimization without explaining why it fits the scenario. Saying “use quantization” without checking whether the workload is memory-bandwidth-bound or compute-bound signals that you memorized a list rather than understanding the mechanism. Another frequent miss is ignoring the cost side entirely — candidates cut latency by adding GPUs or replicas and forget that the interviewer asked for a cost reduction too. The strongest answers tie every proposed change back to a number, even an estimated one, because production decisions are made on ratios and budgets, not on qualitative appeals to “faster” or “cheaper.”
Key facts
- Tarmac has 70 AI Engineering interview questions on this topic, 25 of them on this page, at difficulty 1–5 of 5.
- Tarmac tracked 4,175 job postings asking for AI Engineering in August 2026.
- Roles asking for AI Engineering advertise a median base salary of US$182,450, across 806 job postings as of August 2026.
- Tarmac last reviewed these AI Engineering interview questions on 31 August 2026.
At a glance
| Questions | 25 shown · 70 in the bank |
|---|---|
| Difficulty | 1–5 of 5 |
| Formats | Multiple choice, True / false, Fill in the blank, Multiple answer, Flashcard, Code output, Short answer, Coding exercise, Find the bug, Ordering |
| Interactive | 1 run your code against tests, in the app |
What you'll review
- latency cost
- tokens context
- streaming
- agent loops
- model routing
- llm caching
- llm observability
Practice questions
Try one before you open the answer. Pick an option and press Check; it's marked on the spot.
AI Engineering/ai-production/latency-cost
A production LLM API call is taking too long and costs too much per request. Which of the following strategies most directly reduces both latency and cost at the same time?#
Options
Show answer
Reducing max_tokens most directly lowers both latency and cost. LLM APIs are billed per token and the model generates tokens sequentially, so capping the maximum output length shortens the response time and cuts the token bill in one move. The other options either increase expense, have no effect on token count, or only help in error scenarios.
LLM APIs charge per token (input + output) and latency scales with the number of tokens generated. Capping max_tokens directly limits how many output tokens the model can produce, which simultaneously lowers the per-call cost and reduces time-to-last-token. Larger models increase both cost and latency, temperature does not affect token count or pricing, and retry logic only adds overhead when errors occur.
AI Engineering/ai-production/latency-cost
Caching the responses of identical LLM prompts (prompt caching / semantic caching) can reduce both API costs and end-user latency in a production AI system.#
Options
Show answer
True — caching LLM responses for repeated or semantically similar prompts reduces both cost and latency. A cache hit avoids making an API call altogether, so there is no token charge and the response is served in milliseconds from fast storage rather than waiting for the model to generate tokens. This is one of the simplest and most effective optimizations in production AI systems.
Prompt or semantic caching stores the result of a previously seen query and returns it immediately on a cache hit, bypassing the LLM API entirely. This eliminates the token cost for repeated queries and returns the response in milliseconds instead of seconds, directly improving both dimensions: cost and latency.
AI Engineering/ai-production/latency-cost
In LLM inference systems, the widely used metric whose acronym is TTFT measures the time from sending a request to receiving the _____ token of the response, while the metric commonly called TPOT (Time Per Output Token) measures the average time to generate each _____ token after the first.#
Show answer
In LLM inference systems, the widely used metric whose acronym is TTFT measures the time from sending a request to receiving the first token of the response, while the metric commonly called TPOT (Time Per Output Token) measures the average time to generate each output token after the first.
TTFT stands for Time To First Token — it measures the latency from sending a request until the first token of the response is produced, which captures perceived responsiveness in streaming chat interfaces. TPOT stands for Time Per Output Token — it measures the average time taken to generate each subsequent output token after the first one, capturing steady-state generation throughput. Together, TTFT and TPOT are the two standard, unambiguous latency metrics used across LLM inference benchmarking (e.g., NVIDIA, vLLM, LLMPerf).
AI Engineering/ai-production/latency-cost
A production LLM API receives many identical or near-identical prompts (e.g., FAQ answers). Which single technique most directly reduces both latency and per-request token cost for these requests?#
Options
Show answer
Implementing a semantic or exact-match response cache most directly reduces both latency and cost. For repeated or near-duplicate prompts, a cache returns a stored response immediately—skipping model inference entirely—so you pay zero additional token costs and serve the response in milliseconds instead of seconds.
Caching identical prompts returns pre-computed responses instantly, eliminating model inference entirely and thus reducing both latency and cost. Increasing model size raises both latency and cost. Streaming improves perceived latency but does not reduce total compute cost. Logging adds negligible overhead but doesn't reduce latency or cost on its own.
AI Engineering/ai-production/latency-cost
When optimizing the cost of calling a hosted LLM API (e.g., OpenAI, Anthropic), which of the following actions directly reduce the dollar cost per request? Select all that apply.#
Options
Pick every one that applies.
Show answer
Shortening the system prompt, truncating/summarizing conversation history, and switching to a smaller cheaper model all directly cut costs. LLM API pricing is based on token counts (input + output), so fewer input tokens and a lower per-token rate are the levers that matter. Off-peak timing and streaming do not change the number of tokens billed.
Token count is the primary driver of both input cost (charged per input token) and output cost (charged per output token) in LLM APIs. Prompt engineering to reduce unnecessary context, truncating conversation history, and compressing system prompts all reduce token usage. Request timestamp and the user's geographic region are not factors in token-based billing. Response streaming affects perceived latency but does not reduce the number of tokens generated or their cost.
AI Engineering/ai-production/latency-cost
In LLM production systems, what does TTFT stand for, and why is it a distinct metric from total response latency?#
Show answer
TTFT = Time To First Token. It measures the elapsed time from when a request is sent until the client receives the first generated token. It is distinct from total latency because total latency covers the full generation of all tokens, whereas TTFT captures only the initial delay (network round-trip + prefill/prompt processing). In streaming UIs, a low TTFT makes the system feel fast even if total generation takes several more seconds.
Time To First Token (TTFT) measures the delay from sending a request until the very first token of the response is received by the client. It is distinct from total response time (which covers all tokens) and throughput (tokens per second). TTFT is especially important in streaming UX because users see the response start arriving sooner even if total generation time is the same. It is NOT the same as total latency.
AI Engineering/llm-foundations/tokens-context
A common back-of-the-envelope rule for English text is roughly 4 characters per token. This estimates the token count of a string using that heuristic. What does it print?#
import math
text = "The quick brown fox jumps over the lazy dog today"
estimate = math.ceil(len(text) / 4)
print(estimate)Show answer
13
The string is 49 characters; ceil(49 / 4) = ceil(12.25) = 13. The ~4 chars/token rule is a quick estimate for budgeting context windows and cost, not an exact count — real tokenizers (BPE) split on sub-word units, so whitespace, punctuation, code, and non-English text all change the ratio. For anything that must be exact (e.g. enforcing a hard context limit) you should call the model's real tokenizer rather than rely on this heuristic.
AI Engineering/ai-production/streaming
Why do production chat UIs stream tokens, and what does streaming improve versus what it does not?#
Show answer
Streaming sends tokens to the client as they're generated rather than waiting for the full completion, which dramatically lowers perceived latency — the user sees the first token (time-to-first-token) in a fraction of a second instead of staring at a spinner for the whole response. What it does not change is the total time to finish or the total cost: the same number of tokens are generated and billed, so streaming improves perceived responsiveness, not throughput or price.
Streaming is purely a latency-perception win: tokens are flushed incrementally so the user gets immediate feedback (low time-to-first-token), which matters a lot for long generations. It does not reduce total generation time, total tokens, or cost — those are fixed by the output length. It does add engineering cost: you must handle partial output, parse incrementally, and deal with mid-stream errors and cancellation.
AI Engineering/ai-production/latency-cost
Streaming a response token-by-token to the client, instead of waiting and returning it all at once, reduces the total number of tokens generated and therefore the total dollar cost of the request.#
Options
Show answer
False. Streaming changes only the delivery pattern — how and when tokens reach the client — not how many tokens the model actually generates. The same output is produced and billed either way; streaming's real benefit is perceived responsiveness, a much lower time-to-first-token, not a reduction in total latency, token count, or price.
Streaming changes only the delivery pattern — how and when tokens reach the client — not how many tokens the model generates. The same output is produced and billed either way; streaming's actual benefit is perceived responsiveness (a much lower time-to-first-token, so the user sees output start almost immediately instead of staring at a blank screen for the full generation time), not a reduction in total latency, token count, or price.
AI Engineering/agents/agent-loops
Implement billed_input_tokens(base, per_step, steps). An agent loop re-sends its whole transcript on every iteration. Before the first model call the context holds base tokens; every iteration then appends per_step tokens.#
Starter code
def billed_input_tokens(base, per_step, steps):
# TODO: each iteration re-sends everything before it
return base + per_step * stepsYour solution must pass
- single iteration
- four iterations
- ten iterations
This one is written and run, not read. Solve it in the app and your code is executed against these tests and the hidden ones.
AI Engineering/ai-production/model-routing
Your endpoint handles high volume: ~90% of requests are simple intent classifications, ~10% are open-ended reasoning that genuinely needs your most capable (expensive) model. You want to cut cost without hurting quality on the hard 10%. What is the most effective architecture?#
Options
Show answer
Route by difficulty: cheaply classify each request and send the easy majority to a small model, escalating only the hard cases to the large model — a model cascade. This matches each request to the cheapest model that can handle it, so you pay the premium only where it buys quality. Sending everything to the small model sacrifices the hard 10%, capping max_tokens truncates exactly the open-ended cases that need room, and caching only helps repeated inputs.
Model routing (a cascade) matches each request to the cheapest model that can handle it: a fast classifier sends the easy 90% to a small model and escalates only the hard 10% to the expensive one, so you pay the premium where it actually buys quality (d). Small-model-for-everything (a) sacrifices the 10% that needed the big model. Capping max_tokens (b) just truncates outputs — it hurts exactly the open-ended cases that need room. Caching (c) only helps repeated inputs and does nothing for the volume of distinct queries.
AI Engineering/ai-production/latency-cost
A chat feature feels slow and is expensive at scale. Which techniques are valid ways to reduce latency and/or cost in a production LLM application?#
Options
Pick every one that applies.
Show answer
Valid levers are streaming tokens to lower perceived latency, routing easy requests to a smaller cheaper model while reserving the large model for hard ones, caching responses or prompt prefixes for repeated requests, and trimming unnecessary context while capping max_tokens to what the task needs. Each cuts cost, latency, or both. Padding every prompt with extra few-shot examples does the opposite: it inflates input tokens on every call and beyond a point adds no accuracy.
Streaming (a) doesn't change total compute but dramatically improves perceived speed by showing the first tokens immediately. Model routing / cascading (b) sends the bulk of easy traffic to a cheaper model, cutting average cost and latency while preserving quality on the hard tail. Caching (c) avoids paying for work you've already done. Trimming context and bounding output length (e) reduces both input and output tokens, which is where the bill and the time go. Indiscriminately padding every prompt with more few-shot examples (d) does the opposite — it inflates input tokens (cost and latency) on every call, and beyond a point adds no accuracy, so it is a regression, not an optimization.
AI Engineering/ai-production/latency-cost
Which of the following strategies directly reduce token spend (input + output) in a production LLM application? Select all that apply.#
Options
Pick every one that applies.
Show answer
The strategies that directly cut token spend are compressing or summarizing historical conversation turns before appending them, capping max_tokens to what the task plausibly needs rather than the default, using structured output so the model emits only the fields you need rather than verbose prose, and retrieving only the top-2 or top-3 passages instead of top-20. Switching to a larger-context model does not reduce spend — it only raises the ceiling, and without actively trimming the prompt it is neutral at best.
Summarising history (a) directly shrinks input tokens for every subsequent turn in a long conversation. Setting a task-appropriate max_tokens cap (b) prevents the model from generating a 2,000-token essay when you need a 50-token answer — the difference is billed output tokens. Structured output (c) is a meaningful lever: a JSON object with three fields uses far fewer output tokens than the same information in a conversational paragraph, and it also eliminates post-processing. Limiting retrieved passages to the genuinely useful few (e) reduces input tokens proportionally to what you cut. Switching to a larger-context model (d) does not reduce token spend — it only raises the ceiling on how many tokens you can use; without actively trimming the prompt, it is neutral at best.
AI Engineering/ai-production/latency-cost
For a fixed total token count, a request with 900 input tokens and 100 output tokens will be cheaper and faster than one with 100 input tokens and 900 output tokens.#
Options
Show answer
True. Output tokens are generated auto-regressively, one forward pass per token, so 900 output tokens require 900 sequential decoding steps that dominate latency and compute. Input tokens are processed in parallel in a single, far cheaper prefill pass, and most providers price output at 3-5× the input rate to reflect this. So 900 input plus 100 output is cheaper and faster than the reverse. This is why structured output and speculative decoding target output-token efficiency.
Input tokens and output tokens are priced and computed differently. Output tokens are generated auto-regressively — one forward pass per token — so generating 900 output tokens requires 900 sequential decoding steps, which dominates both latency and compute cost. Input tokens are processed in parallel in a single prefill pass that is far cheaper per token. Most providers price output tokens at 3–5× the input rate to reflect this. In latency-sensitive applications, techniques like constrained decoding, structured output (to avoid verbose free-text), and speculative decoding target output-token efficiency precisely because that is where most of the cost and time lives.
AI Engineering/ai-production/latency-cost
This retries on rate-limit (429) errors but makes the outage worse. Which line is the problem?#
async function callWithRetry(fn, attempts = 5) {
for (let i = 0; i < attempts; i++) {
try {
return await fn();
} catch (err) {
if (err.status !== 429) throw err;
continue;
}
}
throw new Error("exhausted retries");
}Show answer
The bug is on line 7.
Line 7 continues immediately with no delay, so all five attempts fire back-to-back in microseconds. On a 429 the provider is telling you to slow down; retrying instantly hammers the endpoint and can extend or worsen the rate-limit window — a self-inflicted thundering herd. The fix is exponential backoff with jitter (e.g. await sleep(base * 2 ** i + random)), and ideally honoring the Retry-After header the API returns. Tight retry loops without backoff are a frequent cause of cascading failures under load.
AI Engineering/ai-production/llm-caching
What is prompt caching, and how should you structure a prompt to benefit from it?#
Show answer
Prompt caching lets the provider reuse the computed attention state for a large, stable prefix of your prompt (system instructions, few-shot examples, a long document) across requests, so repeated calls are cheaper and lower latency because the cached prefix is billed at a reduced rate and skips recomputation. To benefit, put the stable, reused content at the front of the prompt and the variable, per-request content (the user's question) at the end — caching keys off the longest matching prefix.
Caching works on a prefix match: the provider stores the key/value attention state for an unchanged leading span and reuses it on subsequent calls, cutting both cost and time-to-first-token. The practical rule is order-dependent — keep the big invariant blob (system prompt, tool definitions, long context document, few-shot exemplars) at the start and anything that changes per request at the tail, otherwise the cache misses on every call.
AI Engineering/ai-production/latency-cost
What is the difference between TTFT and TBT in LLM streaming latency, and which matters more for interactive versus batch workloads?#
Show answer
TTFT (Time To First Token) is the delay from sending the request until the first token arrives — dominated by prompt processing (prefill) and network round-trip. TBT (Time Between Tokens) is the interval between successive tokens during generation — set by the model's decode throughput on the provider's hardware. For interactive/chat workloads, TTFT determines perceived responsiveness: users notice a blank screen longer than slow streaming. For batch/background workloads (offline summaries, data extraction), total generation time (TTFT + tokens × TBT) matters more than either metric in isolation. Optimize TTFT by reducing prompt length (cache the static portion), using a faster/smaller model for the first chunk, or streaming early. Optimize TBT by requesting fewer tokens or a smaller model.
TTFT and TBT measure different bottlenecks: prefill vs decode. Interactive UIs are TTFT-sensitive (perceived snappiness); batch pipelines care about throughput. Knowing which metric to target determines whether you shorten the prompt or reduce output length.
AI Engineering/agents/agent-loops
This models an agent loop that re-sends its whole transcript each iteration. sent accumulates the input tokens billed across the run. What does it print?#
context = 1000 # system prompt + goal
sent = 0
for step in range(4):
sent += context # the whole transcript is re-sent
context += 500 # this step's tool call + result
print(sent, context)Options
Show answer
The loop prints 7000 3000, billing 1000, 1500, 2000 and 2500 input tokens across its four iterations, summing to 7000, while the transcript itself only reaches 3000 tokens. The gap is the whole point: every earlier token is paid for again on every later step, so the run costs more than twice the final context size. Counting only the tokens each step adds gives 4000 — the single-call intuition that makes agent bills surprising. At 10 steps the sum reaches 32,500 against a 6000-token transcript.
Trace the four iterations: the loop bills 1000, then 1500, then 2000, then 2500, summing to 7000, while context ends at 1000 + 4·500 = 3000. The point is the gap between those two numbers. The transcript grew to 3000 tokens, but the run was billed for 7000 — more than twice the final size — because every earlier token is paid for again on every later step. Option (b) is what you get by counting only the tokens each step adds, which is the intuition most people carry over from single-call pricing and the reason agent bills surprise teams. Option (c) mistakes the final context size for the amount billed. Extend the loop to 10 steps and the sum reaches 32,500 against a 6000-token transcript: the growth is quadratic, which is why trimming what you carry forward is the strongest cost lever in an agent loop.
AI Engineering/ai-production/model-routing
This fallback chain is supposed to drop to a cheaper model only when the primary is rate-limited or temporarily overloaded. Which line makes it silently mask real failures instead?#
const CHAIN = ["gpt-4o", "gpt-4o-mini"]; // primary, then cheaper fallback
async function complete(prompt: string) {
for (const model of CHAIN) {
try {
return await callModel(model, prompt);
} catch {
continue; // primary failed — fall back to the next model
}
}
throw new Error("all models in the chain failed");
}Show answer
The bug is on line 7.
Line 7's bare catch { swallows every error indiscriminately and falls through to the cheaper model. So a non-transient failure — a malformed request, an auth error, a content-policy block, or a bug in your own code — is silently downgraded to a weaker model (and reported only as the generic 'all models failed' if the whole chain is exhausted) instead of being surfaced. Worse, because the bare catch discards the error object, the code cannot implement the very policy it was written for: 'fall back only on 429/503.' The fix is to inspect the error and fall back only on transient/overload statuses, rethrowing everything else: catch (err) { if (isRetryable(err)) continue; throw err; }.
AI Engineering/ai-production/latency-cost
How does prompt caching work on hosted LLM APIs, and what must you do to get cache hits consistently?#
Show answer
Providers (e.g. Anthropic, OpenAI) cache the KV state computed from a prefix of the prompt. On a cache hit, they skip re-computing that prefix, cutting latency (prefill cost is paid once) and token price (cached-input tokens are typically billed at a fraction of uncached). To get consistent hits: (1) put the stable prefix first — system prompt, documents, tool definitions — and vary only the end (user message, conversation tail); (2) send requests before the cache entry expires (windows vary by provider, often minutes to hours); (3) keep the prefix byte-identical — any character change busts the cache for everything after it; (4) for Anthropic, mark eligible blocks with cache_control: {type: "ephemeral"} to opt in. Cache misses on stable prefixes are expensive and avoidable — the main cause is inserting dynamic content (timestamps, request IDs) near the start of the prompt.
Prompt caching reuses computed KV state across calls. The key discipline is prefix stability: put everything that doesn't change early and everything that varies late. Inserting dynamic content early is the most common reason caches miss.
AI Engineering/ai-production/streaming
Order the request lifecycle of a streamed chat completion, from user input to a rendered answer in the browser.#
Put these in order
Show answer
The streamed completion lifecycle runs in this order:
- Client sends the request; server opens a streaming connection to the model API
- Model prefills the prompt and emits the first token (time-to-first-token)
- Server relays incremental token deltas to the client as they arrive
- Client appends each delta, progressively rendering the answer
- Stream terminates with a stop/finish event and usage totals
Streaming improves perceived latency: the client opens a stream, the model prefills and emits the first token (TTFT — the metric users feel most), the server relays token deltas (commonly over SSE), the client appends and renders them incrementally, and the stream closes with a finish event carrying the stop reason and token usage. Note that total generation time is unchanged — streaming just surfaces tokens as they're produced instead of waiting for the whole completion.
AI Engineering/ai-production/llm-observability
Order the steps to add end-to-end observability tracing to an existing LLM feature in production.#
Put these in order
Show answer
Add end-to-end tracing in this order:
- Instrument the code to emit a trace span for every LLM call, capturing prompt, completion, and latency
- Propagate a single trace-id through the full request so all spans from one user turn are correlated
- Ship the spans to an observability backend (LLM-aware or general-purpose)
- Build dashboards or alerts for the metrics that matter: TTFT, total latency, cost, error rate
- Define sampling rules to control trace volume and cost in high-traffic production
Observability is layered bottom-up: first instrument individual LLM calls to capture the raw signal (prompt, completion, latency, token counts); then propagate a trace-id so multi-step agent calls form a coherent trace rather than isolated records; next export to a backend that can store and query spans at scale; then surface dashboards and alerts for operationally critical metrics; finally configure sampling because capturing every token of every call at volume is prohibitively expensive — sampling keeps costs manageable while preserving statistical coverage of failures.
AI Engineering/ai-production/latency-cost
Perceived responsiveness in streaming LLM applications is dominated by _____ to first token (TTFT), the gap between sending the request and receiving the first output token; once streaming starts, the ongoing delivery rate is measured in tokens per _____ (TPS).#
Show answer
Perceived responsiveness in streaming LLM applications is dominated by time to first token (TTFT), the gap between sending the request and receiving the first output token; once streaming starts, the ongoing delivery rate is measured in tokens per second (TPS).
TTFT (time-to-first-token) is the latency a user feels before anything appears on screen — driven by prompt-processing (prefill) time, which scales with input token count. TPS (tokens per second) governs how fast the stream fills in afterward — driven by the decode phase and is roughly constant per model/hardware configuration. Optimising for TTFT often means shorter prompts or prompt caching; optimising TPS means smaller models or speculative decoding.
AI Engineering/ai-production/latency-cost
A production LLM serving system processes requests using paged attention (e.g., vLLM). An engineer notices that average GPU memory utilization is only 55%, yet p95 TTFT has spiked to 800 ms under moderate load. They suspect KV-cache fragmentation is the root cause.#
Show answer
-
In paged attention (vLLM), the KV cache is divided into fixed-size blocks, and a new request only needs N total free blocks — not N contiguous blocks — because the block table can link non-contiguous pages. External fragmentation in the traditional sense therefore does not apply. The true cause of high TTFT under these conditions is internal fragmentation combined with scheduler watermark policy: each active sequence holds at least one partially filled page (wasting slots in the last allocated block), and vLLM's scheduler withholds new requests until the free-block pool drops below a reserved watermark. When many sequences each waste a fraction of their last page, aggregate utilization metrics report 55% raw byte occupancy but the free-block count falls below the watermark, causing the scheduler to queue incoming requests rather than admit them immediately. Additionally, if the system exhausts free blocks entirely, the scheduler must preempt (evict) in-flight sequences — recomputing or swapping their KV cache — before the new request can start prefill, directly adding latency. The coarse utilization metric masks this because it counts allocated bytes, not free block count.
-
Mitigation A — Reduce block size (page size): Smaller blocks (e.g., 8 tokens instead of 16) reduce internal fragmentation by shrinking the maximum wasted slots per sequence per block. Trade-off: more blocks means larger block-table metadata, increased pointer-chasing during paged attention kernels, and slightly higher scheduler bookkeeping overhead per step.
Mitigation B — Tune the scheduler's free-block watermark / admission policy: Lower the reserved free-block threshold (or implement finer-grained admission control based on per-request estimated block demand) so requests are admitted sooner when blocks are actually available. Trade-off: a lower watermark reduces queuing-induced TTFT but increases the risk of mid-generation preemption if block consumption is underestimated, which can cause expensive recomputation and hurt overall throughput.
Paged attention's block table design deliberately makes KV pages non-contiguous, so the classic OS external-fragmentation narrative (needing a large contiguous region) does not apply to vLLM's allocator. The real mechanisms behind high TTFT despite apparent available memory are: (a) internal fragmentation — each sequence wastes slots in its last partially filled block, inflating allocated-byte counts without providing usable capacity; and (b) vLLM's watermark-based scheduler policy, which queues or preempts requests when the free-block count drops below a threshold, even if raw byte utilization looks low. Effective mitigations therefore target internal fragmentation (smaller block size) or the admission policy (watermark tuning), both of which are orthogonal levers available at the serving layer without model changes.
AI Engineering/ai-production/latency-cost
A cost-optimization team is reducing LLM inference spend per 1 M output tokens. The following techniques are applied in a specific sequence to ensure each step's benefit compounds correctly and no step invalidates a previous one. Order them from first applied to last applied given these constraints:#
Put these in order
Show answer
The correct order is: (1) AWQ INT4 quantization → (2) GPU SKU & tensor-parallel selection → (3) continuous batching tuning → (4) semantic request routing → (5) KV-cache prefix caching. Each step depends on the one before it: quantization sets the memory budget that drives hardware choice; the serving engine is tuned against fixed hardware; routing is layered on a stable engine; and prefix caching is only effective once routing is stable enough to produce predictable, repeated prefixes.
The correct sequence is: (1) Quantize the model weights first (AWQ INT4) because all downstream hardware and serving decisions depend on the resulting memory footprint and accuracy profile. (2) Choose the GPU SKU and tensor-parallel degree once you know how large the quantized checkpoint is—this determines per-device memory and compute budget. (3) Configure the serving engine's continuous batching and batch-token limits against the now-fixed hardware topology. (4) Add semantic routing to split traffic between the large model and a smaller distilled model; routing policies build on a stable serving stack. (5) Finally enable prefix caching, which requires knowing the routing strategy to predict which prefix groups will recur frequently enough to be worth caching.
Related interview questions
Job market
See ai-engineering salaries and hiring demand from live job postings.
The other 45 questions
This page shows 25 and marks what you pick. That's as far as a page can go. A free account opens the other 45 and keeps every answer. What you miss comes back until it's right: after a day, then at longer gaps.
Free · the whole bank · 100 marked answers per 30 days · written feedback on the paid plan