Phase 06/Shipping and being seen/Production inference architecture and performance engineering
PHASE 06 · Shipping and being seen

Production inference architecture and performance engineering

0%
16 h7 subtopics3 lessons · 2 required
In plain English

Knowing how one engine works on one GPU is like knowing how to run one restaurant kitchen. Production inference is running a chain of restaurants that must serve a lunch rush in every city without anyone waiting too long or the owner going broke. This topic is about the arithmetic and the drawings behind that: how many GPUs you need for a given number of users, which model size and precision fits, how requests are routed, what happens when a machine dies, and how you prove the system meets its latency promise. You will write the kind of design document a senior engineer produces before a team spends money on hardware.

Why it matters

Inference engineers are judged on cost per token and tail latency at scale, not on single-GPU benchmarks. A design doc with explicit capacity math is how you earn trust to make hardware and architecture decisions, and it is a standard interview artifact.

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, Cursor, Databricks, ElevenLabs, Fireworks, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Poolside, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Compute KV cache, weight memory and token throughput for a target model, precision and GPU from first principles.
  • Size a cluster for a stated QPS, context distribution and p99 latency SLO with headroom for failures.
  • Choose between tensor parallel, replica and disaggregated prefill/decode layouts with stated trade-offs.
  • Design routing, autoscaling, rollout and observability for an inference fleet.
  • Write a design document that another engineer can critique line by line.

Key concepts

Capacity model
A spreadsheet linking model size, precision, GPU memory and bandwidth to max concurrent sequences and tokens per second.
SLO
A latency or availability target such as p99 TTFT under 500 ms; everything in the design serves it.
Goodput
Throughput counting only requests that met their SLO; the metric that balances batching against latency.
Disaggregated prefill and decode
Running prefill and decode on separate GPU pools with KV transfer between them to isolate their different bottlenecks.
Prefix-aware routing
Sending requests with shared prompts to the same replica so cache hits rise.
Headroom
Spare capacity reserved for traffic spikes and node failures, typically expressed as N plus 1 or a utilization ceiling.
Canary rollout
Shifting a small fraction of traffic to a new engine version while comparing latency and quality metrics.
Cost per million tokens
GPU hourly price divided by sustained tokens per second times 3.6e9; the number finance cares about.

Subtopics

  1. 1. Capacity math from first principles

    Weight bytes, KV bytes per token, max batch from free memory, decode tokens per second from bandwidth, prefill from FLOPs; check against measurements from Phase 3 and 4.

  2. 2. Workload modeling

    Prompt and output length distributions, QPS curves, burst factors, shared-prefix ratio; why averages mislead and percentiles matter.

  3. 3. Parallelism and placement choices

    Replicas versus TP versus PP, when a model needs TP at all, disaggregated prefill/decode, and multi-model fleets.

  4. 4. Routing, autoscaling and resilience

    Gateway design, prefix-aware and least-loaded routing, KV-aware scaling signals, N plus 1 headroom and graceful draining.

  5. 5. Observability and SLO enforcement

    TTFT, ITL, queue depth, KV utilization and preemption metrics; dashboards, alerts and load tests that gate releases.

  6. 6. Cost engineering

    Cost per million tokens by GPU type and precision, quantization trade-offs, spot capacity and when to use smaller models with speculative decoding.

  7. 7. Writing a design document

    Context, goals and non-goals, requirements, options considered, chosen design, capacity table, failure modes, rollout plan, open questions.

Resources

repo
article

Hands-on lessons

L1

Design document for a 70B chat service

CPU · your Macdesign480 minrequired

Goal · Write a complete design document with a capacity spreadsheet for serving a 70B-parameter chat model at 200 QPS peak with p99 TTFT under 800 ms and p99 ITL under 60 ms.

  1. 1Fix the workload: prompt length lognormal with median 1200 tokens and p99 6000, output median 300 tokens, 40 percent of prompts share a 900-token system prefix, peak 200 QPS, trough 30 QPS.
  2. 2Build a spreadsheet computing, for H100 80GB and A100 80GB at FP8 and FP16, weight bytes, KV bytes per token, free KV memory, max concurrent sequences and decode tokens per second per GPU from bandwidth; cite the Phase 3 and 4 measurements you scale from.
  3. 3Decide TP degree per replica and justify it with memory and latency arithmetic; compute replicas needed for peak QPS including 30 percent headroom and N plus 1 for failure.
  4. 4Evaluate a disaggregated prefill/decode layout against the monolithic one using the same spreadsheet; state which you pick and why.
  5. 5Design the gateway with prefix-aware routing, admission control and KV-utilization-based autoscaling; specify scale-up and scale-down signals and cooldowns.
  6. 6Specify the metrics, dashboards and alerts, and a load test plan that must pass before a rollout; include a canary strategy.
  7. 7Write the failure mode table (node loss, OOM from long prompts, hot replica, NCCL hang) with detection and mitigation for each.
  8. 8Compute cost per million tokens for each option and present the final recommendation with explicit assumptions.
Deliverable
design-doc-70b-chat.md plus capacity.csv or a spreadsheet with all formulas visible.
Check
Every number in the doc traces to a formula in the spreadsheet; the chosen design meets both SLOs on paper with headroom, and the cost section states dollars per million tokens for at least two hardware options.
L2

Validate the capacity model against a real engine

Colab T4 · freeexperiment150 minoptional

Goal · Check the capacity spreadsheet's predictions against measured numbers for a small model on a T4 and record the error.

  1. 1Scale the spreadsheet to Qwen2.5-0.5B or TinyLlama in FP16 on a T4 (320 GB/s, 16 GB); predict max concurrent sequences at 2048 context and decode tokens per second at batch 1 and 32.
  2. 2Launch vLLM on Colab with gpu_memory_utilization 0.9 and read the KV cache block count it reports; convert to sequences and compare with your prediction.
  3. 3Run the vllm bench or a simple async client at batch 1 and 32 for 256 output tokens; measure tokens per second.
  4. 4Record predicted versus measured in a table with percent error and explain the two largest discrepancies.
Deliverable
A table of predicted versus measured values with explanations.
Check
Predictions are within 30 percent of measurements, or the discrepancy is explained by a named mechanism (kernel launch overhead, sampling cost, activation memory).
Fallback
Use numbers published in the vLLM or SGLang benchmark blogs for an A100 and compare against your spreadsheet scaled to that GPU.
L3

Take a customer workload from brief to production proposal

CPU · your Macdesign180 minrequired

Goal · Turn a real public inference workload into a benchmarked, costed production proposal that another engineer reviews and can reproduce.

  1. 1Choose a public open-source project, Hugging Face Space or research demo with a real inference workload; link its repository and contact a maintainer or recruit an engineer to act as the customer.
  2. 2Write a one-page discovery brief covering model and quality constraints, traffic shape, input/output lengths, latency and throughput targets, regions, availability, privacy/security, budget, launch date and every unanswered question.
  3. 3Turn the brief into explicit acceptance criteria and a reproducible workload fixture; pin model, engine, container image, hardware assumptions and random seeds.
  4. 4Benchmark two viable configurations with the same load generator; save commands and raw JSON, and report TTFT, ITL, end-to-end latency, goodput and error rate at three concurrency levels.
  5. 5Use the measurements to calculate replicas, headroom and cost per million input and output tokens; reconcile every headline number to the raw benchmark within one percent.
  6. 6Write the proposed architecture, capacity plan, deployment pipeline, canary and rollback plan, SLOs and alerts, failure modes, and a cheaper fallback that states what it sacrifices.
  7. 7Present the proposal for twenty minutes to the maintainer or another engineer; ask them to challenge the assumptions, operational burden and value rather than only the code.
  8. 8Record written feedback, revise the proposal, and add a change log showing which points you accepted, rejected and why; optionally publish it as an issue or discussion on the project.
Deliverable
A public or shareable repository containing the discovery brief, pinned workload, benchmark scripts and raw data, capacity/cost spreadsheet, production proposal, presentation, written feedback and revision change log.
Check
A clean checkout reproduces both benchmark configurations; proposal numbers reconcile to raw data within 1 percent; all discovery acceptance criteria map to a test, SLO or stated trade-off; reviewer sign-off is preserved as a public issue/comment or dated written review.

Build your own

Build your own capacity and cost planner

PythonCPU · your Mac~8 h

A command-line planner that turns a model config, a GPU spec and a traffic profile into memory budgets, concurrency limits, replica counts, SLO feasibility and dollars per million tokens, with every number traceable to a formula.

The real thing: github.com/vllm-project/vllm/blob/main/vllm/v1/core/kv_cache_utils.py ↗

How you know a stage passes

Write tests/test_planner.py first with hand-computed expected values for Llama-2-7B, Llama-3-70B and a GQA model (TinyLlama), and for the A100-80GB, H100-80GB and T4 specs stored in gpus.yaml. Each stage adds assertions on exact byte counts, on derived numbers within 1 percent of a hand calculation, and on a CLI command that must exit 0 and write a file. Run `pytest -q`; a stage passes when its tests and all earlier ones are green.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01model and KV arithmetic from config.json
    `planner model <hf-id-or-path>` reads config.json and prints parameter count, weight bytes per dtype, and KV bytes per token (honouring GQA) for fp16, fp8 and int8 KV.
    test · Llama-2-7B reports 524,288 KV bytes per token in fp16 and 6,738,415,616 parameters; TinyLlama reports 4 KV heads and 8x fewer KV bytes than a 32-head MHA layout; GPT-2 small reports 124,439,808 parameters.
  2. 02memory budget and max concurrency per GPU
    `planner memory` combines weights, a configurable activation reserve and gpu_memory_utilization into free KV bytes, then into KV blocks and the maximum concurrent sequences at a given context length, for a TP degree that splits weights and KV.
    test · For Llama-2-7B fp16 on A100-80GB at utilization 0.9 the free KV bytes equal 0.9*80e9 minus weight bytes minus the reserve to the byte, and max sequences at 4096 context match a hand calculation; for 70B fp16 with TP 1 the tool reports 'does not fit' and with TP 4 reports a positive count.
  3. 03roofline throughput and latency model
    `planner perf` estimates decode tokens per second per GPU from HBM bandwidth and bytes per step (weights plus KV read at the batch's mean context), prefill time from FLOPs and peak tensor throughput, and produces TTFT and ITL curves versus batch size with a configurable efficiency factor.
    test · At batch 1 the decode estimate equals bandwidth divided by weight bytes within 1 percent; ITL grows monotonically with batch and TTFT grows linearly with prompt tokens; the T4 estimate for TinyLlama is within 30 percent of the number you measured in lesson l2 (or the vLLM blog number in the fallback).
  4. 04traffic profile and replica sizing
    `planner size` takes a traffic YAML (QPS peak and trough, prompt and output length distributions, prefix share) and returns replicas needed at peak with headroom and N plus 1, per-replica concurrency, and whether p99 TTFT and ITL targets are met on the model from stage 3.
    test · For the lesson l1 workload (200 QPS peak, median 1200 prompt, 300 output) the tool returns the same replica count as your spreadsheet within 1 replica for H100 FP8 TP 2 and flags the configuration that violates the 60 ms ITL target.
  5. 05cost per million tokens and option comparison
    `planner compare` evaluates a list of (GPU, dtype, TP, disaggregated or monolithic) options, computing hourly cost at peak and at average utilization, dollars per million input and output tokens, and writes a Markdown table sorted by cost with SLO pass or fail per option.
    test · The table lists every option with cost per million tokens that reproduces a hand calculation (hourly price times replicas divided by tokens per hour) within 1 percent; options that fail an SLO are marked and sorted last; the command exits 0 and writes compare.md.
  6. 06calibration against measurements
    `planner calibrate` reads a CSV of measured (model, GPU, batch, context, tokens per second, TTFT) rows from Phase 3 and 4 benchmarks, fits the efficiency factor per GPU, and reports prediction error before and after.
    test · After calibration on your T4 measurements, mean absolute percent error on held-out rows is at most 25 percent and lower than before calibration; the fitted factor is written to gpus.yaml and `planner size` uses it.

Knowledge check

QHow do you estimate decode tokens per second per GPU from first principles?

Each decode step reads all weights plus the batch's KV cache once; divide GPU memory bandwidth by bytes read per step to get steps per second, then multiply by batch size.

QWhy might disaggregating prefill and decode improve goodput?

Prefill is compute-bound and decode is bandwidth-bound; mixing them in one batch makes decode steps wait behind long prefills, hurting ITL, while separate pools let each be batched optimally.

QWhat signal should drive autoscaling for an LLM serving fleet, and why not CPU or GPU utilization?

KV cache utilization and queue depth or TTFT; GPU utilization is near 100 percent even when latency is fine, so it does not reflect remaining capacity.

QHow is cost per million tokens computed?

GPU hourly price divided by sustained output tokens per hour, scaled to one million; it falls with batch size until the latency SLO caps batching.

Completion

  • All 7 subtopics marked done
  • All 2 required lessons done
  • Lesson l1 design document and spreadsheet complete and reviewed by at least one other person.
  • Can derive KV bytes per token and decode throughput for a new model on a whiteboard.
  • All subtopics marked completed.
  • Customer workload capstone reviewed by another engineer, revised from written feedback and reproducible from a clean checkout.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →