Platform Engineering · Lesson 245

Capstone: Build and Benchmark a Production LLM Inference Service on Kubernetes

This capstone takes a chat model from "it runs on my GPU" to a service a company can depend on: the memory arithmetic that picks the GPU, a GPU node pool and a serving runtime, a benchmark sweep that finds how much load one replica carries inside its latency targets, replicas sized by Little's law, autoscaling with a warm floor, a canary gated on quality evaluations, SLOs on time to first token and time per output token, and a cost per million tokens you can defend. It follows the project end to end, and shows the two mistakes that most often turn a good launch into a slow one: a benchmark with unrealistic prompts, and an endpoint that scales to zero during a GPU shortage.

Difficulty: Master · Know this first: Lesson 239, Lesson 231, Lesson 235

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar splits the project from requirements to a steady-state service, in working days. It is a worked example, not a measurement. Benchmarking and the canary are the slices that buy confidence; skipping them shortens the bar and lengthens the incident list.

Try it: size the endpoint from your sweep

Enter the working concurrency of one replica from your benchmark, its latency per request, the peak request rate, and the GPU price. The replica count follows from Little's law, with 25 percent headroom.

in flight = peak × time per request · replicas = ceil(in flight ÷ concurrency × 1.25) · cost per hour = replicas × GPU price

252requests in flight at peak
7replicas (GPUs)
$28per hour at peak

Seven GPUs at peak, with headroom

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

This capstone grows in four levels: first the targets and the arithmetic, then a running service, then measured capacity and safe rollout, and finally a cost-aware fleet.

Basic — Targets and arithmetic

At the basic level you can write the targets and do the sums: peak requests a second, prompt and answer lengths, TTFT and TPOT targets, and memory = weights + KV cache + overhead. You know that time per request ≈ TTFT + output tokens × TPOT, and that in flight = rate × time.

Where it breaks: targets without prompt lengths; every capacity number depends on them.

Try it: Basic

TTFT is 0.7 s, TPOT is 35 ms, and answers average 300 tokens. About how long is a request in flight?

Now do it: Run llm_capacity_plan.py in Go deeper with your own peak rate and answer length.

Intermediate — A running service

At the intermediate level you stand it up: a GPU node pool, the serving engine behind KServe with the settings recorded, the AI gateway in front, readiness after warm-up, and dashboards from the engine and DCGM.

  • Pin the model version and engine version.
  • Expose the OpenAI-compatible API through the gateway, not directly.
  • Pre-pull images and cache weights so a new replica starts in under two minutes.

Try it: Intermediate

Why put the model behind the AI gateway rather than exposing the engine directly?

Now do it: Draw the request path from the app to the GPU and name every hop.

Advanced — Measured capacity and safe rollout

At the advanced level the numbers are measured and the changes are gated.

  • A concurrency sweep with production-like prompts, repeated after any model, engine, or GPU change.
  • Replicas from Little's law with headroom; autoscaling on in-flight requests or queue depth; a warm floor.
  • Canaries gated on latency, errors, and evaluation scores.
  • SLOs on TTFT, TPOT, and availability with burn-rate alerts.

Try it: Advanced

You upgrade the serving engine for a 20 percent throughput gain. What do you redo before relying on it?

Now do it: Write the canary scorecard for your endpoint: three latency numbers, one error rate, one quality score.

Master — A cost-aware fleet

At the master level you run inference as a fleet with a budget.

  • Reserved or committed GPUs for the base load, on-demand for bursts, and a smaller fallback model when GPUs are short.
  • Routing simple requests to smaller models, and caching repeated prompts.
  • Cost per million tokens per endpoint, reviewed monthly with idle GPU-hours.
  • Capacity planning a quarter ahead with the cloud provider for the GPU type you depend on.

Trade-off: reserved GPUs are cheaper per hour and paid whether used or not; on-demand is flexible and may not exist when you ask. Reserve the floor, burst on demand, and have a fallback.

Try it: Master

During a GPU shortage, autoscaling cannot add replicas at peak. What keeps the service up?

Now do it: Write the degradation plan for your endpoint: what happens at 100, 150, and 200 percent of planned peak.

Go deeper

The capacity plan is a few lines once the sweep exists. This script finds the highest concurrency inside the SLO from a sweep, sizes replicas with Little's law, prices the fleet, and flags the short-prompt trap. The sweep rows are example numbers with a realistic shape; replace them with your own benchmark. Standard library only; python3 llm_capacity_plan.py.

From sweep to fleet

# llm_capacity_plan.py - from a benchmark sweep to replicas, GPUs, and cost per million tokens
import math

# A concurrency sweep for one replica (one GPU), as a benchmark tool reports it.
# These are example results with a realistic shape, not measurements from a specific GPU.
# (concurrent requests, p95 time to first token in s, p95 time per output token in ms, output tokens/s)
sweep = [(8, 0.25, 18, 420), (16, 0.31, 21, 760), (32, 0.48, 27, 1180),
         (48, 0.74, 34, 1410), (64, 1.30, 44, 1450), (96, 2.90, 61, 1470)]
SLO_TTFT_S, SLO_TPOT_MS = 1.0, 40          # p95 targets for the chat endpoint

ok = [row for row in sweep if row[1] <= SLO_TTFT_S and row[2] <= SLO_TPOT_MS]
conc, ttft, tpot, tps = ok[-1]
print(f"highest concurrency inside the SLO: {conc} (TTFT p95 {ttft}s, TPOT p95 {tpot} ms, {tps} tokens/s)")
print(f"next step, {sweep[len(ok)][0]} concurrent, breaks it: TTFT {sweep[len(ok)][1]}s, TPOT {sweep[len(ok)][2]} ms")

peak_rps, out_tokens, in_tokens = 20, 350, 1800
latency_s = ttft + out_tokens * tpot / 1000
in_flight = peak_rps * latency_s                       # Little's law
replicas = math.ceil(in_flight / conc * 1.25)          # 25% headroom for bursts and one lost replica
print(f"peak {peak_rps} req/s x {latency_s:.1f} s in flight = {in_flight:.0f} concurrent -> {replicas} replicas at {conc} each, with headroom")

gpu_hour = 4.0                                         # example price per GPU-hour
tokens_per_hour = replicas * tps * 3600 * 0.6          # at an average 60% of peak load
print(f"{replicas} GPUs x ${gpu_hour}/h = ${replicas * gpu_hour:.0f}/h; at 60% average load"
      f" about ${replicas * gpu_hour / tokens_per_hour * 1e6:.2f} per million output tokens")

# The trap: benchmarking with prompts shorter than production's.
print(f"benchmark prompts of {in_tokens // 4} tokens vs production {in_tokens}: prefill does about 4x the work,"
      f" so re-run the sweep with real prompt lengths before trusting the TTFT column")
$ python3 llm_capacity_plan.py
highest concurrency inside the SLO: 48 (TTFT p95 0.74s, TPOT p95 34 ms, 1410 tokens/s)
next step, 64 concurrent, breaks it: TTFT 1.3s, TPOT 44 ms
peak 20 req/s x 12.6 s in flight = 253 concurrent -> 7 replicas at 48 each, with headroom
7 GPUs x $4.0/h = $28/h; at 60% average load about $1.31 per million output tokens
benchmark prompts of 450 tokens vs production 1800: prefill does about 4x the work, so re-run the sweep with real prompt lengths before trusting the TTFT column

Read it like this: 48 concurrent is the knee; 20 requests a second of 12.6 seconds each puts about 253 in flight; seven replicas carry that with headroom; and the cost per million output tokens follows from the GPU price and the realistic load, not the peak.

Run your own sweep

# With vLLM's benchmark script (or any load tool that records TTFT and TPOT), against one replica.
# Use a dataset sampled from production-like prompts; record the lengths alongside the results.
for c in 8 16 32 48 64 96; do
  vllm bench serve --base-url http://chat-predictor.models.svc:8000 --model chat \
    --dataset-name custom --dataset-path prompts.jsonl --max-concurrency $c --num-prompts 600 \
    --save-result --result-filename sweep-c$c.json
done

The benchmark command follows vLLM's vllm bench serve tool; its flags change between releases, so check vllm bench serve --help for your version. Run it from a pod in the same cluster, against one replica with autoscaling paused, so the numbers describe one replica.

One time it broke

This is a composite of a failure pattern that keeps repeating; the numbers are illustrative. A team launched an internal assistant after benchmarking with a public chat dataset.

Timeline

  • LaunchThe assistant attaches retrieved documents to every prompt: 2,000 tokens instead of the benchmark's 400. TTFT p95 is 3 seconds against a 1-second target.
  • Day 2Scaling out helps only partly: each replica now holds fewer concurrent requests because long prompts fill the KV cache. The bill doubles.
  • Day 5A sweep with real prompts sets the working concurrency at a third of the old figure; prefix caching for the shared instructions and a tighter retrieval limit bring TTFT back under target.

What changed after

Every inference project now records prompt and answer length distributions before benchmarking, and the sweep is re-run whenever the prompt template, retrieval settings, model, or engine change. The capacity plan cites the sweep it came from.

If you remember nothing else

Design exercise

Deliver a production inference service for a customer-support assistant that must answer within 1 second to first token at p95, for 30 requests a second at peak, on Kubernetes in one cloud region.

Clarifying questions to ask

What are the real prompt and answer lengths, including retrieved context? Which model passes the evaluation set at which precision? Which GPUs can the region supply, and can you reserve them? What happens at twice the planned peak?

Rough sizing

Say prompts of 2,000 tokens with a 600-token shared system prompt, answers of 250 tokens, and an 8B model.

Shape of the answer

Requirements with measured lengths; model and precision from evals; memory sum; a tainted GPU pool across two zones with pre-pulled images; vLLM with prefix caching behind KServe and the AI gateway; a sweep with real prompts; replicas from Little's law with a warm floor on reserved GPUs and on-demand burst; canaries gated on TTFT, TPOT, errors, and eval scores; SLOs with burn-rate alerts; a fallback route to a smaller model; monthly cost per million tokens.

Trade-offs to name

A larger model may answer better and needs more GPUs per request; a smaller one routed with fallbacks is cheaper and must pass the evals. Reserved capacity lowers price and risk and is paid when idle. Prefix caching cuts TTFT for shared prompts and uses KV memory that could hold more requests.

Saved on this device, in this browser.
Next in this series · Lesson 246
Capstone: Ship a Controlled Enterprise AI Agent: Tools, MCP, State, Approvals, and Evaluation

An agent that can act, refund an order, change a ticket, restart a service, has to be built like any system that moves money or changes production: least-privilege tools, durable state so a retry never repeats an action, human…

Go to Lesson 246 →

Or browse the full course from the Lessons index.