Pidoku

Anatomy of an Inference Service

Module 20 Lesson 20.a 1h Difficulty 3/5

Prerequisites 12.j, 12.l, 15.a


Before you start: words you need#

WordPlain meaning
EngineThe program that runs the model on the GPUs and batches requests (vLLM, SGLang, TensorRT-LLM). Lesson 15.a takes it apart.
ReplicaOne running copy of the engine with its own GPUs. A service usually has several.
Serving systemEverything around the engines that turns them into a product: gateway, queues, routing, scaling, rollout, metrics. This module.
ProcessOne running program with its own memory. A single engine replica is often several processes.
TTFTTime to first token: how long the user waits before the first word of the answer appears (2.c).
Inter-token latencyThe gap between one streamed token and the next, once the answer has started (2.c).
Control planeThe parts that manage replicas (start, stop, update them) rather than serve requests.

1. What is it?#

An inference service is the whole system between a user’s request and the GPU: not just the engine, but the gateway in front of it, the queue that protects it, the router that picks a replica, the controller that adds or removes replicas, and the telemetry that tells you whether it is healthy.

Lesson 15.a described the inside of one engine (API server, scheduler, KV cache manager, model runner, sampler). This module is about everything around the engine. This lesson is its map: the parts, how a request flows through them, and which process each part lives in.

flowchart LR
  C(("clients")) --> GW["Gateway<br/><small>auth, quotas, rate limits</small>"]
  GW --> RT["Router<br/><small>pick a replica</small>"]
  RT --> R1
  RT --> R2
  subgraph R1["Replica 1"]
    direction TB
    A1["API server<br/><small>validate, tokenize, stream</small>"] --> E1["Engine core<br/><small>queue, scheduler, KV cache</small>"] --> G1["GPU workers"]
  end
  subgraph R2["Replica 2"]
    direction TB
    A2["API server"] --> E2["Engine core"] --> G2["GPU workers"]
  end
  CP["Control plane<br/><small>autoscaler, rollout, registry</small>"] -.-> R1
  CP -.-> R2
  R1 -.->|"metrics"| M[("Telemetry")]
  R2 -.->|"metrics"| M
  M -.-> CP

  class C neutral
  class GW,RT,A1,A2 io
  class E1,E2 queue
  class G1,G2 compute
  class CP,M memory
PartJobLesson
GatewayAuthentication, per-tenant quotas, rate limits, request logging21.i
Router / load balancerChoose which replica gets each request20.f, 21.g, 21.h
API serverParse and validate the request, apply the chat template, tokenize, stream tokens back20.b
Queue and admissionHold requests the engine cannot start yet; refuse what it never could20.c
Engine coreBatch requests every step, manage the KV cache, run the model15.a, 20.d
Timeouts and retriesStop work nobody is waiting for; retry safely20.e
AutoscalerAdd or remove replicas as load changes20.g
Model lifecycleLoad, warm up, update and unload model weights20.h
TelemetryQueue depth, time to first token, token rate, KV usage, errors22.j

2. Why it is structured this way#

Every part exists because of a fact from Module 12:

FACT ABOUT LLM INFERENCE                       → PART THAT HANDLES IT
Requests have unknown, wildly different cost   → a scheduler that decides every step (15.a)
GPU memory for the KV cache is the real limit  → admission control in front of the engine (20.c)
Decode is memory-bound, so batching pays       → batching inside the engine, not per request (20.d)
Tokens must reach the user as they are made    → a streaming API layer (20.b)
Starting a replica takes minutes               → an autoscaler that plans ahead (20.g)
Each replica caches different prompts          → a router that knows what each holds (21.h)
CPU work can stall the GPU loop                → API work in separate processes (section 6)

The architecture is a consequence of the physics. That is why vLLM, SGLang, TensorRT-LLM with Dynamo, and every in-house system converged on roughly the same shape.


3. Simple analogy#

A hospital emergency department.

  • Gateway — the front door: who may enter, how many at once.
  • Router — the dispatcher who sends a patient to the ward that already has their records.
  • API server — reception: check in, take details, keep the family updated (streaming).
  • Queue and admission — triage: who waits, who is sent elsewhere.
  • Engine — the ward: beds (KV cache) and doctors (GPU) treating many patients at once.
  • Autoscaler — the manager who opens another ward before the waiting room overflows.

The bottleneck is beds, not doctors. Triage exists because beds are scarce — exactly the KV-cache-bound situation of an LLM service.


4. Tiny example — one request, end to end#

Follow one chat request with a 2,000-token prompt and a 300-token answer:

t = 0 ms      Gateway: API key valid, tenant under quota            (~1 ms)
t = 1 ms      Router: replica 2 already holds this system prompt    (~1 ms)
t = 2 ms      API server: JSON parsed, chat template applied,
              2,000 tokens produced by the tokenizer                 (~3 ms)
t = 5 ms      Queue: replica 2 is busy; request waits               (~40 ms)
t = 45 ms     Engine: scheduler admits it; 1,500 prompt tokens hit
              the prefix cache, 500 are prefilled this step          (~60 ms)
t = 105 ms    First token sampled and streamed         ← TTFT = 105 ms
t = 105 ms    Decode: one token per step, batched with ~60 others   (~25 ms/token)
t ≈ 7.6 s     300th token; request finishes, KV blocks freed

Notice where the time goes: almost nothing in the gateway, router and API server; the user’s experience is decided by queueing (40 ms) and by the engine’s step time (25 ms per token). Most of this module is about controlling those two numbers.


5. Technical explanation of each layer#

Gateway#

The shared front door for every model a company serves. It authenticates callers, enforces per-tenant quotas and rate limits (counted in tokens, not requests — lesson 23.j), logs usage for billing, and forwards the request. It must not buffer streamed responses. Lesson 21.i.

Router#

Chooses a replica. Round-robin is a poor choice for LLMs because replicas differ in queue depth, KV memory use and which prompt prefixes they have cached. Modern routers score replicas on all three (20.f, 21.h); in Kubernetes this is standardised by the Gateway API Inference Extension.

API server#

Responsibilities:
  - protocols: HTTP/1.1 + server-sent events, HTTP/2, gRPC, WebSocket for realtime
  - validation: parameter ranges, maximum lengths, JSON-schema checks
  - chat template and tokenization
  - incremental detokenization and streaming
  - per-request metrics

Design rules:
  - asynchronous (thousands of long-lived connections)
  - a SEPARATE process from the engine loop, so HTTP parsing and tokenization
    never delay a GPU step
  - talks to the engine over a local socket or shared memory (vLLM uses ZeroMQ)

Large deployments run several API-server processes per engine — vLLM’s --api-server-count exists because one process cannot tokenize fast enough for very short requests at high rates.

Engine core#

Owns the waiting and running queues, the per-step scheduling decision, and the KV cache. Its policies — admission, batch size, chunked prefill, preemption, priorities — are what Modules 16 and 17 read in vLLM’s source. From the serving system’s point of view it is a black box with three knobs (maximum batch, token budget, memory fraction) and a handful of metrics.

GPU workers#

One process per GPU, all running the same step in lockstep under tensor or pipeline parallelism, communicating through NCCL (9.f). The engine core sends them each step’s plan.

Control plane#

Not on the request path at all: the autoscaler (20.g), rollout controller (20.j), model registry (21.b) and configuration. It acts on replicas, never on individual requests. Lesson 21.a explains why that separation matters.


6. Under the hood — processes on one replica#

A vLLM replica with tensor parallelism 4 (one model split across 4 GPUs) looks like this (lesson 16.d reads the code):

Process: API server(s)          asyncio HTTP, tokenizer, detokenizer
   │  ZeroMQ
Process: engine core            scheduler + KV cache manager, the step loop
   │  shared memory / message queue
Process: GPU worker 0..3        one per GPU, NCCL between them

Why separate processes instead of threads?

  1. Python’s global interpreter lock (GIL). Only one thread runs Python at a time. HTTP and tokenization work in the same process would delay the step loop and raise inter-token latency.
  2. One CUDA context and NCCL rank per GPU is the simplest, most robust model.
  3. Fault isolation. An API-server crash should not unload the model.

The price is inter-process communication on every request. Engines reduce it with shared memory for large payloads (images, long prompts) and compact serialization.


7. Performance implications#

At large batch sizes the GPU work per step is well optimised; the engine’s CPU work becomes visible. A typical breakdown of engine-process CPU time per step at batch 128:

preparing inputs (token ids, positions, block tables)   30–45%
scheduler bookkeeping                                    15–25%
sampling metadata                                        10–15%
output processing                                        10–15%
kernel launches (with CUDA graphs)                        5–10%

This is why engines moved hot paths to C++ or Rust, overlap CPU preparation of step N+1 with GPU execution of step N (asynchronous scheduling, 17.d), and why vLLM added a Rust frontend (19.h). If a replica’s GPU looks idle between steps, profile the engine process first (22.i).


8. Production implications#

  • Monitor each layer separately: gateway latency, router decisions, queue depth, time to first token, inter-token latency, KV cache usage, GPU step time. One end-to-end latency number hides which layer is failing.
  • Scale API servers and engines independently. Short-prompt, high-rate traffic needs more API processes per engine; long-prompt traffic does not.
  • Fail cleanly. If an engine dies, in-flight requests must get an error immediately, not hang until the client times out. The router must stop sending to it within seconds.
  • Bound every queue (20.c). An unbounded queue turns a load spike into an outage.

9. Common mistakes#

  1. Running HTTP handling and the engine loop in one Python process. GIL contention shows up as jittery inter-token latency.
  2. Round-robin load balancing across replicas. It ignores load and cached prefixes (20.f).
  3. No queue limit. Requests complete long after the client gave up.
  4. Blocking the API server’s event loop with synchronous tokenization or logging.
  5. Treating the engine as a black box. When latency rises you must know which layer caused it.

10. Hands-on exercise#

A. Draw your system. For a service you run or plan, draw the diagram in section 1 with real names (which gateway, which router, which engine, which autoscaler). Mark which parts you do not have yet.

B. Map a real replica. Start vLLM with --tensor-parallel-size 2 (or 1 if you have one GPU). List its processes and threads (ps -eLf, py-spy dump --pid on each). Label them with the names from section 6. Which process would you profile for an inter-token-latency problem? For a time-to-first-token problem?

C. Time the layers. Send a request with a 2,000-token prompt and record: time to the gateway, time in queue (from engine metrics), time to first token, time per output token. Rebuild the timeline of section 4 from your own numbers.

D. Build it (Project 06). Implement a minimal service: an HTTP server that tokenizes, a bounded queue, an engine loop that batches, and a streaming response. Projects 07–09 extend it.


11. Interview questions#

  1. Name the parts of an LLM inference service outside the engine and what each one owns.
  2. Why are the API server and the engine core separate processes?
  3. Walk through where time goes for one request from gateway to first token.
  4. Why is round-robin a poor load-balancing choice for LLM replicas?
  5. At large batch sizes, where does the engine’s CPU time go, and what do engines do about it?
  6. What should happen to in-flight requests when one engine replica crashes?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in