The Inference Stack Top to Bottom: From API Call to GPU Kernel
Every major inference provider handles request routing, batching, and GPU scheduling differently. Understanding these mechanics turns vague latency…
Every major inference provider handles request routing, batching, and GPU scheduling differently. Understanding these mechanics turns vague latency complaints into actionable architecture decisions.
The Inference Stack Top to Bottom: From API Call to GPU Kernel
Table of Contents
- The Request Lifecycle
- API Gateway and Authentication
- Request Routing and Model Selection
- Continuous Batching
- The KV Cache
- Quantization at Inference Time
- Speculative Decoding
- Prefill vs Decode: The Two Phases
- Attention Kernels
- Tensor Parallelism and Pipeline Parallelism
- Adaptive Thinking and Effort Steering
- Prompt Caching
- Streaming and Token Delivery
- Putting It All Together: A Real Request
- Summary
- Further Reading
An API call to GPT-6.2 Astra or Claude Opus 5.5 triggers a cascade of systems — load balancers, routers, schedulers, memory managers, and GPU kernels — each with distinct performance characteristics and failure modes. This post traces a single inference request from the moment it leaves a client application to the moment output tokens stream back, covering every layer of the stack as it operates in production in late 2026.
The Request Lifecycle
A single completion request passes through roughly eight stages before a token reaches the client.
End-to-end lifecycle of a single inference request, from API gateway to streamed token delivery.
Each stage introduces latency. The total time-to-first-token (TTFT) for a 4,000-token prompt on a frontier model typically ranges from 200ms to 2 seconds depending on provider load, model size, prompt caching, and geographic distance. Time-per-output-token (TPOT) then ranges from 10ms to 80ms depending on model architecture and batch pressure.
API Gateway and Authentication
The gateway layer handles TLS termination, API key validation, organization-level rate limiting, and request schema validation. For providers like OpenAI and Anthropic, this layer also enforces token-based rate limits (tracked per minute and per day), which behave differently from traditional request-count limits because a single request consuming 100K input tokens eats far more quota than one consuming 500 tokens.
The gateway inspects the model parameter to route downstream. It also strips or validates headers like anthropic-beta feature flags, OpenAI’s stream_options, and Google’s generationConfig. Malformed requests get rejected here — the most common failure mode is exceeding a model’s context window (e.g., sending 1.1M tokens to a model with a 1M limit).
Provider gateways generally add 5–30ms of overhead. Geographic routing matters: a request from Tokyo hitting a US-East gateway adds ~150ms of round-trip latency before anything else happens.
Request Routing and Model Selection
Behind the gateway sits a routing layer that maps the requested model identifier to a specific deployment. This is more complex than it appears.
Model routing considers regional GPU pool capacity and can overflow to secondary regions or queue.
A single model name like claude-opus-5-5 maps to potentially hundreds of GPU clusters across multiple regions. The router considers:
- Current load per cluster (measured in active batch slots, not just request count)
- Region affinity (keeping requests close to the client when possible)
- Priority tier (paid tiers get routed preferentially; free tiers get queued during peak)
- Prompt cache locality (if the system prompt is already cached on a specific cluster, the request goes there to get cache hits)
For providers offering multiple model tiers — OpenAI’s Astra/Sol/Luna hierarchy, Anthropic’s Fable/Opus/Sonnet/Haiku lineup — the router also validates that the requested model is available in the caller’s subscription tier.
OpenAI’s GPT-6 Astra “Fast mode” (up to 2x speed at 2x price) is likely implemented at this layer: routing to a pool with smaller batch sizes or dedicated capacity, trading utilization efficiency for lower per-request latency.
Continuous Batching
This is probably the single most important optimization in the production inference stack. Without batching, a 70B-parameter model running on a single GPU would process one request at a time, leaving compute heavily underutilized during the memory-bound decode phase.
Static batching (the naive approach) groups requests together and processes them as a unit. The entire batch waits until the longest sequence finishes. A batch of 8 requests where 7 finish in 50 tokens and 1 runs to 2,000 tokens wastes enormous compute.
Continuous batching (also called “inflight batching” or “iteration-level scheduling”) solves this by allowing new requests to enter the batch and completed requests to exit at every decode step.
Continuous batching admits and evicts requests at each decode iteration, maximizing GPU utilization.
In practice, vLLM (the dominant open-source serving engine) implements this via its Scheduler class, which runs before every forward pass to decide which sequences get a slot. The scheduler considers:
- Available KV cache memory (the primary constraint)
- Pending prefill requests (which are compute-bound and slow down the batch)
- Running decode requests (which are memory-bound and cheap to include)
- Preemption policies (which running request gets swapped out if memory is exhausted)
The batch size in production varies widely. A system serving DeepSeek-V4.1-Flash (552B MoE with 8B active parameters per token for input) can pack far more concurrent sequences than a dense model of the same total size, because only the active expert parameters need compute at each step. Reports from DeepSeek’s own infrastructure suggest batch sizes in the hundreds during peak load.
The KV Cache
The key-value cache is the data structure that makes autoregressive generation tractable. During the prefill phase, the model processes the entire prompt and stores the intermediate key and value tensors for every attention head at every layer. During decode, each new token only needs to attend to these cached values rather than recomputing attention over the full sequence.
For a model with 128 layers, 128 attention heads, and a head dimension of 128 — roughly the architecture of a large frontier model — the KV cache for a single 100K-token sequence at FP16 precision consumes:
2 (K+V) × 128 layers × 128 heads × 128 dim × 100,000 tokens × 2 bytes
≈ 838 GB
This is obviously impractical on a single GPU. Several techniques compress and manage this:
Grouped-Query Attention (GQA): Most models since 2024 use GQA, where multiple query heads share a smaller number of key-value heads. A model using 8 KV heads instead of 128 reduces cache size by 16x.
KV cache quantization: Storing cached values in INT8 or even INT4 instead of FP16 halves or quarters memory at a small quality cost. vLLM supports FP8 KV cache quantization with minimal perplexity degradation.
PagedAttention: Invented by the vLLM team, this manages KV cache memory like an operating system manages virtual memory — in fixed-size pages rather than contiguous blocks. This eliminates the internal fragmentation that wastes 60–80% of KV cache memory in naive implementations.
PagedAttention maps variable-length KV caches to fixed physical memory pages, enabling efficient GPU memory management.
PagedAttention enables a critical capability: KV cache sharing across requests. When multiple requests share the same system prompt (common in production — a customer support bot serves thousands of users with an identical system prompt), the KV cache for that prefix can be computed once and shared. This is the mechanism behind prompt caching features offered by OpenAI, Anthropic, and Google.
Quantization at Inference Time
Quantization reduces model weights from FP16 (16 bits per parameter) to lower bit widths. For inference, the goal is to reduce memory bandwidth requirements — since decode is memory-bound, moving fewer bytes per parameter directly translates to higher throughput.
| Precision | Bits/param | Memory for 70B model | Typical quality loss |
|---|---|---|---|
| FP16/BF16 | 16 | 140 GB | Baseline |
| FP8 (E4M3) | 8 | 70 GB | Negligible on most benchmarks |
| INT8 (W8A8) | 8 | 70 GB | <1% on most tasks |
| INT4 (W4A16) | 4 | 35 GB | 1–3% on reasoning tasks |
| GPTQ/AWQ 4-bit | 4 | 35 GB | Varies by calibration |
| GGUF Q4_K_M | ~4.5 | ~39 GB | 1–2% typical |
FP8 inference has become the production default for most providers in 2026. NVIDIA’s H100 and B200 GPUs have native FP8 tensor core support, making FP8 matrix multiplications as fast as INT8 while preserving more dynamic range. The B200’s transformer engine can dynamically switch between FP8 and FP4 precision per layer.
For self-hosted inference, llama.cpp’s GGUF format with Q4_K_M or Q5_K_M quantization remains the standard for running models on consumer hardware. The tradeoff is straightforward: Q4_K_M on a model like Qwen3.8-27B fits in ~16GB of RAM and runs at acceptable speeds on a Mac with 32GB unified memory, while FP16 would require 54GB.
Mixture-of-experts models like DeepSeek-V4.1-Flash (552B total, 8–16B active) complicate the picture. The total model weights are large, but only the active expert parameters flow through compute on each token. Memory still needs to hold all expert weights for routing, but the memory bandwidth consumed per token is proportional to the active parameter count.
Speculative Decoding
Autoregressive decoding is inherently sequential — each token depends on the previous one. Speculative decoding breaks this bottleneck by using a small, fast “draft” model to guess multiple future tokens, then verifying those guesses in a single forward pass of the large “target” model.
Speculative decoding uses a draft model’s guesses verified by a single target model forward pass, producing multiple tokens per step.
The key insight: verifying K draft tokens takes roughly the same time as generating a single token from the target model, because the target model processes all K positions in parallel (like a prefill operation). If the draft model’s acceptance rate is high — say 70–85% of tokens are accepted — throughput improves proportionally.
In practice, speculative decoding works best when:
- The draft model is 10–20x smaller than the target (e.g., a 1B draft for a 70B target)
- The task has predictable token sequences (code completion, structured output)
- The draft model shares the same vocabulary as the target
Medusa and EAGLE are variants that replace the separate draft model with additional prediction heads attached to the target model itself, eliminating the need to load a second model. EAGLE-2 achieves 3–4x speedup on code generation tasks where token predictability is high.
Google’s Gemini models likely use a form of speculative decoding internally — the ~4x faster output speed reported for Gemini 3.5 Flash compared to other frontier models is consistent with aggressive speculation combined with efficient attention kernels.
For self-hosted inference, llama.cpp supports speculative decoding via its --draft parameter, and vLLM added speculative decoding support with configurable draft models. The setup overhead is nontrivial — the draft model needs to share the tokenizer and be loaded alongside the target — but the throughput gains on long generations are substantial.
Prefill vs Decode: The Two Phases
Every inference request has two distinct computational phases with fundamentally different performance characteristics.
Prefill processes the entire input prompt in parallel. All input tokens are known upfront, so the model runs a single forward pass across the full sequence length. This is compute-bound — the GPU’s FLOPs are the bottleneck, not memory bandwidth. A 100K-token prompt on a large model might take 2–10 seconds to prefill depending on the hardware.
Decode generates output tokens one at a time (or a few at a time with speculative decoding). Each step produces one token and appends it to the KV cache. This is memory-bound — the GPU spends most of its time reading model weights and KV cache from HBM rather than doing arithmetic.
Prefill is compute-bound and determines time-to-first-token; decode is memory-bound and determines throughput.
This split explains why TTFT and TPOT often don’t correlate. A system optimized for high throughput (large batch sizes during decode) will have slower TTFT because new prefill requests compete for compute with the existing batch. Conversely, a system that prioritizes low TTFT (small batches, immediate prefill admission) underutilizes GPUs during decode.
Production serving systems handle this tension through disaggregated prefill and decode — running the two phases on separate GPU pools. The prefill pool is configured for compute throughput (fewer, larger batches), while the decode pool is configured for memory bandwidth (many concurrent sequences with small per-step compute). The KV cache is transferred between pools after prefill completes. This architecture is becoming standard at scale; DeepSeek’s production infrastructure uses a variant of it.
The OpenAI pricing model for GPT-6 Astra (prompts over 272K input tokens bill at 2x input/cache and 1.5x output) reflects the real cost of prefilling very long sequences — longer prefills consume disproportionately more compute because attention computation scales quadratically with sequence length unless efficient attention mechanisms are used.
Attention Kernels
Attention is the computational core of transformer inference. The standard self-attention operation for a sequence of length N has O(N²) time and memory complexity, which becomes the dominant cost for long contexts.
FlashAttention (and its successors FlashAttention-2, FlashAttention-3) rewrites the attention computation to avoid materializing the full N×N attention matrix in GPU HBM. Instead, it tiles the computation into blocks that fit in SRAM (the GPU’s fast on-chip memory), computing attention and the softmax normalization in a fused kernel. This reduces HBM reads/writes from O(N²) to O(N), yielding 2–4x speedups on long sequences with no approximation — the output is mathematically identical.
FlashAttention-3, optimized for Hopper architecture (H100/H200), exploits FP8 tensor cores and asynchronous memory operations. It achieves close to the theoretical peak throughput of H100s on attention operations.
Ring Attention extends FlashAttention across multiple GPUs for very long contexts. Each GPU holds a chunk of the KV cache and passes blocks to neighbors in a ring topology, enabling context windows that exceed a single GPU’s memory. This is probably how 1M-context models like Claude Opus 5.5, Gemini 4 Argon, and GPT-6 Astra handle their full context windows — the KV cache for 1M tokens at FP8 on a GQA model might require 50–200GB depending on architecture, which exceeds single-GPU HBM.
Multi-Head Latent Attention (MLA): DeepSeek introduced MLA in DeepSeek-V2 and continues to use it in V4.1-Flash. Rather than caching separate K and V tensors per head, MLA compresses them into a low-rank latent representation, reducing KV cache size by 5–10x compared to standard GQA. This allows DeepSeek to serve very long contexts (1M tokens) with dramatically less memory per sequence, enabling larger batch sizes and lower per-token costs.
| Attention Mechanism | KV Cache Size (relative) | Compute Overhead | Used By |
|---|---|---|---|
| Multi-Head Attention | 1.0x (baseline) | Baseline | Older models |
| Grouped-Query Attention (GQA) | 0.06–0.25x | Negligible | Most 2024–2026 models |
| Multi-Query Attention (MQA) | 0.008x | Slight quality loss | PaLM, Falcon |
| Multi-Head Latent Attention | 0.1–0.2x | Small upsample cost | DeepSeek V2–V4 |
Tensor Parallelism and Pipeline Parallelism
Large models don’t fit on a single GPU. An FP16 model with 405B parameters needs ~810GB of memory just for weights, plus KV cache, activations, and framework overhead. Even at FP8, that’s ~405GB — requiring at least 5 H100s (80GB each) or 3 H200s (141GB each).
Tensor parallelism (TP) splits individual weight matrices across GPUs. Each GPU holds a shard of every layer and executes its portion of each matrix multiplication. The partial results are combined via all-reduce communication before the next operation. TP requires high-bandwidth interconnect (NVLink at 900 GB/s on H100 SXM, or the newer NVLink Switch on B200 systems) because every layer triggers a cross-GPU synchronization.
Pipeline parallelism (PP) splits layers across GPUs. GPU 0 handles layers 0–31, GPU 1 handles layers 32–63, etc. This requires less cross-GPU communication (data only flows between stages at layer boundaries) but introduces pipeline bubbles — GPUs sit idle while waiting for activations from the previous stage.
Parallelism strategies combine tensor parallelism within nodes and pipeline parallelism across nodes; MoE models add expert parallelism.
Expert parallelism (EP) is specific to MoE models. Different experts reside on different GPUs, and tokens are routed to the appropriate GPU based on the router’s decision. DeepSeek-V4.1-Flash, with 552B total parameters but only 8–16B active, distributes experts across many GPUs but only activates a small fraction per token. The challenge is load balancing — if certain experts are “hot” (frequently selected), those GPUs become bottlenecks.
Production deployments of frontier models typically use a combination: TP within a single node (8 GPUs connected by NVLink), PP across nodes (connected by InfiniBand or RoCE), and EP for MoE models. A deployment of a 1T+ MoE model might span 32–64 GPUs across 4–8 nodes.
Adaptive Thinking and Effort Steering
A development specific to current-generation models: thinking budget is now a controllable parameter that affects inference cost and latency.
Anthropic’s current models (Opus 5.5, Sonnet 5.5, Haiku 5.5, Fable 5.2) use adaptive thinking steered by an effort parameter with levels like low, medium, and high. The older budget_tokens approach (explicit token count for thinking) is deprecated. At the infrastructure level, this likely translates to:
- The model generates internal reasoning tokens that consume compute but aren’t returned to the user (or are returned in a
thinkingblock) - Higher effort levels allow more internal tokens before the model commits to an output
- The scheduler accounts for thinking tokens in batch management — a high-effort request consumes more KV cache and more decode steps
Gemini 3.8 Flash similarly exposes tunable thinking levels (low/medium/high). OpenAI’s GPT-6 Astra doesn’t expose thinking levels in the same way but likely performs variable amounts of internal computation depending on query complexity.
From an infrastructure perspective, thinking tokens are expensive: they consume the same KV cache memory and decode compute as output tokens, but the user doesn’t see them (unless the provider returns them). A request that generates 500 thinking tokens and 200 output tokens has the same GPU cost as generating 700 output tokens. Some providers charge for thinking tokens; others absorb the cost.
Thinking tokens consume the same GPU resources as output tokens; effort settings control how many are generated.
Anthropic’s guidance that prompting habits like “think hard” are now counterproductive on Opus 5.5 (which defaults to medium effort) suggests the model already allocates thinking budget based on perceived query difficulty. Explicitly asking it to think harder on a simple query wastes tokens on redundant reasoning.
Prompt Caching
Prompt caching stores the KV cache state for previously-seen prompt prefixes so subsequent requests with the same prefix skip the prefill computation. This is distinct from semantic caching (which caches final outputs based on input similarity) — prompt caching operates at the KV cache level and reduces GPU compute, not just API latency.
| Provider | Cache Mechanism | Pricing | TTL |
|---|---|---|---|
| OpenAI (GPT-6 Astra) | Automatic for repeated prefixes | Input tokens at reduced rate | Not publicly documented |
| Anthropic (Opus 5.5) | Automatic, cache_read pricing | $0.20/M for cache reads vs $4/M input | Depends on usage frequency |
| Google (Gemini 4 Argon) | Automatic, cached input 95% off | Introductory: 95% off input pricing | Not publicly documented |
| DeepSeek (V4.1-Flash) | Automatic prefix caching | Cached reads at ~90% discount | Varies |
The 95% cache discount on Gemini 4 Argon is aggressive — it makes long system prompts nearly free on repeated calls, which is a strong incentive for the kind of agent architectures where every tool call resends the same system context.
Prompt caching works by hashing the token sequence and looking up the corresponding KV cache state. For it to hit, the prefix must match exactly — same tokens in the same order. This means:
- System prompts with dynamic content (timestamps, user IDs) will miss the cache unless the dynamic portions come after the cached prefix
- Prompt structures that place variable content first and static instructions last will never cache effectively
- Reordering few-shot examples between requests defeats caching
A well-structured prompt for caching puts the system prompt and static instructions first, followed by few-shot examples (if stable), followed by the user’s variable query last. The first N tokens match the cache; only the variable suffix needs new prefill computation.
Prompt caching checks for matching token prefixes and skips redundant prefill computation on hits.
Streaming and Token Delivery
Once decode begins, tokens can be streamed to the client as they’re generated rather than waiting for the full response. This is what makes LLM applications feel responsive — the user sees text appearing within hundreds of milliseconds even though the full response might take 10+ seconds.
The standard mechanism is Server-Sent Events (SSE) over HTTP. The client opens a single HTTP connection, and the server pushes data: lines containing JSON chunks with partial token content. Each chunk typically contains 1–4 tokens (providers batch small groups of tokens per SSE event to reduce overhead).
The anatomy of a streamed response from a typical provider:
HTTP/1.1 200 OK
Content-Type: text/event-stream
data: {"id":"chatcmpl-abc","choices":[{"delta":{"role":"assistant","content":"The"}}]}
data: {"id":"chatcmpl-abc","choices":[{"delta":{"content":" inference"}}]}
data: {"id":"chatcmpl-abc","choices":[{"delta":{"content":" stack"}}]}
data: [DONE]
Streaming introduces a tension with structured output. JSON mode and function calling require the full output to be valid JSON, but the model generates tokens left-to-right. Providers handle this differently:
- Some buffer tokens internally and only stream once a valid JSON structure is confirmed
- Others stream partial JSON as it’s generated, relying on the constrained decoder to guarantee eventual validity
- Grammar-based constrained decoding (used by vLLM and llama.cpp locally) masks invalid tokens at each step, so every partial output is a valid prefix of a final valid JSON document
The latency between token generation on the GPU and delivery to the client depends on the number of intermediate hops. A production setup might involve: GPU → inference server buffer → load balancer → CDN edge → client TLS → application. Each hop adds some buffering. Providers like Cloudflare Workers AI or running inference at the edge can reduce this chain.
Putting It All Together: A Real Request
Consider a concrete example: a production application sends a 50K-token prompt to Claude Opus 5.5 requesting a code review with medium effort.
A real request flow: prompt cache hits skip 40K tokens of prefill, thinking tokens consume GPU compute, and output tokens stream to the client.
Timeline:
- 0ms: Request leaves client
- ~80ms: Reaches Anthropic’s gateway (network + TLS)
- ~90ms: Auth and rate limiting complete
- ~95ms: Router identifies a 40K-token cache hit (the system prompt). Only 10K new tokens need prefill
- ~295ms: Prefill of 10K tokens completes, KV cache is ready. First decode step begins
- ~350ms: Time-to-first-token — the first visible token reaches the client (after some thinking tokens are generated internally)
- ~350ms–15s: Decode phase generates ~300 thinking tokens and ~800 output tokens. The 800 output tokens stream to the client at ~40ms each
- ~15s: Stream completes. The
[DONE]sentinel fires
The billing: 50K input tokens at $4/M = $0.20 (but 40K of those were cache reads at $0.20/M = $0.008). 800 output tokens at $20/M = $0.016. Thinking tokens at the output rate if charged. Total: roughly $0.03–0.07 depending on thinking token billing.
Compare this to the same request without prompt caching: the full 50K-token prefill would take ~800ms instead of ~200ms, adding 600ms to TTFT. At scale — thousands of requests per second with the same system prompt — caching reduces total GPU-hours by 70–80% for prefill.
Summary
The inference stack has seven critical points where performance is won or lost:
- Prompt caching determines whether redundant prefill work is skipped. Structuring prompts with stable prefixes first is the highest-leverage optimization most applications can make.
- Continuous batching is the reason GPU utilization went from ~20% (static batching) to 70–90%+ in production. This is why vLLM and TensorRT-LLM dominate serving.
- KV cache management (PagedAttention, GQA, MLA, quantized caches) determines how many concurrent requests a GPU pool can serve. Memory, not compute, is the binding constraint during decode.
- Prefill/decode disaggregation separates compute-bound and memory-bound work onto different hardware configurations, improving both TTFT and throughput.
- Quantization (FP8 as the production default, INT4 for cost-sensitive deployments) reduces memory bandwidth requirements proportionally to the bit reduction, directly increasing decode throughput.
- Speculative decoding breaks the sequential decode bottleneck by verifying multiple draft tokens in parallel, with 2–4x speedups on predictable token sequences.
- Attention kernels (FlashAttention-3, ring attention) make long-context inference feasible by reducing memory traffic from O(N²) to O(N) and distributing KV caches across GPUs.
Understanding these layers turns “the API is slow” into “prefill is slow because we’re not caching the system prompt” or “TPOT is high because the provider is running large batches during peak hours.” That specificity is what separates effective infrastructure debugging from guessing.
Further Reading
- vLLM GitHub — The dominant open-source inference engine; source code for PagedAttention, continuous batching, and speculative decoding implementations
- FlashAttention GitHub — Tri Dao’s FlashAttention kernels, including FlashAttention-2 and FlashAttention-3 for Hopper GPUs
- EAGLE GitHub — Speculative decoding using draft heads attached to the target model, with EAGLE-2 achieving 3–4x speedups
- Efficient Memory Management for Large Language Model Serving with PagedAttention (Kwon et al., 2023) — The original PagedAttention paper from the vLLM team
- DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model — Introduces Multi-Head Latent Attention (MLA) and details DeepSeek’s inference architecture
- TensorRT-LLM GitHub — NVIDIA’s optimized inference library with INT4/FP8 quantization, speculative decoding, and multi-GPU parallelism
- llama.cpp GitHub — The reference implementation for quantized local inference; GGUF format, speculative decoding, and consumer GPU/CPU inference
- Anthropic API Documentation — Prompt Caching — Official documentation for Anthropic’s prefix caching mechanism and pricing
- Medusa GitHub — Multi-head speculative decoding that adds prediction heads to the target model itself
- Distilling the Knowledge in a Neural Network (Hinton et al., 2015) — Foundational work on knowledge distillation, relevant to understanding draft model training for speculative decoding