Unit 2 of 12 · about 5 hours · explain, implement
Deadlines, cancellation, authentication, quotas, validation and idempotency
The engine optimizes tokens, not trust. Auth, quotas, validation, deadlines and idempotency live in the gateway the learner builds around it, and a missing one becomes the incident.
You'll be able to
- Put a deadline and cancellation path on a streaming endpoint and prove a disconnected client frees its engine slot.
- Enforce API-key auth, per-key quotas and request validation in front of an engine that authenticates almost nothing by itself.
- Draw the retry boundary with request IDs so a retried call never executes twice, and validate multimodal media before it reaches the encoder.
Covers
Read
In this order, only the parts listed
0 of 5 done
- Enterprise public API: auth, rate limiting and ingressHands-On LLM Serving and Optimization - Chapters 3 and 4, serving system design
Chapter 4, Implementing Public API (printed pp. 127-128):
/v1/chat/completionswithDepends(require_auth)andawait rate_limit(tenant), JWT bearer or API-key lookup, HPA at 70% CPU with 3 to 15 replicas, Nginxlimit-rps: 50annotations - Project 103 auth, rate-limit and streaming middlewareAI Infrastructure Engineer Learning - Project 103 LLM Deployment
src/api/middleware.py:RateLimitMiddlewaretoken bucket (requests_per_minute=60,burst_size=10, 429 withRetry-After: 60),APIKeyAuthMiddlewarewith public endpoints/health,/docs,/openapi.json;src/api/streaming.py:safe_stream_wrappercancellation and error events,stream_with_heartbeat - vLLM request identity and priority headersvLLM Online Serving, Architecture and Production Metrics
Extra HTTP Headers:
--enable-request-id-headerswith callerx-request-id,X-Vllm-Priorityoverriding bodypriority; Extra Parameters:request_iddefaultrandom_uuidand stablesession_id - OpenAI auth, rate limits and client request IDsOpenAI API Reference - streaming, auth, rate limits and request IDs
API Overview: Authentication with bearer credentials and server-side key handling; Debugging requests:
x-request-idand thex-ratelimit-*headers; Supplying your own request ID withX-Client-Request-Id(ASCII, at most 512 characters, else 400) (page read 2026-10-14)Use the header and ID contract only. Quota numbers and hosted rate limits do not transfer to a self-hosted engine.
- vLLM multimodal fetch policy and cache identityvLLM Multimodal Inputs - media validation, fetch policy and cache identity
Online Serving for image, video and audio inputs:
--allowed-media-domainswithVLLM_MEDIA_URL_ALLOW_REDIRECTS=0, fetch timeouts 5s image / 30s video / 10s audio,--limit-mm-per-prompt,--allowed-local-media-path, and mediauuidfor cache identityRead the Online Serving parts and the security tip only. Skip decoder-backend tuning; encoder scheduling returns in the disaggregation section.
Focus on
- vLLM's
--api-keycovers only/v1,/v2and/inference(plus/coherein the v0.31.0 source). Quotas, validation, deadlines and idempotency are gateway work: check them before the request enters the scheduler. - A deadline has three legs: client timeout, gateway timeout and engine cancellation. vLLM aborts a chat or completion request when its HTTP connection closes; background Responses use
/v1/responses/{response_id}/cancel, and--tokens-onlyor development-mode servers expose/abort_requests. A gateway that times out its client but keeps the upstream connection open leaks the KV slot untilmax_tokens. - Retries are safe only inside an idempotency boundary: caller-supplied
x-request-idmapped to one enginerequest_id, with a dedupe table that returns the first result. Retry without that key executes twice. - Media is untrusted input: restrict fetch domains, cap count and size per prompt with
--limit-mm-per-prompt, enforce fetch timeouts, and give cacheable media stable UUIDs so identical bytes share encoder work.
Common mistakes · 3
- Trusting
--api-keyas full auth. It leaves/health,/metricsand/invocationsopen; the security note in the server docs says to deploy behind a reverse proxy. - Retrying a timed-out stream as a new request. The first attempt may still be decoding; without a shared
request_idthe retry doubles cost and can double side effects. - Fetching arbitrary media URLs server-side. A prompt can point the fetcher at internal hosts; allow-list domains and disable redirect following.
Try it yourself
Closed-book, before checking anything
requests_per_minute=60, burst_size=10) that returns 429 with Retry-After: 60 and X-RateLimit-Remaining: 0. Drain the bucket with 10 quick calls from one key, then show the 11th call rejected without reaching the engine.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.A gateway times out its client after 10s, but the engine keeps decoding to
max_tokens=512. What leaked, and what stops it?AnswerThe KV-cache and scheduler slots stay held until generation ends. vLLM aborts a request when its HTTP connection closes, so the gateway must close or cancel its upstream call on every timeout (
/v1/responses/{response_id}/cancelfor a background Response).2.Two identical chat requests arrive with the same caller
x-request-id. How many engine executions should happen?AnswerOne. The gateway maps the caller key to a single engine
request_id, returns the stored result for the duplicate, and only a new key starts new work.3.Why must media fetch domains be allow-listed even when prompts are authenticated?Answer
An authenticated prompt can still embed an internal URL, turning the server fetcher into a proxy into the datacenter network. Allow-listing plus no-redirect policy contains that SSRF path.
4.A video request stalls for 40s before the first token on a healthy GPU. Which serving knob do you check first?Answer
The media fetch path: a remote video fetch can run up to its 30s default timeout before prefill starts, so a slow media host looks like slow inference. Check fetch timing before blaming prefill.
Practice
- Project 103: stubbed API, middleware and streaming tests
TestMiddleware::test_rate_limitingandtest_authentication,TestGenerateEndpoint::test_generate_streaming; implementsrc/api/middleware.pyandsrc/api/streaming.pyper their comments until all seven tests passThe bodies are
passstubs with the contract in comments. Implement token-bucket limiting, key auth with public/health, and SSE with heartbeat before running the suite.
You're done when
An over-limit key gets 429 without engine work, a cancelled stream frees its slot, and a duplicate x-request-id returns one stored result.
Only when you can do this without notes.
Leads to
Notes
Resources · 5 for this unit, 8 more in the section
- vLLM Online Serving, Architecture and Production MetricsvLLM Project · primary
Trace the API server, engine core, scheduler, KV manager and model runner, then map documented metrics to your SLIs. The link is pinned to v0.31.0; add the auth, tenant, quality and rollout controls the engine leaves to you.
- Hands-On LLM Serving and Optimization - Chapters 3 and 4, serving system designChi Wang and Peiheng Hu (O'Reilly) · required
Read Chapter 3 (an online service from scratch, batching with streaming, multi-model trade-offs) and the enterprise-architecture part of Chapter 4. Convert the designs into explicit request, model-lifecycle and failure state machines.
- AI Infrastructure Engineer Learning - Project 103 LLM DeploymentAI Infra Curriculum · support
Use its Docker, API, monitoring, Kubernetes and cost files as scaffolding only. Check its resource assumptions against your own model and GPU, and rerun any benchmark before reusing a result.
- OpenAI API Reference - streaming, auth, rate limits and request IDsOpenAI · reference
Read the chat streaming event shape with the
[DONE]terminator, bearer auth, rate-limit headers, andx-request-idwith caller-suppliedX-Client-Request-Id. vLLM is the implementation under test; use this only for the contract it claims compatibility with. - vLLM Multimodal Inputs - media validation, fetch policy and cache identityvLLM Project · reference
Read Online Serving for image, video and audio inputs:
--allowed-media-domains, fetch timeouts,--limit-mm-per-prompt, local-media path restriction, and media UUIDs for cache identity. The link is pinned to v0.31.0.
Also in this section
- vLLM Production MetricsvLLM Project · required
Define every selected queue, cache, phase and request metric, check histogram buckets and measure exporter overhead. Add model version, cancellation, rejection, quality sample and tenant-safe trace fields in the surrounding service.
- Machine Learning Systems, Volume 2 - Inference at Scale and Serving Fault ToleranceHarvard (Vijay Janapa Reddi) · required
Read "Load Balancing and Request Routing", "Multi-Tenancy and Isolation" and "Autoscaling and Global Infrastructure" in Inference at Scale, then "Serving Fault Tolerance" and "Graceful Degradation" in the Fault Tolerance chapter.
- Inference Engineering - Chapter 7, ProductionPhilip Kiely (Baseten Books) · support
Read Chapter 7 for containers, autoscaling, cold starts, routing and queueing, zero-downtime deployment, cost estimation and client-side streaming. Skip the vendor section at its end.
- Gateway API Inference ExtensionKubernetes SIG Network · required
Study model-aware routing, endpoint selection and operational integration. Use it for architecture and an optional local deployment only after the service passes lifecycle and failure tests without Kubernetes.
- SGLang documentation - Production MetricsSGLang Project · support
Compare its metric names and phase boundaries with vLLM's, so your dashboards do not depend on one engine's vocabulary.
- AI Systems Performance Engineering - Production Inference LabsChris Fregly · required
Use Chapter 16 monitoring, cache health, capacity planning and load-test utilities, then Chapter 17 routing only if distributed. Add process death, overload and bad-version cases that the performance pairs do not cover.
- 100 Days of LLM Inference - Days 22 to 26Elizabeth Thomas · support
Use the container, autoscaling, routing, capacity and zero-downtime notebooks as small operational simulations. Replace calendar order and fixed scale targets with the stage checkpoint and your hardware limits.
- LLM Inference Systems Laboratory - Operations and FailureRoadmap-Final · support
Complete production gateway, isolation, telemetry, canary, drain, rollback and fault campaigns. Store first-cause timelines and revise runbooks from observed blind spots.