LevelUpWith

Explore / AI Engineering

Serving LLMs in Production: Engines, Scale and Cost

Run open models behind an OpenAI-compatible API, load-test them for TTFT, inter-token latency and goodput, size GPUs, autoscale and route traffic, then cut your cost per request in half and show that output quality held.

Read lesson 1 free →

Levels 1 and 2 are free to read, no account needed. Levels 3 and 4 are free with a free account, and so are 20 answers from the AI tutor.

Photographic 3D course artwork for Serving LLMs in Production: Engines, Scale and Cost

Expert · 48 levels · 4 free · Created Nov 2026 · Professionally curated by levelupwith.com

What's inside

  1. Level 1: One Request, Token by TokenFree
    You follow a single chat request through tokenisation, the forward pass, sampling and detokenisation to see that an LLM generates one token per step, and that this loop is why serving is harder than an ordinary API call.
    • Use a Hugging Face tokenizer and a small open model in Python to step through the generation loop by hand and print each sampled token
    • Explain why the work done per output token is roughly the same at every step, and why output length matters more to cost than input length suggests
    • Count the tokens in a set of real prompts and replies and estimate how many forward passes each request needs
  2. Level 2: Prefill and Decode: Two Very Different JobsFree
    You learn that prefill processes the whole prompt in one parallel, compute-heavy pass, while decode emits tokens one at a time and is limited by memory bandwidth, and that this split drives almost every serving decision later in the course.
    • Time prefill and decode separately for prompts of different lengths on a rented GPU and plot how each one scales
    • Work out a rough decode speed ceiling by dividing GPU memory bandwidth by the model's weight bytes, then compare it with what you measured
    • Say for a given workload (long RAG prompts or long chat replies) whether prefill or decode will dominate
  3. Level 3: The KV Cache: Memory That Grows With Every Token
    You see what the KV cache stores, why it saves recomputing attention over the whole history, and how to calculate its size per token from layers, KV heads, head size and data type, including the savings from grouped-query attention.
    • Calculate KV-cache bytes per token and per request for two open models from their config.json files, in a short Python function
    • Show how context length and concurrency together use up GPU memory, and find the point where the cache rather than the weights becomes the limit
    • Compare the KV footprint of multi-head and grouped-query attention models and explain what that means for how many users fit on one GPU
  4. Level 4: Latency Measures: TTFT, ITL and End-to-End
    You define time to first token, inter-token latency (also called time per output token) and end-to-end latency precisely, link each one to prefill or decode, and learn why you report percentiles rather than averages.
    • Measure TTFT, ITL and end-to-end latency from a streaming OpenAI-compatible response using timestamps in Python
    • Report p50, p90 and p99 for each measure and explain why the tail is what users notice
    • Say which measure matters most for a chat UI, a voice agent and a batch summarisation job
  5. Level 5: Throughput, Concurrency and the Trade-off Curve
    You learn how output tokens per second, requests per second and concurrency relate (Little's law in plain numbers), and why pushing up throughput by batching more requests eventually makes each user's latency worse.
    • Sweep concurrency against a local server and plot total throughput against per-request ITL to find the knee of the curve
    • Use Little's law to work out the concurrency you need for a target request rate and latency
    • Explain the difference between system throughput and per-user tokens per second, and why vendor benchmarks often blur the two
  6. Level 6: SLOs and Goodput
    You turn latency targets into service-level objectives and measure goodput (the rate of requests that actually meet every SLO), which is the number that should decide capacity and cost.
    • Write SLOs for TTFT and ITL for a realistic product and justify the thresholds
    • Calculate goodput from load-test results and show how it can fall while raw throughput still rises
    • Pick the operating point on a throughput and latency curve that maximises goodput
  7. Level 7: Build Your Load-Test Harness in Python
    You write a reusable async Python load tester that streams from any OpenAI-compatible endpoint, records per-token timings, controls concurrency or arrival rate, and writes results you can compare across runs for the rest of the course.
    • Build an asyncio and httpx (or openai SDK) client that sends requests at a fixed concurrency or a Poisson arrival rate and logs TTFT, ITL and token counts
    • Count tokens on the server side from usage fields instead of guessing from client chunks, and handle errors and timeouts
    • Write JSON results plus a summary table of percentiles, throughput and goodput against your SLOs
  8. Level 8: Realistic Workloads and Trustworthy Benchmarks
    You make load tests reflect production by sampling realistic prompt and output length distributions, warming up, fixing seeds and output lengths, and checking your harness against established tools such as vLLM's benchmark CLI and GuideLLM.
    • Build a workload file from real or public conversation data with matched input and output length distributions
    • Spot common benchmark mistakes such as no warm-up, unlimited output length, cache-friendly repeated prompts and client-side bottlenecks
    • Reproduce one run with your harness and with a standard benchmark tool and account for any difference between them
  9. Level 9: The Inference Engine Landscape Today
    You survey the engines that are current today (vLLM, SGLang, TensorRT-LLM and llama.cpp), see where each one fits, and learn that Hugging Face TGI is now in maintenance mode, with its own README pointing new work to vLLM and SGLang.
    • Describe what vLLM, SGLang, TensorRT-LLM and llama.cpp are each built for: hardware, model formats and deployment style
    • Explain what TGI's maintenance-mode status means for existing deployments and for new projects
    • Draw up a shortlist of engines for a given set of constraints: GPU vendor, model, scale and whether there is a team to operate it
  10. Level 10: Your First Production-Style Server with vLLM
    You serve an open model behind vLLM's OpenAI-compatible API on a rented GPU and learn the settings that matter most: context length cap, GPU memory fraction, maximum concurrent sequences, data type and the chat template.
    • Launch vLLM serve with explicit max-model-len, gpu-memory-utilization and max-num-seqs settings and call it with the openai Python SDK
    • Read the startup logs to find how much KV-cache memory and how many concurrent tokens the engine has allocated
    • Run your load-test harness against the server and record a baseline for TTFT, ITL, throughput and goodput
  11. Level 11: Continuous Batching
    You learn why static batching wastes the GPU on padding and on waiting for the longest reply, and how iteration-level (continuous) batching adds and removes requests at every decode step to raise throughput.
    • Simulate static and continuous batching in a short Python script and compare GPU utilisation and latency on mixed output lengths
    • Show on your vLLM server how max-num-seqs and max-num-batched-tokens change throughput and tail latency
    • Explain why continuous batching makes per-request latency depend on other users' traffic
  12. Level 12: PagedAttention and KV-Cache Memory Management
    You see how PagedAttention stores the KV cache in fixed-size blocks, like virtual-memory pages, to remove fragmentation, and what the engine does when blocks run out: queueing, preemption and recomputation.
    • Explain block allocation, fragmentation and why paging lets more requests fit in the same GPU memory
    • Push your server into KV-cache pressure and spot preemptions and rising queue time in its metrics endpoint
    • Tune context length and memory settings to trade the longest supported prompt against concurrency
  13. Level 13: Chunked Prefill and Scheduler Tuning
    You learn how long prompts arriving mid-stream stall other users' decoding, and how chunked prefill and the token budget per step let the scheduler mix prefill and decode to protect inter-token latency.
    • Reproduce an ITL spike by injecting long-prompt requests into a steady chat workload
    • Turn on and size chunked prefill (the max-num-batched-tokens budget) and measure the shift between TTFT and ITL
    • Choose scheduler settings for a latency-sensitive workload and for a throughput-oriented one, and justify each
  14. Level 14: Prefix Caching Inside the Engine
    You learn how engines reuse KV blocks for shared prompt prefixes, through vLLM's automatic prefix caching (hash-based) and SGLang's RadixAttention (tree-based), and when that cuts prefill cost.
    • Turn on prefix caching and measure the TTFT and throughput gain on a workload with a long shared system prompt
    • Explain how blocks are matched and evicted, and why a single changed early token wipes out the cache benefit
    • Read prefix-cache hit-rate metrics from the server and relate them to measured TTFT
  15. Level 15: Designing Prompts and Traffic for Cache Hits
    You put caching to work: order prompts so stable content comes first, compare hosted API prompt caching (its pricing and rules as documented today) with self-hosted prefix caching, and see how routing affects hit rates across replicas.
    • Restructure an agent or RAG prompt so static content comes first, then measure the change in cache hit rate
    • Estimate the savings from a provider's documented prompt-caching prices for a real traffic pattern
    • Explain why round-robin load balancing across replicas lowers cache hits, and what cache-aware routing changes
  16. Level 16: Speculative Decoding
    You learn how a cheap drafter (n-gram lookup, a small draft model or an EAGLE-style head) proposes tokens that the target model checks in one pass, why the output distribution stays the same, and why speedups depend on acceptance rate and load.
    • Turn on n-gram and EAGLE-3 speculative decoding in vLLM for a supported model pair and measure the acceptance rate and ITL
    • Show that speculation helps most at low concurrency and can hurt throughput when the GPU is already saturated
    • Decide, based on measurements, whether to keep speculation on for a given workload and SLO
  17. Level 17: Structured Output at the Server
    You learn how grammar-constrained decoding (for example with XGrammar in current engines) masks invalid tokens so outputs always match a JSON schema or regex, and what that costs in latency.
    • Request JSON-schema-constrained output from your server through the OpenAI-compatible response_format and check that it is always valid
    • Measure the overhead of constrained decoding against unconstrained decoding with a prompt that only asks for JSON
    • Explain the pitfalls: schema compile time, constraints that hurt answer quality, and how constraints interact with speculation
  18. Level 18: Serving Many LoRA Adapters
    You serve one base model with many LoRA adapters on the same GPU, loading and swapping them dynamically and batching requests for different adapters together, and learn how adapter count and rank affect memory and latency.
    • Launch vLLM with LoRA turned on, register several adapters and route requests to each one by model name
    • Load-test a mix of adapters and measure the cost of max-loras, max-lora-rank and adapter swapping
    • Decide when multi-LoRA serving beats running separate merged models
  19. Level 19: Choosing an Engine With Your Own Benchmark
    You run a fair head-to-head of vLLM and SGLang (with llama.cpp as a single-user reference) on the same model, GPU and workload, and pick an engine on goodput, features and operating cost rather than headline numbers.
    • Deploy the same model on two engines with matched settings and run your workload file against both
    • Compare goodput at your SLOs, cache behaviour and the features you need, and note where results depend on the workload
    • Write a one-page engine decision record you could defend in a design review
  20. Level 20: Why Quantisation Speeds Serving: Bytes and FP8
    You learn that fewer bytes per weight and per KV entry speed up memory-bound decode and free memory for more users, and you serve an FP8 model to see the gains and the hardware it needs.
    • Work out the weight memory and decode speed ceiling of a model at BF16, FP8 and INT4 from its parameter count and the GPU's memory bandwidth
    • Serve the same model in BF16 and FP8 (weights, plus an FP8 KV cache where supported) and compare throughput, memory and concurrency
    • Name which GPU generations run FP8 natively and what happens on older hardware
  21. Level 21: A Quality Gate for Every Optimisation
    Before you quantise anything, you build a repeatable quality check from perplexity, task evals and a regression set of your own prompts, and run it against the full-precision baseline, because perplexity alone can hide the regressions users notice.
    • Run a task-level eval and a perplexity check against a BF16 model served behind an OpenAI-compatible endpoint
    • Build a small golden set of real prompts with pass/fail checks that runs in minutes
    • Record baseline scores with confidence intervals so later changes can be judged against noise
  22. Level 22: FP8 Serving: Weights and Activations
    You quantise a model to FP8 (W8A8), check which GPUs actually speed it up, and measure what it does to memory, throughput and quality.
    • Produce an FP8 checkpoint with llm-compressor (dynamic per-token or block-wise) and serve it in vLLM
    • Explain why FP8 speeds up compute on Hopper-class and newer GPUs but on older cards mainly saves memory
    • Compare FP8 and BF16 on your quality gate and your load test, and report the trade-off
  23. Level 23: INT4 Weight-Only: AWQ and GPTQ
    You use calibration-based 4-bit weight quantisation with AWQ and GPTQ, see why weight-only INT4 helps memory-bound decode most, and learn how calibration data shapes quality.
    • Quantise one model with AWQ and with GPTQ using a calibration set that matches your traffic
    • Explain why INT4 weight-only speeds up small-batch decode but can lose to FP8 at high batch sizes
    • Find where 4-bit quality drops on your regression set, not just in average scores
  24. Level 24: GGUF, k-quants and 4-bit Float Formats
    You map llama.cpp's GGUF quant levels and the newer microscaled 4-bit floats (MXFP4, NVFP4) to the hardware that runs them, and choose a format by target device.
    • Convert a model to several GGUF quant levels and benchmark them with llama.cpp's server
    • Explain block-wise scaling and why NVFP4 is tied to Blackwell-class GPUs
    • Pick a quantisation format for a given engine and GPU, and check that the engine really supports it
  25. Level 25: Quantising the KV Cache
    You quantise the KV cache separately from the weights, trading some accuracy on long contexts for more concurrent sequences, and measure where it hurts.
    • Turn on an FP8 KV cache in your engine and measure how much the maximum concurrency grows
    • Test long-context retrieval before and after, to find quality loss that short prompts miss
    • Decide when KV-cache quantisation is worth it based on your traffic's context lengths
  26. Level 26: GPU Memory Maths: Weights, KV Cache, Headroom
    You work out a model's memory needs from parameter count, precision, layers, KV heads and context length, then check your sums against what the engine reports.
    • Write a Python calculator for weight memory and per-token KV-cache memory, including grouped-query attention
    • Predict the maximum concurrent sequences on a given GPU and compare with vLLM's startup logs
    • Allow for activations, CUDA graphs and fragmentation when choosing a GPU size
  27. Level 27: Tensor Parallelism Across GPUs
    You split a model's layers across GPUs with tensor parallelism, see why it needs a fast interconnect, and measure when two GPUs beat one.
    • Serve a model with tensor parallelism of 2 and compare TTFT, inter-token latency and throughput against one GPU
    • Explain the all-reduce traffic per layer and why NVLink and PCIe give very different results
    • Decide between tensor parallelism and running independent replicas for a given workload
  28. Level 28: Pipeline and Expert Parallelism for Big and MoE
    You learn how pipeline parallelism splits a model by layer stages and how expert parallelism spreads mixture-of-experts layers, and what each costs in bubbles and communication.
    • Explain pipeline bubbles and why pipeline parallelism suits slow links better than tensor parallelism
    • Explain how expert parallelism routes tokens to experts and why load imbalance matters
    • Choose a parallelism layout for a dense model and for a mixture-of-experts model on a fixed GPU budget
  29. Level 29: Multi-Node Serving
    You learn what changes when one model spans several machines: the network fabric, NCCL, orchestration with Ray or similar, and how failures play out.
    • Describe a working two-node layout (tensor parallelism within a node, pipeline parallelism across nodes) and the network it needs
    • Find NCCL and network bottlenecks with the engine's logs and simple bandwidth tests
    • Judge when multi-node serving is truly needed and when a smaller or quantised model removes the need
  30. Level 30: Running an Inference Engine on Kubernetes
    You package an engine for Kubernetes, with GPU scheduling, model storage, probes and graceful shutdown, so pods start cleanly and drain without dropping requests.
    • Deploy vLLM on a GPU node with resource requests, a shared-memory volume and a cached model volume
    • Write readiness and liveness probes that wait for model load and spot a stuck engine
    • Configure graceful draining so rolling updates finish in-flight streams
  31. Level 31: Inference-Aware Gateways and Routing
    You see why round-robin load balancing wastes GPU caches, and use the Kubernetes Gateway API Inference Extension and stacks such as llm-d to route by load, queue and prefix-cache hits.
    • Explain InferencePool and the endpoint picker, and how they differ from a plain Kubernetes Service
    • Compare round-robin with prefix-cache-aware routing on a shared-system-prompt workload
    • Measure cache hit rate and TTFT gains, and note where the routing adds its own overhead
  32. Level 32: Managed and Serverless GPU Platforms
    You compare managed endpoints and serverless GPU platforms with running your own cluster, on control, cold starts, pricing models and lock-in.
    • Deploy the same model on a managed or serverless GPU platform and compare it with your own deployment
    • Compare per-second, per-hour and per-token pricing against your traffic pattern
    • List the engine flags, metrics and limits you lose or keep on each platform
  33. Level 33: Autoscaling on the Right Signals
    You learn why CPU and request rate are poor scaling signals for LLM servers, and scale on queue depth, KV-cache use and latency SLOs instead.
    • Expose engine metrics such as waiting requests and KV-cache usage to a scaler like KEDA or HPA
    • Tune scale-up and scale-down thresholds and cooldowns against a bursty load test
    • Show the effect on goodput and GPU-hours compared with a fixed replica count
  34. Level 34: Taming Cold Starts
    You break a replica's cold start into image pull, weight load, engine warm-up and graph capture, and shorten each stage so scaling up keeps pace with traffic.
    • Time each stage of a cold start and find the longest one
    • Apply fixes such as pre-pulled images, local or streamed weights, and cached compilation
    • Decide between scale-to-zero, warm minimum replicas and request queuing for a given SLO
  35. Level 35: Disaggregated Prefill and Decode
    You split prefill and decode onto separate workers that pass the KV cache between them, learn when this improves goodput, and see where published results are still unsettled.
    • Explain why prefill and decode interfere and how disaggregation lets each scale separately
    • Run or trace a disaggregated setup with llm-d, NVIDIA Dynamo or the engine's own connector, and measure KV transfer cost
    • Tell from your traffic's input-to-output ratio whether disaggregation is likely to pay off, and treat vendor speed-up figures with care
  36. Level 36: Routing Requests Between Models
    You build a router that sends each request to a small or a large model by task type, difficulty or user tier, and you measure the cost saved against quality lost.
    • Put a rule-based and a classifier-based router in front of two OpenAI-compatible endpoints
    • Score routing decisions on your golden set for misroutes and quality impact
    • Work out the blended cost per request at different routing splits
  37. Level 37: Cascades: Small First, Escalate When Unsure
    You build a cascade that tries a small model first and escalates to a larger one when a check fails, and learn which checks are trustworthy.
    • Build escalation on validators, schema checks or verifier scores, rather than on self-reported confidence alone
    • Measure the added latency from escalations and the overall cost against always using the large model
    • Tune the escalation threshold to hit a quality target at the lowest cost
  38. Level 38: Fallbacks, Retries and Circuit Breakers
    You make a multi-model setup resilient with timeouts, retries, failover between self-hosted and hosted providers, and circuit breakers that stop failures from cascading.
    • Set timeouts for TTFT and for the full stream rather than one total request timeout
    • Write retries with backoff that avoid retry storms and avoid repeating side effects
    • Add a circuit breaker and a provider fallback, and test them by killing a backend mid-load
  39. Level 39: Rate Limits, Quotas and Admission Control
    You protect shared GPU capacity with token-based rate limits, per-tenant quotas, priority classes and load shedding, so one noisy client cannot wreck everyone's latency.
    • Write a token-bucket limiter that counts estimated input plus output tokens, not just requests
    • Add priority classes and admission control that reject or queue work before the engine overloads
    • Show under load that high-priority traffic keeps its SLO while low-priority traffic is shed
  40. Level 40: Cost per Million Tokens: Hosted vs Self-Hosted
    You turn GPU price, measured throughput and utilisation into a cost per million input and output tokens, and compare it honestly with hosted API prices.
    • Calculate self-hosted cost per million tokens from your own load-test numbers and the hourly GPU price
    • Show how utilisation, cache hit rate and input-to-output ratio change the comparison
    • Find the traffic volume where self-hosting breaks even with a hosted API, counting staff time
  41. Level 41: Metering the Cost of Every Request
    You learn to work out what each request actually costs by counting its prompt, cached and output tokens and the GPU-seconds it used, so you can see which tenant, feature or prompt is spending the money.
    • Add a Python middleware to an OpenAI-compatible endpoint that logs prompt, cached and completion tokens, latency and model for each request, and turns them into a cost using your own per-token or per-GPU-hour rates
    • Split one load-test run's GPU bill across requests by their share of prefill and decode work, and name the five most expensive prompt shapes
    • Explain why the average cost per request hides the long tail, and report cost at p50, p95 and p99 per feature
  42. Level 42: Edge and On-Device Inference
    You learn what changes when the model runs on a laptop, phone or small edge box: memory bandwidth limits decode speed, the model must fit in shared RAM, quantised formats such as GGUF become essential, and the cost moves from your GPU bill to the user's battery.
    • Estimate on-device decode speed from model size after quantisation and the device's memory bandwidth, then check the estimate with llama.cpp's benchmark tool
    • Compare the same quantised model on a rented GPU and on a CPU or Apple-silicon machine for TTFT, tokens per second and quality on a small fixed eval set
    • Decide which requests in an app should run on the device and which in the cloud, based on privacy, latency, model size and the quality you measured
  43. Level 43: Monitoring Engine Metrics and Latency SLOs
    You learn to scrape the Prometheus metrics that serving engines expose and build dashboards and alerts for the signals that predict trouble: TTFT and inter-token latency percentiles, queue depth, KV-cache use, prefix-cache hit rate and preemptions.
    • Scrape a vLLM or SGLang /metrics endpoint with Prometheus and build a Grafana dashboard showing TTFT and ITL percentiles, running and waiting requests, and KV-cache use
    • Write SLO burn-rate alerts based on goodput rather than raw latency, and trigger them on purpose with your load test
    • Read a dashboard during an overload test and say whether the bottleneck is prefill, decode, KV-cache space or the queue
  44. Level 44: GPU Health and Fleet Monitoring
    You learn to watch the hardware under the engine, including GPU utilisation that misleads, memory errors, thermal and power throttling, XID errors and failing nodes, so a sick GPU is drained before users notice.
    • Run NVIDIA's DCGM exporter next to your engine and chart SM activity, memory bandwidth, power, temperature and error counters alongside request latency
    • Explain why nvidia-smi 'GPU utilisation' near 100% does not mean the GPU is saturated, and use better signals to judge spare capacity
    • Write a health check and runbook that takes a node out of rotation when it throttles or reports errors, and test it by simulating a degraded node
  45. Level 45: Watching Quality in Production
    You learn to catch quality regressions that latency dashboards miss, from changes to quantisation, the engine, the router or speculative decoding, using fixed eval sets, shadow traffic, canaries and request tracing.
    • Build a regression gate in Python that scores a candidate deployment against the current one on a fixed eval set and fails when the difference exceeds a threshold you can defend
    • Send mirrored shadow traffic to a canary deployment and compare output length, structured-output validity, refusal rate and judge scores with the baseline
    • Trace one request through router, cache and engine with OpenTelemetry spans so a quality or latency complaint can be traced to the component responsible
  46. Level 46: Final Project I: Baseline Deployment and Evidence
    You start the final project by serving an open model behind an OpenAI-compatible API on one or two rented GPUs and recording a reproducible baseline of latency, goodput, cost per request and quality.
    • Deploy an open-weight model with the engine of your choice behind an OpenAI-compatible endpoint, with metrics, per-request cost metering and tracing turned on
    • Run the course load test at fixed traffic levels and record TTFT, ITL, goodput against your SLO, and cost per request and per million tokens
    • Freeze a quality baseline on a task-specific eval set, with confidence intervals, that later changes must match
  47. Level 47: Final Project II: Halving the Cost per Request
    You cut the baseline's cost per request by at least half by applying and measuring the course's levers one at a time, from quantisation, prefix caching and speculative decoding to batch tuning, right-sized GPUs and routing to a smaller model.
    • Rank candidate levers by expected saving and risk using what you measured in the baseline, then apply them one at a time and record the cost and latency change each brings
    • Re-run the same load test after each change and show cost per request at or below 50% of baseline while goodput still meets the SLO
    • Drop any lever whose saving disappears under realistic traffic, and explain why it did
  48. Level 48: Final Challenge: Prove Quality Held Exam
    You finish the course by showing with statistics that the cheaper deployment kept quality, and by defending every design choice from generation basics through engines, memory, scaling, routing and economics in a review write-up.
    • Compare the optimised deployment with the frozen baseline on the eval set and on shadow traffic, and report the quality difference with confidence intervals and a clear pass or fail
    • Write a one-page deployment review that links each saving to the mechanism behind it (KV cache, batching, caching, quantisation, parallelism, routing) and states what is still uncertain
    • Set up the monitoring, alerts and regression gate that would keep the cost saving and the quality level in place after go-live

Access

Levels 1 and 2 are free to read, no account needed. Levels 3 and 4 are free with a free account, and so are 20 answers from the AI tutor. Every level, the podcast edition and the AI tutor come with All Access at £4.99/month or any Creator plan — see pricing.

Read lesson 1 free →

More like this