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

Deadlines, disconnects and cancellation propagationAuthentication, quotas and request validationIdempotency and retry boundariesMultimodal media validation and encoder scheduling
1

Read

In this order, only the parts listed

0 of 5 done

  1. 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/completions with Depends(require_auth) and await rate_limit(tenant), JWT bearer or API-key lookup, HPA at 70% CPU with 3 to 15 replicas, Nginx limit-rps: 50 annotations

  2. Project 103 auth, rate-limit and streaming middlewareAI Infrastructure Engineer Learning - Project 103 LLM Deployment

    src/api/middleware.py: RateLimitMiddleware token bucket (requests_per_minute=60, burst_size=10, 429 with Retry-After: 60), APIKeyAuthMiddleware with public endpoints /health, /docs, /openapi.json; src/api/streaming.py: safe_stream_wrapper cancellation and error events, stream_with_heartbeat

  3. vLLM request identity and priority headersvLLM Online Serving, Architecture and Production Metrics

    Extra HTTP Headers: --enable-request-id-headers with caller x-request-id, X-Vllm-Priority overriding body priority; Extra Parameters: request_id default random_uuid and stable session_id

  4. 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-id and the x-ratelimit-* headers; Supplying your own request ID with X-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.

  5. 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-domains with VLLM_MEDIA_URL_ALLOW_REDIRECTS=0, fetch timeouts 5s image / 30s video / 10s audio, --limit-mm-per-prompt, --allowed-local-media-path, and media uuid for cache identity

    Read the Online Serving parts and the security tip only. Skip decoder-backend tuning; encoder scheduling returns in the disaggregation section.

2

Focus on

  • vLLM's --api-key covers only /v1, /v2 and /inference (plus /cohere in 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-only or development-mode servers expose /abort_requests. A gateway that times out its client but keeps the upstream connection open leaks the KV slot until max_tokens.
  • Retries are safe only inside an idempotency boundary: caller-supplied x-request-id mapped to one engine request_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-key as full auth. It leaves /health, /metrics and /invocations open; 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_id the 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.
3

Try it yourself

Closed-book, before checking anything

From a blank file, implement a token-bucket limiter keyed by API key (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.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.A gateway times out its client after 10s, but the engine keeps decoding to max_tokens=512. What leaked, and what stops it?Answer

    The 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}/cancel for a background Response).

  2. 2.Two identical chat requests arrive with the same caller x-request-id. How many engine executions should happen?Answer

    One. 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. 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. 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.

5

Practice

  • Project 103: stubbed API, middleware and streaming tests

    TestMiddleware::test_rate_limiting and test_authentication, TestGenerateEndpoint::test_generate_streaming; implement src/api/middleware.py and src/api/streaming.py per their comments until all seven tests pass

    The bodies are pass stubs 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

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.