- Support chat costs tripled: routing and caching. Problem: a retail support assistant sent every message to its largest model, and cost ran at three times the forecast. Pattern: a non-AI FAQ deflector first, then rules by risk and a small-first cascade with escalation, plus a stable cacheable prefix.
- In-product assistant latency: streaming and prefill. Problem: a SaaS assistant felt slow because of a long prompt and unstreamed replies. Pattern: a latency budget split into time to first token and decode time, then streaming, shorter prompts and answers, a cached prefix and a smaller model for simple intents.
- Classifying 2 million documents: batch and cascade. Problem: a public body priced one real-time model call per document far above its budget. Pattern: rules for coded documents, then batch processing with a cheap tier first and a larger model only for uncertain documents, with human sampling.
Under the hood: Tokenization and the context window
Intuition
A model sees integers, each naming a piece of text from a fixed vocabulary that each model family trains for itself. So the same text is a different number of tokens in different models.
Mechanism
Figure 6. Where token counts come from
sequenceDiagram
accTitle: Learning and applying a tokenizer
accDescr: Before the model is trained, a merge learner reads a text corpus and repeatedly stores the most frequent adjacent pair as a new symbol, building the vocabulary and merge list. At request time the Model gateway asks the tokenizer to count a prompt. The tokenizer applies the merges in learned order and returns token ids and a count, and the ids are sent to the model.
participant C as Training corpus
participant L as Merge learner
participant V as Vocabulary and merges
participant T as Tokenizer
participant G as Model gateway
participant M as Model
C->>L: text split into symbols
loop until the chosen number of merges
L->>L: count adjacent symbol pairs
L->>V: store the most frequent pair as a new symbol
end
G->>T: count tokens for this prompt
T->>V: apply merges in the learned order
V-->>T: token pieces
T-->>G: token ids and the count
G->>M: ids, if input plus output fit the window
Note over G,M: A different model has a different merge list, so a different count
How to read this: the loop happens once, before training; the lower half happens on every request.
- Sennrich, Haddow and Birch adapted byte pair encoding (BPE) to words: start from characters plus an end-of-word symbol.
- Repeatedly replace the most frequent adjacent pair with a new symbol. Vocabulary size is the initial symbols plus the number of merges, the paper's "only hyperparameter".
- At use time apply the merges in learned order, so any word can be encoded.
The paper's code on its toy dictionary (low 5, lower 2, newest 6, widest 3) gives the first merges (e, s) 9, (es, t) 9, (est, end-of-word) 9, (l, o) 7, (lo, w) 7; the unseen word "lowest" then encodes as low and est.
Anthropic's token-counting page says models from Claude 4.7 on use a newer tokenizer that produces approximately 30% more tokens for the same input, depending on content (as of 2026-10-22). The context window limits input plus output together.
Check yourself: a prompt counts 10,000 tokens on an earlier Anthropic model. Roughly how many on the newer tokenizer, and what happens to a fixed limit check?
About 13,000, depending on content. A check that passed at 10,000 can now fail, so a model upgrade is a budget event even with unchanged text.
What this means for architects
Under the hood: Attention and the KV cache
Intuition
To choose the next token the model looks back at every earlier position, and what it looks up there (key and value) never changes. The server keeps them: the KV cache. It grows by a fixed amount per token, and memory runs out before arithmetic does.
Mechanism
Figure 7. What is computed once and what is kept
sequenceDiagram
accTitle: Prefill fills the KV cache and decode appends to it
accDescr: During prefill the inference server runs all prompt tokens through the model weights in parallel and stores their keys and values in the KV cache. During decode it runs only the newest token, appends that token's key and value to the cache, reads all earlier keys and values for attention, and samples the next token.
participant S as Inference server
participant W as Model weights
participant K as KV cache
Note over S,K: Prefill, once per request
S->>W: run all n prompt tokens in parallel
W-->>S: keys and values for every layer and position
S->>K: store n keys and values
loop Decode, one step per output token
S->>W: run the newest token only
W-->>S: its key, its value and scores for the next token
S->>K: append the new key and value
K-->>S: all earlier keys and values, read for attention
Note over S: Sample the next token from the scores
end
How to read this: the first block happens once, the loop repeats per output token, and the cache is the only thing carrying information between steps.
- The Transformer paper defines attention as
softmax(Q K^T / sqrt(d_k)) V; the vLLM paper notes that in generation only the new token's key and value are computed.
- Bytes per token = 2 (key and value) x layers x KV heads x head dimension x bytes per value.
- PagedAttention's OPT-13B example: 2 x 5,120 (hidden size) x 40 (layers) x 2 (FP16 bytes) = 819,200 bytes, the paper's 800 KB per token (1 KB as 1,024 bytes), up to 1.6 GB for 2,048 tokens.
- Grouped-query attention shares keys and values among query heads; the Llama 3 paper states its models use GQA with 8 KV heads.
Head dimension = model dimension / heads = 128. For the 8B model, 2 x 32 x 8 x 128 x 2 = 131,072. Set sequences to 10: ten 8,192-token conversations hold 10 GiB on top of the weights.
Check yourself: the same 8B model with 32 KV heads (plain multi-head attention). How big is the cache per token?
4 times larger: 2 x 32 x 32 x 128 x 2 = 524,288 bytes, 512 KiB. KV bytes scale with KV heads, which is why GQA makes long context cheaper.
What this means for architects
Under the hood: Prefill and decode
Intuition
The prompt is read all at once, a large batch of arithmetic a GPU does well. The answer is written one token at a time, and each step re-reads the model's weights from memory, so memory bandwidth limits it.
Mechanism
Figure 8. Anatomy of one streamed request
sequenceDiagram
accTitle: Prefill then decode for one request
accDescr: The Client app sends a request through the Model gateway to the LLM provider. The provider queues the request, processes all prompt tokens in parallel during prefill and returns the first token, which ends the time to first token. It then generates one token per step, each streamed back to the client, and finishes with a stop event and usage.
participant C as Client app
participant G as Model gateway
participant P as LLM provider
C->>G: request with 9,000 input tokens
G->>P: model request, stream on
Note over P: Queue wait, then prefill - all prompt tokens in parallel
P-->>G: first token
G-->>C: first token
Note over C,P: Time to first token = queue + network + prefill
loop each remaining output token
Note over P: Decode step - one token, weights read again
P-->>G: next token
G-->>C: next token
end
P-->>G: stop event with usage
Note over C,P: Total = TTFT + (N minus 1) x TPOT
How to read this: the part before the loop is paid once and grows with prompt length; the loop is paid per output token.
- The vLLM paper: the prompt phase parallelises over the prompt; the generation phase is sequential, memory-bound, and most of a single request's latency.
- Sarathi-Serve: prefill is compute-bound, decode memory-bound; on Mistral-7B on an A100 one decode token costs nearly the same linear operations as 128 prefill tokens.
- DistServe defines TTFT as the duration of prefill and TPOT as the average time per token after the first.
Check yourself: the cache removed 6,000 of 9,000 prompt tokens from prefill. Does total latency drop more than, less than, or the same as TTFT?
The same: 0.6 s in both. The 399 decode steps are unchanged and dominate the total.
What this means for architects
Under the hood: Continuous batching and paged KV memory
Intuition
Because decode is memory-bound, running many requests together shares each weight read. Fixed batches waste slots when requests finish at different times, and reserving worst-case cache space wastes memory. Continuous batching fixes the first, paged memory the second.
Mechanism
Figure 9. Life of a request in a continuous-batching server
stateDiagram-v2
accTitle: Request states in a continuous-batching server
accDescr: A request waits in a queue, is admitted to the running batch when memory blocks are free, and generates one token per iteration, taking a new block when its last block is full. It finishes on an end token or the token limit and its blocks are freed. If memory runs out the newest requests are preempted, their blocks swapped out or dropped for recomputation, and they return to waiting.
[*] --> Waiting: request arrives
Waiting --> Running: admitted, blocks are free
Running --> Running: one iteration, one token, new block when full
Running --> Finished: end token or token limit
Running --> Preempted: no free blocks, newest request first
Preempted --> Waiting: blocks swapped out or dropped for recompute
Finished --> [*]: blocks freed
How to read this: each box is a state, arrows carry the condition, and the loop on Running is the per-iteration step continuous batching makes possible.
- Orca (OSDI 2022) replaces request-level scheduling, where the batch stays fixed until every request finishes, with iteration-level scheduling: finished requests return at once and a new one starts after the current iteration. The authors report 36.9 times the throughput of NVIDIA FasterTransformer at the same latency on GPT-3 175B.
- The vLLM paper measures that earlier systems, pre-allocating a contiguous chunk per request, held real token states in only 20.4% to 38.2% of KV memory.
- PagedAttention uses fixed-size blocks (16 tokens by default) and a block table, and allocates a block only when the last fills, so waste stays within one block.
- When memory runs out, vLLM preempts whole requests (latest arrivals first) and swaps them to CPU or recomputes. It reports 2 to 4 times the throughput of FasterTransformer and Orca at similar latency.
What this means for architects
Under the hood: Quantization
Intuition
Store 16-bit weights in 8 or 4 bits and the model needs half or a quarter of the memory, and since decode is limited by bytes read per token it can run faster. The price is rounding error.
Mechanism
Figure 10. Offline quantization and online use
sequenceDiagram
accTitle: Quantizing weights offline and using them online
accDescr: Offline, a quantizer uses a small calibration sample to choose low-bit weight values that keep layer outputs close to the original and stores the low-bit weights with their scales. Online, at every decode step the GPU kernel reads the low-bit weights, which is a fraction of the bytes, dequantizes them inside the kernel and multiplies them with 16-bit activations.
participant D as Calibration sample
participant Q as Quantizer
participant S as Weight store
participant K as GPU kernel
Note over D,S: Offline, once per model
D->>Q: a small sample of inputs
Q->>Q: choose low-bit values per weight group to keep layer outputs close
Q->>S: store low-bit weights and scales
Note over S,K: Online, every decode step
loop each decode step
K->>S: read low-bit weights, a fraction of the bytes
Note over K: Dequantize in the kernel, multiply with 16-bit activations
end
How to read this: the top block is paid once and may change quality; the loop is where the saving shows up as speed.
Weight memory = parameters x bits / 8, plus small per-group scales. For an 8B model at 2,039 GB/s the decode floor is a ceiling for weight-bound decode, not a forecast:
- LLM.int8() (Dettmers et al.) quantizes the large matrix multiplications to 8 bits, halving inference memory with no loss in their tests.
- GPTQ (Frantar et al.) is a one-shot post-training method that compresses weights to 3 or 4 bits with negligible accuracy degradation in their measurements. At batch size 1 it reports about 3.25 times speedup for 3-bit OPT-175B (one A100, against FP16 on 5 GPUs) and 4.5 times (two A6000, against FP16 on 8 GPUs). It notes that LLM.int8() has the same runtime as FP16.
What this means for architects
Under the hood: Speculative decoding
Intuition
A small draft model guesses a few tokens; the large model checks them all in one pass and keeps those it would have produced. Because decode is memory-bound, checking several positions costs little more than one token, so accepted guesses are nearly free.
Mechanism
Figure 11. One speculative step with four guesses
sequenceDiagram
accTitle: One speculative decoding step
accDescr: The draft model guesses four tokens one after another. The target model scores the prefix plus all four guesses in one parallel pass. Guesses one to three are accepted and guess four is rejected, so the target model supplies a corrected token, and four tokens are emitted from a single target pass.
participant Q as Draft model
participant P as Target model
participant O as Output stream
Q->>Q: guess tokens 1 to 4, one after another, cheaply
Q->>P: prefix plus the four guesses
P->>P: one parallel pass scores all four positions plus one more
Note over P: Guesses 1 to 3 accepted, guess 4 rejected
P->>O: tokens 1 to 3 plus one corrected token
Note over O: Four tokens from a single target pass
How to read this: the target runs once per step, and the tokens emitted depend on how many guesses it accepts.
- Leviathan et al. (Google) and Chen et al. (DeepMind) published the method independently: a drafted token is kept with probability min(1, p/q), else a replacement is sampled. Both prove the output distribution equals sampling from the target alone, with 1 to gamma + 1 tokens per target pass.
- Only Leviathan et al. derive the speed formulas. With alpha the average acceptance probability (assumed equal at each position), tokens per pass are
E = (1 - alpha^(gamma+1)) / (1 - alpha) (Equation 1) and wall-time improvement is E / (gamma x c + 1) (Theorem 3.8), c being draft run time over target run time.
Measured: 2.3 to 3.4 times on T5-XXL (Leviathan et al.) and 2 to 2.5 times on Chinchilla 70B in a distributed setup at batch size 1 (Chen et al.), whose gain plateaus or regresses as the number of guesses grows.
What this means for architects
Under the hood: Prompt caching and prefix stability
Intuition
A token's cached state depends on every token before it, so prompts share cached work only where they are identical from the first token (the vLLM paper: the same tokens can have different KV cache at different positions). Put the stable part first and the changing part last.
Mechanism
Figure 12. A prefix cache across three requests
sequenceDiagram
accTitle: Prefix cache across three requests
accDescr: The first request misses the provider prefix cache, which stores the processed prefix. The second request with the same start and a new user turn hits it and reports cache read tokens. The third request has an edited system prompt, so the match breaks at the edit and everything after it is processed again.
participant O as Orchestrator
participant M as Model gateway
participant P as LLM provider
participant C as Provider prefix cache, internal
O->>M: request 1 - tools, system, reference text, user turn 1
M->>P: model request
P->>C: look up the longest matching prefix
C-->>P: none
P->>C: store the processed prefix
P-->>M: answer, usage shows cache creation tokens
O->>M: request 2 - same start, user turn 2
M->>P: model request
P->>C: look up the longest matching prefix
C-->>P: prefix found
P-->>M: answer, usage shows cache read tokens
O->>M: request 3 - system prompt edited near the top
M->>P: model request
Note over P,C: Match breaks at the edit, everything after it is a miss
P-->>M: answer, usage shows cache creation tokens again
How to read this: the cache is inside the provider, so the usage fields in each reply are the evidence of a hit or a miss.
Implementation is mostly undocumented; the contract is documented.
An entry is available only after the first response begins, so parallel requests sharing a prefix should wait for the first. Anthropic's multipliers: writes 1.25 times the base input rate (5-minute lifetime), reads 0.1 times (some models differ).
Check yourself: for n = 3 requests inside the lifetime, what are the cached and uncached costs in prefix-lengths?
1.25 + 0.1 x 2 = 1.45 cached against 3 uncached. Every further hit inside the lifetime widens the gap.
What this means for architects
Under the hood: Streaming responses
Intuition
The provider sends tokens as they are produced. Total time is unchanged, but the user reads from the first token and can cancel early.
Mechanism
Figure 13. A stream through the system, with a failure after the first token
sequenceDiagram
accTitle: Streaming path and a mid-stream failure
accDescr: The Client app opens an event stream through the API gateway to the Orchestrator and Model gateway, which call the LLM provider with streaming on. Token deltas flow back along the same path and the interface shows text from the first delta. In the normal case the provider ends with a stop event and usage. If the connection fails after the first token, the HTTP status 200 has already been sent, so the Orchestrator keeps the partial text, sends an error event with a partial flag and does not retry silently.
participant C as Client app
participant G as API gateway
participant O as Orchestrator
participant M as Model gateway
participant L as LLM provider
C->>G: open event stream
G->>O: forward request
O->>M: generate, stream on
M->>L: model request
L-->>M: message start, then token deltas
M-->>O: token deltas
O-->>G: token deltas
G-->>C: data lines, text appears from the first delta
alt Stream completes
L-->>M: stop event with usage
M-)O: usage record
else Failure after the first token
L--xM: connection drops or error event
Note over O: Status 200 was already sent, keep the partial text, no silent retry
O-->>C: error event with partial flag
end
How to read this: the same arrows carry every delta to the screen; the else branch is the case where the HTTP status can no longer signal the error.
Provider streams use server-sent events, defined in the WHATWG HTML Standard.
Anthropic's streaming documentation (as of 2026-10-22) adds message_start, content blocks with deltas, message_stop and ping events. Tool-call arguments stream as partial JSON, parsed only after the block stops, and errors can arrive inside the stream (an overloaded_error instead of HTTP 529).
What this means for architects
Decision framework
Figure 14. Choosing model-layer policies
flowchart TD
accTitle: Choosing model-layer policies
accDescr: A chain of decisions. Route with rules if the request type is known, otherwise use a cascade or classifier. Lay out a stable prefix if one exists and traffic keeps it warm. Use a semantic cache only for generic answers that do not depend on the user or changing data. Stream if a person is waiting and batch if not. Self-host only for a hard residency, pinning or sustained-load requirement, otherwise use an API behind a Model gateway.
R{"Request type known before the call?"}
R1["Rules first"]
R2["Cascade or classifier, see Figure 3"]
A{"Stable prefix above the provider minimum, traffic keeps it warm?"}
A1["Stable-first prompt layout"]
B{"Answer depends on user, tenant, time or changing data?"}
B1["No semantic cache, exact cache keyed on every input"]
B2["Semantic cache allowed for generic intents"]
C{"Is a person waiting for the answer?"}
C1["Stream, with separate TTFT and TPOT objectives"]
C2["Batch, no streaming"]
D{"Residency, pinning or sustained load a hard requirement?"}
D1["Evaluate self-hosting with operations cost"]
D2["API behind a Model gateway"]
R -->|"yes"| R1
R -->|"no"| R2
R1 --> A
R2 --> A
A -->|"yes"| A1
A -->|"no"| B
A1 --> B
B -->|"yes"| B1
B -->|"no"| B2
B1 --> C
B2 --> C
C -->|"yes"| C1
C -->|"no"| C2
C1 --> D
C2 --> D
D -->|"yes"| D1
D -->|"no"| D2
How to read this: work down the chain, one decision per row; the policies combine rather than compete.
Comparison of the main options
Failure scenarios to design for
Worked example
A support assistant sends 1,000,000 requests a month. Cost is in large-model input-token equivalents (LTE), so no price appears; use the LLM cost estimator for real prices.
Assumptions:
- Composite scenario; every figure is illustrative.
- Each request: 6,000-token stable prefix, 300 variable input tokens, 250 output tokens; an output token weighs 4 LTE.
- A small model costs 0.1 of the large model per token.
- Cache writes weigh 1.25 and reads 0.1 (Anthropic, as of 2026-10-22), with a 90% hit rate on every model.
- In the cascade 25% of requests escalate, paying for both calls.
The widget prices per million tokens, so it starts at the baseline as 0.0073 per request (7,300 x 10^-6). Set cachedShare to 0.952 (6,000 of 6,300 input tokens cached) for about 0.0019, the 1,900 all-hit best case; the table's 2,590 adds the 10% of misses that pay the write.
- The cascade stops paying at f = 0.9; the real saving depends on measured f and quality at the threshold.
- The perfect classifier is an upper bound; a real one adds a call and makes errors.
- The 90% hit rate is an assumption: the large model sees about 5.8 requests a minute (0.25 x 23.1), so its prefix can expire overnight.
A routing policy you can run
A rule layer plus a cascade, run with stub models on four paths: confident small, low-confidence escalation, small timeout and an always-large intent. Validate the scorer on a golden set first.
import logging
from dataclasses import dataclass
from typing import Callable
log = logging.getLogger("model-gateway")
@dataclass
class Answer:
text: str
confidence: float
Model = Callable[[str], Answer]
ALWAYS_LARGE = {"refund_dispute", "complaint", "legal_threat"}
THRESHOLD = 0.80
def route(intent: str, prompt: str, small: Model, large: Model) -> Answer:
if intent in ALWAYS_LARGE:
log.info("route=large reason=rule intent=%s", intent)
return large(prompt)
try:
first = small(prompt)
except TimeoutError:
log.warning("route=large reason=small_timeout")
return large(prompt)
if first.confidence >= THRESHOLD:
log.info("route=small confidence=%.2f", first.confidence)
return first
log.info("route=large reason=low_confidence confidence=%.2f", first.confidence)
return large(prompt)
ALWAYS_LARGE is the rule layer, the try block is the cascade, and every branch logs route and reason. Production would also pass the remaining deadline (Figure 4) and emit the usage event (Figure 2).
Common mistakes
- Routing on an unvalidated confidence number. Set the threshold on labelled data.
- A timestamp or user name at the top of the prompt. Move it below the stable part.
- Counting tokens as words times 1.3. Use the target model's counter.
- Semantic-caching user-specific answers. Generic intents only.
- Tracking only total latency. Track TTFT and TPOT separately.
- Streaming batch jobs. Stream only where a person is reading.
Try it
Time: 25 to 40 minutes.
- Compute KV bytes per token and per 32,000-token request for a Llama 3 size above.
- Paste a real 500-word prompt into the token counter, then count it with a provider's counting endpoint for two models if you can, and record the difference.
- Write a latency budget for one feature, with and without streaming and a cached prefix.
- List your prompt's parts in cache order and mark those that change per request.
Done when you have a one-page note with the KV bytes per token, the tokens-per-word difference between models, the latency split with its arithmetic, and a prompt order with no per-request value before the stable prefix.
Key takeaways
- A model gateway owns budgets, routing, caching, retries and usage records.
- Rules where the type is known; a cascade only with a validated scorer, and break-even is 1 minus the cost ratio.
- Tokens are model-specific: count with the target tokenizer.
- KV bytes per token = 2 x layers x KV heads x head dimension x bytes per value.
- Output tokens cost more latency than input tokens: set separate TTFT and TPOT objectives.
- Prefix caching needs an identical start: stable content first.
- Streaming moves failures into mid-response.
Self-check
1. A 6,000-token system prompt is followed by a line with the current time and then the user turn. The prefix cache never hits. Why, and what is the fix?
The provider matches from the first token, so a changing timestamp early on makes prompts differ from that point and only the text before it can match. Move per-request values after the stable content.
2. Compute the KV-cache bytes per token for a model with 40 layers, 8 KV heads, head dimension 128 and 16-bit values, and the size for a 16,000-token request.
2 x 40 x 8 x 128 x 2 = 163,840 bytes (160 KiB) per token; for 16,000 tokens, 2.62 x 10^9 bytes, about 2.44 GiB.
3. Why does an output token add more latency than an input token?
Input tokens are processed together in parallel prefill. Output tokens come one at a time, each step re-reading the weights, so decode is sequential and memory-bound.
4. A cascade sends every request to a small model costing 0.1 of the large one and escalates 30% of them. Does it save money, and at what escalation rate does it stop paying?
Cost relative to large-only = 0.1 + 0.3 = 0.4, a 60% saving before scorer overhead. It stops paying when 0.1 + f = 1, so f = 0.9.
5. A stream fails after 200 tokens have been shown. Why is retrying silently the wrong default?
The user has read the text, so a different answer on retry contradicts it, and a retried tool call could run twice. Keep the partial text, mark it incomplete and offer an explicit retry.
Further reading
- Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention (SOSP 2023), and Yu et al., Orca: A Distributed Serving System for Transformer-Based Generative Models (OSDI 2022).
- Leviathan et al., Fast Inference from Transformers via Speculative Decoding, and Chen et al., Accelerating Large Language Model Decoding with Speculative Sampling.
- Chen et al., FrugalGPT, and Ong et al., RouteLLM, for cascades and learned routers.
- Provider documentation: Anthropic prompt caching and OpenAI prompt caching.
- WHATWG, HTML Standard: Server-sent events.
Last verified: 2026-10-22
Next
Next is Data and retrieval architecture for AI systems, which covers how documents are ingested, chunked, indexed and retrieved safely.