Phase 03/Anatomy of a serving system/LLM serving architecture
PHASE 03 · Anatomy of a serving system

LLM serving architecture

0%
6 h5 subtopics2 lessons · 1 required
In plain English

When you type into a chatbot, your words do not go straight to the model. They pass through a chain of helpers, much like a letter passing through a post office. A front door (the API server) accepts the request and checks it. A tokenizer turns your words into numbers. A scheduler decides when your request gets its turn on the GPU, bundling it with other people's requests. A model runner does the actual maths, and a detokenizer turns numbers back into words that stream to your screen. Model loading is the step before any of this, where tens of gigabytes of weights are read from disk and placed on the GPU. This topic maps the whole pipeline so every later topic has a home.

Why it matters

Every inference engine is a different answer to the same set of design questions. Once you can name the stages (API, tokenize, schedule, run, sample, detokenize, stream) you can read any engine's source tree and understand where latency and memory are spent.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Cohere, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Draw the request path through a modern LLM server from HTTP to streamed tokens.
  • Explain how model weights get from safetensors files into GPU memory.
  • Compute the GPU memory budget for weights, KV cache and activations for a given model.
  • Describe the OpenAI-compatible API and why engines converge on it.
  • Identify which stage is responsible for TTFT and which for ITL.

Key concepts

Serving engine
The process that owns the GPU, holds the weights, and executes batched forward passes for many requests.
API server
The HTTP front end (usually FastAPI/uvicorn) that validates requests and streams responses, often in a separate process from the engine.
Safetensors
A zero-copy, memory-mappable weight file format that replaced pickle-based .bin files for safe, fast loading.
Memory budget
GPU memory split into weights, KV cache, activations and CUDA workspace; the KV share determines how many requests fit.
Sampler
The stage that turns logits into a token using temperature, top-p, top-k and penalties.
Streaming (SSE)
Server-sent events that push each new token to the client as soon as it is decoded.
Tokenizer / detokenizer
Convert text to token ids and back; detokenization is incremental so partial tokens are not emitted.

Subtopics

  1. 1. The request lifecycle

    HTTP request, validation, tokenization, admission to the waiting queue, scheduling, prefill, decode steps, detokenization, streaming, completion.

  2. 2. Model loading

    Reading config.json and safetensors shards, mapping HF parameter names onto engine modules, dtype casting, and loading directly to the GPU.

  3. 3. GPU memory budgeting

    Weights = params * bytes; KV per token = 2 * layers * kv_heads * head_dim * bytes; the remainder after activations becomes KV blocks.

  4. 4. OpenAI-compatible APIs

    The /v1/chat/completions and /v1/completions contracts, chat templates, and why almost every engine implements them.

  5. 5. Process layout

    API process versus engine core process, IPC between them, and multi-process workers for tensor parallelism.

Resources

documentation
article

Hands-on lessons

L1

Build a toy LLM server on CPU

CPU · your Macscript120 minrequired

Goal · Serve Qwen2.5-0.5B-Instruct behind a FastAPI /v1/chat/completions endpoint with token streaming, written by you.

  1. 1pip install torch transformers fastapi uvicorn sse-starlette; load Qwen/Qwen2.5-0.5B-Instruct in bfloat16 (or float32 on CPU).
  2. 2Implement a POST /v1/chat/completions handler that applies the chat template with tokenizer.apply_chat_template.
  3. 3Write a manual decode loop (no model.generate) that keeps past_key_values and yields one token per step.
  4. 4Stream tokens as server-sent events in the OpenAI chunk format; detokenize incrementally.
  5. 5Add timing logs for tokenization, prefill, each decode step and detokenization.
  6. 6Call it with the openai Python client pointed at base_url http://localhost:8000/v1 and confirm streaming works.
  7. 7Print a per-stage time breakdown for a 50-token prompt and 50-token answer.
Deliverable
server.py plus a markdown table of per-stage timings for one request.
Check
The openai client receives a streamed response; prefill time is a single number while decode shows about 50 roughly equal step times.
L2

Memory budget calculator

CPU · your Macnotebook45 minoptional

Goal · A function that, given a HF config.json and GPU size, returns weight bytes, KV bytes per token and max concurrent tokens.

  1. 1Download config.json for Qwen2.5-0.5B, Llama-3.1-8B and Qwen2.5-72B with huggingface_hub.
  2. 2Implement weight_bytes(config, dtype) and kv_bytes_per_token(config, dtype) using num_key_value_heads.
  3. 3Compute how many KV tokens fit on a 16 GB T4, 24 GB L4 and 80 GB H100 after weights at 90% utilization.
  4. 4Compare your 8B numbers against the KV cache size vLLM logs on startup (search the docs or a Colab run).
Deliverable
A notebook with a table of models x GPUs showing max KV tokens.
Check
Llama-3.1-8B in FP16 gives about 16 GB of weights and 128 KB of KV per token.

Build your own

Build your own OpenAI-compatible server

PythonCPU · your Mac~6 h

A FastAPI front door, a separate model worker process and SSE token streaming, so every stage of the request path is code you wrote.

The real thing: github.com/vllm-project/vllm/blob/main/vllm/entrypoints/openai/api_server.py ↗

How you know a stage passes

Write tests/test_server.py first. A pytest fixture starts your server as a subprocess on a free port, waits for /health, and tears it down. Every stage adds tests that hit the server with httpx and with the official openai Python client (base_url pointed at localhost) and assert on status codes, JSON fields and token streams. Run `pytest -q`; a stage is done when its tests pass and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01/v1/models and a tokenizer round-trip
    FastAPI app exposes GET /health, GET /v1/models and POST /v1/completions that echoes the prompt back through the Qwen2.5-0.5B tokenizer with a correct usage block.
    test · curl /v1/models lists one model id; POST with a 37-token prompt returns usage.prompt_tokens equal to 37 and text identical to the input after detokenization.
  2. 02a model worker in its own process
    A worker process loads the model and serves generate requests over a multiprocessing queue; the API process never imports torch.
    test · ps shows two Python processes; the openai client gets a 32-token completion; kill -9 on the worker makes the next request return HTTP 503 instead of crashing the API.
  3. 03chat completions with SSE streaming
    POST /v1/chat/completions applies the chat template and, with stream=true, emits one data chunk per token in the OpenAI delta format ending with data [DONE].
    test · curl -N shows data chunks arriving one at a time; concatenated delta.content equals the non-streaming content for the same greedy prompt, and the openai client's streaming iterator consumes it without error.
  4. 04validation and OpenAI-shaped errors
    Requests are validated with pydantic (temperature, max_tokens, stop, n) and failures return the OpenAI error object with type invalid_request_error.
    test · pytest sends temperature 5.0 and a missing messages field and asserts HTTP 400 with error.type equal to invalid_request_error; the openai client raises BadRequestError.
  5. 05concurrent requests and a static batch in the worker
    The API handles many in-flight requests with asyncio; the worker drains its queue and runs up to 8 prompts per forward pass with padding.
    test · 8 concurrent 32-token requests all complete with correct usage counts, and total wall-clock is under 2x the single-request time; the same test at batch size 1 is at least 3x slower.
  6. 06/metrics
    A Prometheus /metrics endpoint exposes request count, tokens generated, TTFT and e2e latency histograms, and worker queue depth.
    test · After exactly 10 requests, curl /metrics shows requests_total 10 and generated_tokens_total equal to the sum of usage.completion_tokens; histogram bucket counts sum to 10.

Knowledge check

QWhich stage of the serving pipeline determines time to first token?

Queueing plus prefill; the first token can only stream after the whole prompt has been processed in one forward pass.

QWhy do engines put the API server and the engine core in different processes?

So HTTP parsing, tokenization and JSON serialization on the CPU never stall the GPU loop, and so the engine can be restarted or scaled independently.

QHow many bytes of KV cache does one token need for a model with 32 layers, 8 KV heads, head_dim 128 in FP16?

2 * 32 * 8 * 128 * 2 bytes = 131,072 bytes, or 128 KB per token.

QWhy is safetensors preferred over torch.save pickles for model loading?

It cannot execute arbitrary code, it can be memory-mapped for zero-copy loading, and tensors can be loaded lazily and sharded.

Completion

  • All 5 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 server streams tokens to the openai client and the timing table is saved.
  • Can sketch the request lifecycle and the GPU memory split from memory.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →