AI Foundations0% complete
0%

Chapter 17 of 2525 chapters remaining

Saved on this device. Mark a chapter complete after reading.

MODULE 4 · LESSON 17 · 12 MIN

Latency, Throughput, and Reliability in AI Systems

By Siten Sanghvi · Published · Updated

A model's reply spends time in four places: the network, a queue for capacity, prompt processing (prefill), and writing the reply one token at a time (decode). The first three decide when the first token can appear; decode decides how long the rest takes. Which one dominates depends on your prompt, reply length, model, provider and load, so measure your own system. We also cover throughput, slow outliers, and keeping a feature working when calls fail. Timings here are illustrative unless attributed; vendor facts are dated 2026-11-09.

Where the time goes

Stage What happens Time grows with
Network Request and reply travel between you and the provider Distance, connection quality
Queue Request waits for capacity Load on the service
Prefill The model processes all prompt tokens together and produces the first token Prompt length, model size
Decode One step per further token (plain loop, BT-L09) Reply length, model size

BT-L09 introduced prefill and decode (Pope et al. name them). DistServe uses two common measures: time to first token (TTFT), the delay before the first piece of reply, and time per output token (TPOT), the average time for each later token. Papers time at the server; your user's clock also includes the network and any wait before the server accepts the request, as in Anthropic's latency guide, which counts TTFT from when the prompt is sent.

This lesson's model, used in every number below: first token = network + queue + prefill; total = first token + (N − 1) ÷ tokens per second, for N output tokens. Models that reason before answering emit hidden reasoning tokens first (on by default for Anthropic's current Claude 5 models, not older ones, and billed as output; thinking docs, BT-L16). These are extra decode steps, so first visible text comes later than this model says, and N includes them.

More prompt tokens mean more prefill work, so a very long prompt delays the first token. More reply tokens mean more decode steps. OpenAI's latency guide calls generating tokens almost always the slowest step, with a heuristic that cutting 50% of output tokens may cut about 50% of latency, but cutting 50% of the prompt only 1 to 5%, except for massive contexts. That is one vendor's rule of thumb, not a law.

EXHIBIT 17 / LATENCY

Explore the mechanism

First token is not finished.

Separate waiting, prompt processing and output generation.

First token is not finished.Network · 100 msQueue · 300 msPrefill · 600 msAfter first token · 5980 msFirst tokenComplete
TTFT1.00 s
Total completion6.98 s

First visible content: 1.00 s

Changing streaming changes when content is shown; it does not change this synthetic compute timeline. KV caching can avoid recomputing cached key/value states, but is not unlimited memory.

Inspect the example data and reasoning
First token is not finished. — current illustrative state
ElementWhat to notice
Network100 ms
Queue300 ms
Prefill600 ms
After first token5980 ms

Illustrative timing model: 100 ms network plus queue, prefill and (N−1)/rate. No real service measurements or guaranteed speeds.

Read the mechanism without interacting
TTFT
Network, queueing and prompt processing contribute to the first visible token.
Completion
After the first token, additional output steps extend total response time.
Serving
Latency, throughput, batching and cache behavior need workload-specific measurement.

With the same compute timeline, streaming shows the first token earlier; it does not shorten the generation interval.

Try explaining it: Would you reduce the queue or the output length to improve this user’s main wait?

Where the KV cache fits

BT-L09 introduced the KV cache (stored attention data for earlier tokens). Prefill builds it for the prompt; each decode step adds one token's entries (vLLM paper). It takes memory for every request in flight, limiting how many share a GPU. Prompt caching reuses work for a repeated prompt start; Anthropic's docs say you generally see better TTFT for long documents. BT-L16 covers cost.

Streaming changes what users see, not generation time

With streaming, the API sends pieces as they are generated (BT-L09). In scenario A below, text starts at 1.00 s instead of 6.98 s, yet generation still takes 5.98 s after the first token, so a person can read while the rest is written.

Streaming has costs: an error can arrive after the 200 success status (Anthropic errors), so handle half a reply. OpenAI's streaming guide notes partial output is harder to moderate.

Latency versus throughput

Latency is how long one request waits. Throughput is total work finished per second across all requests, such as tokens per second summed over users (DistServe). People also say "throughput" loosely for one stream's speed; this lesson calls that tokens per second.

They trade off through batching: serving requests together, which reuses the same model weights, like a shared ride that carries more riders per trip while each waits longer. Naive batching makes early requests wait for late ones, or new ones wait for the whole batch (vLLM paper). Iteration-level scheduling (Orca, now often called continuous batching) lets finished requests leave and new ones join between steps. Pope et al. report that smaller batches often give lower latency but use hardware less efficiently, raising cost per token, and that offline work is cheapest at larger batches.

With a public API the provider makes these choices; you choose per workload. Work that can wait (nightly summaries) suits batch-style endpoints (provider Batch APIs: results arrive later, a different mechanism with the same trade; see BT-L16), and the SRE book suggests separate objectives for interactive and throughput clients.

Averages hide slow requests

A percentile is a value that a given share of requests fall at or below: p95 is the time 95% of requests beat, so 5% are slower. Google's SRE guidance treats latency as a distribution: an average of 100 ms can coexist with 1% of requests taking 5 seconds (SRE book). Ten requests taking 0.9, 1.0, 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0 and 9.0 seconds have a mean of 2.05 s, above nine of the ten, while the slowest took 9.0 s.

For AI, latency depends heavily on reply length, so one p99 over 20-token and 2,000-token replies can mostly reflect the mix. Track percentiles per request type. Slow calls compound: if each call independently has a 1% chance of being slow, a task making 5 sequential calls (an agent, BT-L15) has 1 − 0.99^5 ≈ 4.9% chance of at least one slow call.

Failures to expect

  • Rate limits (429). Limits count more than one unit, such as requests and tokens per minute, and the first one hit triggers the error (OpenAI, Gemini). They apply to an organization or project, not each end user. Bursts count: Anthropic says 60 requests per minute might be enforced as one per second. A response may include Retry-After (RFC 6585); OpenAI says treat it as a minimum wait. Some 429s cannot be retried away: Anthropic's spend-cap 429 has no retry-after and fails until access resumes.
  • Overload and server errors. Not a rate limit: OpenAI returns 503 and Anthropic 529 when temporarily overloaded; 500 and 504 also occur.
  • Silent quality problems. Anthropic's 2025 postmortem describes three infrastructure bugs that degraded some responses for weeks; its evaluations did not capture what users reported. OpenAI recommends pinning to a model snapshot, since snapshots can differ, and Anthropic says each model ID is pinned. Anthropic's page adds that serving infrastructure around a pinned ID can change, so pinning does not replace checks (BT-L19).

Reliability patterns

  • Timeouts. The SRE book's cascading-failures chapter says to set a deadline: none, or a very high one, lets stuck calls hold resources, while a short one fails expensive requests consistently. A long reply is expensive, so consider a short first-token timeout plus a longer total deadline (this lesson's suggestion).
  • Retries. Retry only temporary errors. Honor Retry-After, then back off exponentially with random jitter, which spreads retries so clients do not return together (SRE book, AWS). Cap attempts and total time. Do not stack layers: three layers each making 4 attempts can send 4³ = 64 calls for one user action. SDKs may already retry (Anthropic's twice by default), so count them.
  • Circuit breaker. Wrap the call. When failures reach a threshold, calls fail immediately without being made, so a hanging dependency cannot use up your resources; after a while one trial call checks recovery (Fowler).
  • Fallbacks. Graceful degradation gives a cheaper or lower-quality result under stress (SRE book). For AI, that can be a smaller model, a saved answer or a "try again" message. A second provider needs your prompts re-evaluated, since models respond differently.

Set targets with SLOs

A service level indicator (SLI) is a measurement, like TTFT. A service level objective (SLO) is a target for it, such as "99% of requests complete in under 100 ms" (SRE book). An error budget is the rate at which the SLO may be missed; 100% is unrealistic. A made-up chat SLO: 95% of requests show a first token within 2 s, 99% finish within 30 s, 99.5% do not error. Percentile targets such as 95% and 99% put the tail into the objective; a target on the average would not. An SLO covers only the indicators you pick: this one covers speed and errors, not whether answers are good, so measure quality separately (BT-L19).

Try it

Check these with the model above (network 100 ms, 50 tokens/s).

Scenario Queue (ms) Prompt processing (ms) Output tokens First token (s) Total (s)
A: baseline 300 600 300 1.00 6.98
B: long prompt 300 3000 300 3.40 9.38
C: long reply 300 600 1000 1.00 20.98
D: peak load 2000 600 300 2.70 8.68

With streaming on, log request-sent, first-chunk and last-chunk times plus token counts for 20 requests; compute TTFT, total and tokens/s = (tokens − 1) ÷ (last chunk − first chunk). Treat a 20-request p95 as rough.

The takeaway

In a typical serving setup, the first token waits for network, queue and prompt processing (and any hidden reasoning), and each later token takes one decode step. Streaming changes when text appears, not when generation ends. Batching trades one request's latency for system throughput, and averages hide slow outliers. Provider calls need timeouts, capped retries with backoff and jitter, circuit breakers, fallbacks and SLOs that include the tail. Numbers here are illustrative; measure your own system.

Up next

AI Hallucinations, Prompt Injection, and Safety Guardrails Explained: how an AI system can fail or be misused, and the controls that limit harm.

VISUAL FIELDNOTES / 17

Keep the big picture.

A one-page visual companion. Save it, print it, or explain it to someone else.

Separate waiting, prompt processing and output generation. Illustrative timing model: 100 ms network plus queue, prefill and (N−1)/rate. No real service measurements or guaranteed speeds.View the full-size sheet ↗

First token is not finished.

Separate waiting, prompt processing and output generation.

One US Letter page · Vector artwork · Fits A4 when printed to fit

Read the key points as text
TTFT
Network, queueing and prompt processing contribute to the first visible token.
Completion
After the first token, additional output steps extend total response time.
Serving
Latency, throughput, batching and cache behavior need workload-specific measurement.

Remember: Network, queueing and prompt processing contribute to the first visible token.

Try it: With the same compute timeline, streaming shows the first token earlier; it does not shorten the generation interval.

Recall: Would you reduce the queue or the output length to improve this user’s main wait?

OPTIONAL CHECK

Check your understanding.

The optional check requires JavaScript. You can continue reading the lesson.

YOUR LEARNING

Keep your place.

Your progress is saved on this device.