Skip to content

    AI Architect

    Models, Routing and Inference for AI Architects

    How AI architects choose models, route requests, cache prompts and budget latency, with tokenization, KV cache, batching and quantization explained.

    By Published 28 min read

    Share

    This lesson is part of AI Architect (Intermediate): Design the System. Enroll for free, then sign in, to read it in full.

    What you'll learn: how to design the model layer: what a model gateway does, how to route, cache and budget latency, and eight "Under the hood" mechanisms (tokenization, KV cache, prefill and decode, batching, quantization, speculative decoding, prompt caching, streaming) behind each rule.

    At a glance

    Figure 1. The model layer: one request, six levers

    The model layer in one requestOrchestrator to 1 Count tokens (request); 1 Count tokens to Orchestrator (over budget); 1 Count tokens to 2 Route; 2 Route to 3 Caches; 3 Caches to 4 Provider (miss); 4 Provider to 5 Decode; 3 Caches to Orchestrator (hit); 5 Decode to Orchestrator (6 stream tokens); 5 Decode to Trace store (usage event)MODEL GATEWAYLLM PROVIDEROrchestratorOrchestrator1 Count tokens: check budget1 Count tokenscheck budget2 Route: rule, classifier, cascade2 Routerule, classifier,cascade3 Caches: exact, semantic3 Cachesexact, semantic5 Decode: token per step, KV cache5 Decodetoken per step,KV cache4 Provider: prefix cache, prefill4 Providerprefix cache,prefillTrace storeTrace storerequestover budgetmisshit6 stream tokensusage event

    How to read this: numbers 1 to 6 are the levers in the order a request meets them; the Under the hood sections open the machinery behind 1, 4, 5 and 6.

    • Tokens are the unit of cost, limit and speed, and counts are model-specific.
    • The gateway owns budgets, routing, caches and usage records; the Orchestrator owns prompts.
    • Route with rules where the request type is known; a cascade needs a validated scorer.
    • Output tokens cost more latency than input tokens.
    • A prefix cache hits only on an identical start: stable content first.
    • Streaming moves failures into mid-response.

    The real-world problem

    Composite scenario, not a real company. An assistant works in the demo. In month one the bill beats the forecast, because every message, even "where is my order", goes to the largest model. Users call it slow while the status page is green, and after a model upgrade the same prompts count as more tokens, so long conversations fail limit checks. None of this is a code bug.

    After this page you will be able to

    • Say which gateway jobs do not belong in the Orchestrator.
    • Choose between rule, classifier and cascade routing, and compute a cascade's break-even.
    • Compute KV-cache bytes per token and per request from a model's published dimensions.
    • Split a latency budget into TTFT and decode time, and lay out a prompt so a prefix cache can hit.

    Read the AI architect mindset and diagramming AI systems first. Background: LLM inference explained, prompt caching and LLM costs, LLM token budgeting and AI gateways in the enterprise. This page contains no prices: use the site's LLM cost estimator and token counter.

    Terms used on this page: model gateway, token, byte-pair encoding, context window, KV cache, prefill, time to first token, continuous batching, quantization, speculative decoding, prompt caching, semantic cache, model cascade and server-sent events.

    Core concepts

    What a model gateway does

    Figure 2. Inside the Model gateway

    Inside the Model gatewayOrchestrator to Budget check (request); Budget check to Orchestrator (reject or trim); Budget check to Router; Router to Cache lookup; Cache lookup to Adapter (miss); Cache lookup to Orchestrator (hit); Adapter to LLM provider (prompt text only); LLM provider to Adapter (streamed tokens); Adapter to Orchestrator (stream passed through); Adapter to Trace store (usage event)MODEL GATEWAYOrchestratorOrchestratorBudget check: tokens and deadlineBudget checktokens anddeadlineRouter: choose a modelRouterchoose a modelCache lookup: exact and semanticCache lookupexact andsemanticAdapter: timeout, retry, fallbackAdaptertimeout, retry,fallbackLLM providerLLM providerTrace storeTrace storerequestreject or trimmisshitprompt text onlystreamed tokensstream passed throughusage event

    How to read this: solid arrows are the request path, dashed arrows are the stream back and the asynchronous usage record; the cache sits after the router because a cache key must include the chosen model.

    The Model gateway does The Orchestrator does
    Checks token and deadline budget Builds prompts, decides the next step
    Chooses the model, checks the caches Decides which tool to call
    Calls the provider with timeouts, retries, fallback Owns business rules and the final answer
    Passes streams through, emits a usage record Sends a purpose, size limits and a deadline

    Routing policies: rules, classifier, cascade

    Policy Routes on Strength Weakness
    Rule Facts known before the call: endpoint, tier, language, length Free, deterministic, testable Brittle when difficulty is not in the metadata
    Classifier The request text, predicted Sees difficulty rules cannot Needs data, drifts silently
    Cascade The small model's scored answer Cheap when escalation is rare Escalations pay and wait twice; only as good as the scorer

    RouteLLM learns a strong-or-weak router from human preference data; its authors report cost savings of over 2 times with minimal impact on response quality on public benchmarks. FrugalGPT scores each answer from 0 to 1 and calls models in sequence until a score passes a threshold; on some datasets it matched the best single model at up to 98% lower cost (2023 APIs and datasets). These are the authors' settings, not a promise for your traffic.

    Figure 3. Which routing policy fits?

    flowchart TD accTitle: Choosing a routing policy accDescr: A decision tree. If the request type is known before the call, use rules. If not, and labelled data and stable traffic exist, use a classifier. If not, and answers can be scored reliably with tolerable extra latency, use a cascade. Otherwise use one model with caching. Q1{"Is the request type known before the call?"} Q2{"Do you have labelled quality data and stable traffic?"} Q3{"Can you score an answer reliably and accept extra latency on escalations?"} A1["Rules on endpoint, tier or intent"] A2["Classifier router, re-checked on a golden set"] A3["Cascade with a validated scorer and threshold"] A4["One model, plus caching"] Q1 -->|"yes"| A1 Q1 -->|"no"| Q2 Q2 -->|"yes"| A2 Q2 -->|"no"| Q3 Q3 -->|"yes"| A3 Q3 -->|"no"| A4

    How to read this: follow yes or no from the top and stop at the first rectangle; real systems often put a rule layer in front of a cascade.

    Figure 4. A cascade with its failure paths

    sequenceDiagram accTitle: Cascade routing sequence accDescr: The Orchestrator sends a request to the Model gateway. A rule check passes it to the small model. If the small model answers confidently its answer is returned. If it answers with low confidence or times out, the gateway escalates to the large model within the remaining deadline. Every outcome emits a usage event to the Trace store. autonumber participant O as Orchestrator participant M as Model gateway participant S as LLM provider small model participant L as LLM provider large model participant T as Trace store O->>M: request, intent order_status, deadline 8 s Note over M: Rule check - intent is not on the always-large list M->>S: prompt with 3 s timeout alt Small model replies and is confident S-->>M: answer Note over M: Score at or above threshold, accept M-->>O: answer, route small else Small model replies with low confidence S-->>M: answer Note over M: Score below threshold, escalate with the remaining budget M->>L: prompt with 5 s timeout L-->>M: answer M-->>O: answer, route large else Small model times out Note over M: Decision - escalate, small attempt used 3 s of 8 s M->>L: prompt with 5 s timeout L-->>M: answer M-->>O: answer, route large end M-)T: usage event with route, tokens and latency

    How to read this: the alt block lists three outcomes of the small model, notes mark the gateway's decisions, and the last arrow is asynchronous.

    Check yourself: in Figure 4 the small model times out after 3 s of an 8 s deadline. What is the longest timeout the large call can get?

    5 s, the remaining deadline. The timeout comes from the budget, not from a constant. The usage event records route and reason so the policy can be audited.

    With the large model at cost 1 and the small at 0.1, a cascade costs 0.1 + f for escalation rate f. Start at 30%, then find where the saving vanishes.

    Cascade break-even: small model costs 0.1 of the large one (interactive when JavaScript is on)
    Cascade cost per request0.4
    Always-large cost per request1
    Break-even escalation rate90.0%

    At 30% it costs 0.4 of large-only. It stops paying at 0.9, and helps only if accepted answers match the large model's quality on your golden set.

    Caching layers

    Cache Reuses Output changes? What goes wrong Scope it
    Exact A stored answer for an identical request No Leaks if the key omits tenant, permissions or policy version Key on everything the answer depends on
    Prefix (provider prompt caching) The provider's processed start of a prompt No: OpenAI's documentation says caching does not change how output tokens are generated Layout changes silently kill hits Stable-first layout (below)
    Semantic A stored answer for a close query by embedding distance (FrugalGPT lists a completion cache among its levers) Yes "Cancel my order" and "cancel my subscription" are close in meaning, far apart in consequence; cross-tenant hits; stale answers Tenant and version in the key, generic intents, high threshold, sampled review

    Figure 5. Cache lookup order in the Model gateway

    flowchart TD accTitle: Cache lookup order accDescr: A request first checks the exact cache. On a miss it checks the semantic cache only if the intent allows it and a similar stored query exists in the same tenant and policy version. On a second miss it calls the LLM provider, where the provider prefix cache applies, and stores the answer if it is cacheable. Req["Request from the Orchestrator"] Ex{"Exact cache hit? Key has model, prompt version, tenant"} Sem{"Intent allows semantic cache and a close query exists in this tenant and policy version?"} R1["Return stored answer"] R2["Return stored answer and log the hit for review"] Prov["Call LLM provider, prefix cache applies there"] Store["Store under the exact key if cacheable"] R3["Return the new answer"] Req --> Ex Ex -->|"yes"| R1 Ex -->|"no"| Sem Sem -->|"yes"| R2 Sem -->|"no"| Prov Prov --> Store Store --> R3

    How to read this: diamonds are lookups, rectangles are outcomes, and the safest cache is checked first.

    Which caching choice fits? (interactive when JavaScript is on)

    Which must not be served from a semantic cache?

    • Return policy, the same for every user of a tenant
    • Where is my order, which depends on the user's data
    • How do I reset my password, a generic how-to
    Answer

    Where is my order, which depends on the user's data. An answer that depends on the user, tenant, time or changing data can be wrong for the next person.

    Every prompt starts with the current time, then 6,000 stable tokens, and the prefix cache almost never hits. The fix?

    • Move the time after the stable content
    • Add a semantic cache in front
    • Switch to a larger model
    Answer

    Move the time after the stable content. A prefix cache matches from the first token, so a changing value near the top makes every prompt differ from there on.

    Latency anatomy: time to first token and total time

    Time to first token (TTFT) is the wait for the first output token; the DistServe paper defines it as the duration of prefill, and a client also sees queueing and network time. Time per output token (TPOT) is the average per token after the first. Total = TTFT + TPOT x (tokens after the first).

    Illustrative Value
    TTFT, TPOT, output 0.6 s, 25 ms, 400 tokens
    Total 0.6 + 399 x 0.025 = 10.575 s
    First text seen, unstreamed or streamed 10.6 s or 0.6 s

    A chatbot cares about TTFT, and TPOT only until it beats reading speed; summarisation cares about TPOT. The total misses a 10 s deadline: shorten decode to 7.5 s (about 300 tokens) and it fits.

    Latency budget for one streamed answer (illustrative 10 s deadline) (interactive when JavaScript is on)
    Time to first token0.6 s
    Decode, 399 tokens x 25 ms9.97 s
    Total10.57 s of 10 s
    Over budget by0.57 s
    Check yourself: halve the answer to 200 tokens. What is the new total, and which number moved?

    0.6 + 199 x 0.025 = 5.575 s. TTFT is unchanged; only the decode stage shrank.

    Structured output and context-window budgeting

    Topic What the provider documents (Anthropic, as of 2026-10-22) Rule
    Structured output Constrained decoding; the guarantee fails on a refusal or a token-limit cut; first use of a schema adds compile latency, and grammars are cached 24 hours from last use (docs) Check the stop reason before parsing; valid JSON is not correct JSON
    The window Counts the system prompt, messages including tool results, images, documents, tool definitions and the output including thinking; accuracy degrades as tokens grow More context is not better; reserve output first
    Overflow Input alone above the window returns a 400 error; on newer models input plus max_tokens above it is accepted and generation stops with a dedicated stop reason; older models return an error Count before sending; define your own "too long" error
    Part of the request Illustrative tokens Policy when it grows
    Output reservation (max_tokens) 1,000 Fixed, from the longest legitimate answer
    Tool definitions 1,500 Load only the route's tools
    System prompt, reference text 4,000 Keep stable: the cacheable prefix
    Retrieved passages 3,000 Cap the count
    Conversation history up to 4,000 Summarise or trim oldest
    Current user turn 500 Reject or truncate

    Self-hosting versus API

    API behind a Model gateway Self-hosted
    Runs batching, KV memory, quantization The provider You
    Cost Per token GPU hours, so utilisation
    Model and tokenizer changes You accept them You pin versions
    Data Crosses your boundary under contract Stays with you
    You also own Little beyond the gateway Capacity, on-call, an evaluation per model

    Cost per token = GPU cost per hour / (tokens per hour at full load x utilisation). Practitioners disagree on the crossover volume, so measure. Default to an API behind a gateway.

    Case files

    Three composite case files apply this page. All are illustrative scenarios, not real companies.

    • 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.

    1. Sennrich, Haddow and Birch adapted byte pair encoding (BPE) to words: start from characters plus an end-of-word symbol.
    2. 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".
    3. 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.

    Tokenizer (Llama 3 paper, English) Characters per token Tokens for 4,000 characters
    Llama 3 (128K vocabulary) 3.94 4,000 / 3.94 = 1,015
    Llama 2 3.17 4,000 / 3.17 = 1,262, which is 24% more

    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

    What changes What you do
    Counts are model-specific Count with the target model's tokenizer or counting endpoint, never words times a ratio
    The site's token counter uses 4 characters per token Treat it as a planning estimate
    An upgrade changes counts with unchanged text Pin versions, recount, enforce the limit at the gateway

    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.

    1. 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.
    2. Bytes per token = 2 (key and value) x layers x KV heads x head dimension x bytes per value.
    3. 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.
    4. Grouped-query attention shares keys and values among query heads; the Llama 3 paper states its models use GQA with 8 KV heads.
    Model Layers Model dim Heads KV heads KV bytes per token 8,192 tokens 128,000 tokens
    Llama 3 8B 32 4,096 32 8 131,072 (128 KiB) 1.0 GiB 15.6 GiB
    Llama 3 70B 80 8,192 64 8 327,680 (320 KiB) 2.5 GiB 39.1 GiB

    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.

    KV cache of Llama 3 8B at 8,192 tokens (interactive when JavaScript is on)
    Bytes per token131,072
    Total for 8,192 tokens x 1 sequence(s)1.00 GiB
    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

    What changes What you do
    Context length becomes memory Capacity = (GPU memory minus weights) / (KV bytes per token x tokens per request)
    In the vLLM paper's setup (13B on a 40 GB A100) about 65% of memory is weights and close to 30% is cache: about 12 GB, or 12 x 10^9 / 819,200 = 14,648 tokens, roughly seven full 2,048-token sequences A model's maximum window is not the context you can afford on every request
    Fewer KV heads means cheaper long context Make it a selection criterion beside price and quality

    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.

    1. 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.
    2. 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.
    3. DistServe defines TTFT as the duration of prefill and TPOT as the average time per token after the first.
    Bound (stated assumptions) Calculation Result
    Decode floor 8B parameters x 2 bytes = 16 GB; NVIDIA lists 2,039 GB/s for the A100 80GB SXM; 16 x 10^9 / 2,039 x 10^9 7.85 ms per token; 400 tokens at least 3.1 s (ignores KV cache and overheads)
    TTFT, no cache 9,000 tokens / an assumed 10,000 per second 0.9 s; total 0.9 + 399 x 0.025 = 10.875 s
    TTFT, 6,000 tokens cached 3,000 / 10,000 0.3 s; total 10.275 s
    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

    What changes What you do
    Output tokens cost more latency than input tokens Shorten answers first (tighter format, schema without prose, sane max_tokens); thinking tokens are decode time too
    Shortening or caching the prompt moves TTFT, which interactive users feel first Cache or trim the prompt on interactive routes
    Under load, scheduling delays raise TTFT (Sarathi-Serve) and a prefill added to a decode batch slows both (DistServe) Set separate TTFT and TPOT objectives; alert on 95th percentiles

    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.

    1. 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.
    2. 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.
    3. 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.
    4. 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.
    Worked numbers Calculation Result
    Fixed batch, output lengths 10, 50, 200, 30 4 x 200 = 800 steps occupied, 290 needed 36.25% utilisation
    OPT-13B, 100 tokens, 16-token blocks ceil(100 / 16) = 7 blocks = 112 slots, 12 unused x 819,200 bytes 9.8 MB wasted
    Same request, 2,048 tokens reserved 1.68 GB held for 100 tokens in use 95.1% idle

    What this means for architects

    What changes What you do
    Under load, latency is queueing plus slower iterations: a long TTFT at peak Track TTFT percentiles by hour
    Self-hosted capacity is the KV block pool: concurrent requests x average tokens x bytes per token Size for peak; a long max_tokens raises preemption risk
    Anthropic's Message Batches API is asynchronous, most batches finish within an hour, they expire after 24 hours, and the page states a 50% cost reduction (as of 2026-10-22, batch processing) Trade delay for cost where no one waits, as the document-classification case does

    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:

    Bits Weight memory Decode floor per token
    16 16 GB 7.85 ms
    8 8 GB 3.92 ms
    4 4 GB 1.96 ms
    • 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

    What changes What you do
    A quantized model is a different model, and papers measure perplexity and benchmarks, not your task Run it on your golden set first
    Smaller weights leave more memory for the KV cache Count it as a concurrency lever too
    API providers generally do not document quantization Let your regression gate catch silent changes

    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.

    1. 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.
    2. 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.
    alpha 0.8, gamma 4 Calculation Result
    Tokens per pass (1 - 0.8^5) / 0.2 3.36
    Improvement at c = 0.05 3.36 / 1.2 2.80 times
    Improvement at c = 0.2 3.36 / 1.8 1.87 times

    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

    What changes What you do
    Mostly a server-side optimisation; an API provider may use it invisibly Do not plan around it for API models
    It needs spare compute (the paper says it does not help without it) Expect the gain to shrink as batches grow
    It needs a draft model that agrees often and shares the tokenizer Measure alpha on your traffic; the gain collapses as it falls

    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.

    OpenAI Anthropic (as of 2026-10-22)
    Cached Key-value tensors, not tokens Prompt in order tools, system, messages, up to the cache_control block (up to 4 breakpoints)
    A hit needs The entire rendered prefix to match 100 percent identical segments; a change invalidates that level and all later ones
    Lifetime Machine-local; above 15 requests per minute can lead to overflow routing 5 minutes, refreshed on use; 1-hour option at extra cost
    Evidence n/a Usage: cache_read_input_tokens + cache_creation_input_tokens + input_tokens
    Minimum 1,024 tokens for newest models 512 to 4,096 by model; shorter prompts run uncached, no error

    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).

    Prompt-cache break-even (Anthropic 5-minute multipliers, as of 2026-10-22) (interactive when JavaScript is on)
    Break-evenfrom request 2
    After 1 request(s): with cache / without1.25 / 1
    After 2 request(s): with cache / without1.35 / 2
    After 5 request(s): with cache / without1.65 / 5
    After 10 request(s): with cache / without2.15 / 10
    A 6,000-token prefix Calculation Result
    10 requests, uncached 10 x 6,000 60,000
    10 requests, cached 1.25 x 6,000 + 9 x 0.1 x 6,000 = 7,500 + 5,400 12,900, which is 78.5% less
    Break-even cached cost for n requests = 1.25 + 0.1 (n - 1) prefix-lengths Request 2: 1.35 against 2
    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

    What changes What you do
    Stability is set by layout and releases Order stable to least: tools, system prompt, reference text, retrieved passages, user turn
    Timestamps, ids and names at the top make every prefix unique Keep them out; serialise tool schemas in a fixed order
    Every prompt release rewrites the cache once Ship prompt changes in batches
    1,000,000 requests a month is about 23 a minute: warm by day, possibly expired at night Compare rate with lifetime; alert on cache-read share
    Per-tenant data early gives each tenant its own prefix Put it after the shared part; OpenAI says cached tensors may sit in GPU-local storage, so read the data terms

    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.

    SSE rule Detail
    Format text/event-stream, always UTF-8; events separated by blank lines; fields data, event, id, retry
    Keep-alive A colon-prefixed comment line; about every 15 seconds is suggested so proxies keep idle connections
    Reconnect EventSource reconnects with Last-Event-ID; a non-200 status or wrong content type fails with no reconnect; 204 stops it

    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

    What changes What you do
    After headers the status is 200, so failures sit mid-response Send errors in-band; show partial text as incomplete
    Shown text cannot be unsaid, and a retried tool call may run twice No silent retry after the first token
    Output checks on a full answer now meet partial text Decide per intent which replies may stream
    Every hop must pass the stream unbuffered; JSON cannot be parsed until complete Set idle timeouts longer than token gaps
    Whether closing the connection stops billing is provider-specific Test it

    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.

    If Then Because Revisit when
    The request type is known before the call Route with rules first Free, deterministic, testable Difficulty is not in the metadata
    Cheap answers can be scored, a slower tail is acceptable Cascade, else classifier A cascade pays twice per escalation Escalation nears break-even
    A stable prefix above the minimum stays warm Lay out for prefix caching first Cuts cost and TTFT, same answers Releases outpace the cache lifetime
    An answer depends on user, tenant, time or changing data No semantic cache; exact caches keyed on all inputs A wrong hit is an incident Versioning can expire entries exactly
    A user is waiting on a long answer Stream; if nobody waits, batch Streaming adds failure modes Output checks can run on partial text
    Residency, pinning or sustained load is a hard requirement Evaluate self-hosting; else an API behind a gateway The gateway keeps the exit open Volume or regulation changes

    Comparison of the main options

    Option Effect on cost and latency Main risk Fits when
    One large model Highest cost, slow tail Cost grows with traffic Prototype
    Rule routing Lower cost, none added Brittle Type known upfront
    Classifier router Lower cost, one extra step Silent drift Stable, labelled traffic
    Cascade Lower if escalation is rare; escalations wait twice False accepts Reliable scorer
    Exact cache Removes repeats, near-zero latency Key omits an input Generic answers
    Prefix cache Lower input cost and TTFT Layout changes kill hits Long stable prompts
    Semantic cache Removes near-repeats Wrong, stale or cross-tenant hit FAQ-like intents
    Self-hosted Depends on utilisation Operations burden Residency, steady volume

    Failure scenarios to design for

    Failure What the system does Why
    The router sends a hard request to the small model unnoticed Logs route, reason and confidence; reviews a weekly sample per intent; escalates the next turn on tool errors or thumbs-down Silent misrouting needs a record
    The cascade scorer accepts a wrong answer Threshold set on labelled data; costly intents always large; alerts on a rising low-confidence share A rising share signals drift
    A cache returns another tenant's or an old-policy answer Tenant and version in the key; expiry on a version change; hits logged A wrong hit is an incident
    The prefix cache goes cold Alerts on cache-read share; one warm-up request per release No error is raised
    An upgrade changes token counts Pinned versions; target tokenizer; trim by policy or reject with a defined error Counts are model-specific
    A stream fails after the first token Keeps partial text marked incomplete; no tool call from it; explicit retry Shown text cannot be unsaid

    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.
    Design Calculation LTE per request Change
    Baseline: all large, no cache 6,000 + 300 + 250 x 4 7,300 none
    Add prefix caching input 0.9 x (6,000 x 0.1 + 300) + 0.1 x (6,000 x 1.25 + 300) = 810 + 780 = 1,590; plus output 1,000 2,590 -64.5%
    Add a cascade (25% escalate) 0.1 x 2,590 + 0.25 x 2,590 = 259 + 647.5 906.5 -87.6%
    A perfect classifier router 0.75 x 0.1 x 2,590 + 0.25 x 2,590 = 194.25 + 647.5 841.75 -88.5%

    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.

    Cost per request in LTE (illustrative, no real prices) (interactive when JavaScript is on)
    Cost per request (units)0.007300
    Cost per 1,000 requests (units)7.3
    • 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.

    1. Compute KV bytes per token and per 32,000-token request for a Llama 3 size above.
    2. 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.
    3. Write a latency budget for one feature, with and without streaming and a cached prefix.
    4. 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

    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.

    Enroll to keep reading

    Lesson 4 of 8 · AI Architect (Intermediate): Design the System

    How AI architects choose models, route requests, cache prompts and budget latency, with tokenization, KV cache, batching and quantization explained.

    In the rest of this lesson

    • Under the hood: Tokenization and the context window
    • Under the hood: Attention and the KV cache
    • Under the hood: Prefill and decode
    • Under the hood: Continuous batching and paged KV memory
    • Under the hood: Quantization
    • Under the hood: Speculative decoding

    Enrolling is free. It unlocks every lesson in AI Architect (Intermediate): Design the System, tracks your progress across devices and keeps your quiz scores. The newsletter is optional.

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments