11C.1 Deploying LLM Services
Everything so far in this module has been about what happens inside one request: how it is traced, measured, cached, optimised, routed, and made reliable. This lesson is about where that code lives: the production FastAPI service that ties it together, the container and configuration around it, how it scales when every request holds a connection open for seconds to minutes, how it ships new versions without dropping streams, and which deployment target fits an LLM workload at all. The running project is llm_service, the FastAPI app built across this module: by the end you will have its complete application skeleton, a production Dockerfile, a compose file for local development, an nginx snippet for streaming, and a reference deploy workflow.
What you'll learn
- What is genuinely different about deploying an LLM service compared with a CRUD API: long-lived requests, streaming bodies, token-driven bursty load, expensive downstream calls, big payloads, secrets for provider keys, and non-deterministic behaviour
- How to choose a deployment target — containers on a PaaS, Kubernetes, serverless functions, VMs, edge — with a decision table, and the timeout, concurrency and streaming limits that decide whether each one works
- A complete production FastAPI service: app factory,
pydantic-settingsconfiguration, dependency-injected LLM client with lifespan management, request validation, auth boundary, per-tenant rate limits, a streaming endpoint with disconnect handling, background jobs with a status API, structured logging with request IDs, health and readiness endpoints, graceful shutdown, error mapping to HTTP, and versioned routes - How to run it: uvicorn workers and flags, gunicorn, connection pools, and the SSE-through-proxies problem (nginx, ALB, Cloudflare) with keep-alives and timeouts
- Containerisation done properly: a multi-stage
uvDockerfile, non-root user, pinned base image,.dockerignore, secrets at runtime not build time, and acompose.yamlfor local development - Configuration and secrets in production: 12-factor config, secret managers, key rotation without downtime, per-environment keys, prompts and model names as configuration, feature flags
- Scaling an I/O-bound, stream-heavy service: statelessness, workers versus processes, autoscaling on concurrency rather than CPU, provider connection limits, the queue-plus-worker pattern for slow jobs, backpressure and load shedding, cold starts, multi-region and residency, and cost controls on autoscaling
- Release strategies for a service with in-flight streams: rolling updates with draining, blue/green, canaries, index migrations, flag-gated prompt and model changes, rollback, and environment parity
- Infrastructure as code at awareness level, managed AI platforms (Bedrock, Vertex AI, Azure AI Foundry), private networking and egress, and where GPU deployment fits
- Frontend integration in brief: streaming to browsers, auth boundaries, CORS, and per-user limits
What you don't need
- A cloud account or any deployment to actually run. Every artefact here is reference code and configuration, labelled as unrun where it would need infrastructure. The Python parts that can run locally — the app with a fake client, the settings, the error mapping, the job layer — are written to be run.
- Prior deployment experience. If containers, reverse proxies or CI pipelines are new, the callouts explain them; experienced readers can skip ahead.
- Provider API keys for the core lesson. The service is tested against an injected fake client, so every behaviour in Parts 2 and 5 is exercisable without spending anything. Hosted-provider details link back to earlier lessons.
- Module 12's security depth. Authentication, secret handling and egress are covered here only as far as deployment requires; the security treatment is Module 12.
Setup
This lesson's samples live in the module's running project, llm_service, a Python package plus deployment files. If you haven't created the project yet:
uv init llm-service --bare --python 3.13 && cd llm-service
uv add "fastapi[standard]" "uvicorn[standard]" pydantic pydantic-settings httpx python-dotenv
# or: pip install "fastapi[standard]" "uvicorn[standard]" pydantic pydantic-settings httpx python-dotenvThe samples were written and checked against fastapi 0.162.0, uvicorn 0.54.0, pydantic 2.14.3, pydantic-settings 2.16.2 and httpx 0.28.1 as of November 2026. A plain install gives you the newest release of each, and uv.lock records exactly what resolved, so commit it. FastAPI, uvicorn and Pydantic move quickly; if a newer release changes a default (for example uvicorn's worker or proxy-header options) or deprecates an import, the project's release notes are the authority.
The .env file holds provider keys exactly as in lesson 03.1 — never commit it:
# .env (never commit this file)
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=... # optional
OPENROUTER_API_KEY=... # optional gateway
# This service's OWN bearer-token map (JSON): token -> tenant id, for local dev.
# Without it every request 401s. Production injects the real value from a
# secret manager (Part 4) — never commit a real token map.
LLM_SERVICE_API_KEYS_JSON='{"dev-token":"dev-tenant"}'The service calls providers through the provider_agnostic package built in lesson 03.11. That package is not self-contained: it borrows six top-level files (five modules and a YAML price table) from lessons 03.7 and 03.8 (cost_calc.py, prices.py, prices.yaml, llm_errors.py, retry_after.py, check_response.py), and importing provider_agnostic pulls in the three provider SDKs. Give llm-service access to it one of two ways:
- Install the packaged distribution (if you did 03.11's "Packaging it" step): in the
agnostic-clientproject runuv build, then hereuv add --editable ../agnostic-client(oruv add ../agnostic-client/dist/agnostic_client-0.1.0-py3-none-any.whl). The wheel already depends onopenai,anthropic,google-genai,pydantic,pyyamlandpython-dotenv, and ships the borrowed modules inside it. - Copy the sources: copy
provider_agnostic/and the six borrowed files above into this project root — they are top-level imports (from prices import PriceTable,import cost_calc), not package members. Then add the SDKs the adapters import:
uv add openai anthropic google-genai pyyaml
uv add --dev pytest # the test suite in 2.16For pytest to import llm_service and provider_agnostic from tests/, add this to pyproject.toml:
[tool.pytest.ini_options]
pythonpath = ["."]Everything that needs a real model is marked; the app itself runs against a fake client with no keys.
What you must be able to do after this lesson#
- Name three ways an LLM request differs from a CRUD request and what each changes in deployment
- Build a FastAPI service with an app factory, pydantic-settings config and separate /healthz and /readyz
- Handle both SSE error boundaries and keep streams alive through proxy timeouts
- Write a multi-stage uv Dockerfile with a non-root user and runtime secrets, not baked-in ones
- Choose autoscaling signals for an I/O-bound async service instead of CPU
- Choose between rolling, blue/green and canary releases for in-flight streams
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Why can't we just put the LLM call in a Lambda function?" | Part 1: deployment targets |
| "The stream dies after 60 seconds in production." | 2.15 SSE through proxies |
"Set --workers 4 and we're done." |
2.13 Running it |
| "Autoscaling on CPU never triggers — requests are just waiting." | 5.3 Autoscaling signals |
| "The deploy killed every open stream mid-answer." | 6.2 Rolling updates and draining |
| "Don't put the API key in the Dockerfile." | 3.2 Build-time vs runtime secrets |
| "Why is there a queue for a chat endpoint?" | 5.5 Queue plus worker |
| "502s during the rollout, then it recovered." | 6.3 Blue/green and canary |
| "The container uses too much memory at idle." | 5.7 Cold starts and warm-up |
| "Which platform should we pick?" | 1.4 The decision table |
Part 1: What is different about deploying LLM services#
1.1 The shape of an LLM request#
A CRUD endpoint receives a small JSON body, does a few milliseconds of database work, and returns a small JSON body. An LLM endpoint breaks almost every assumption that shape makes:
| Property | CRUD API | LLM service |
|---|---|---|
| Duration | Milliseconds to low seconds | Seconds to minutes per request, longer with reasoning models and big contexts |
| Connection lifetime | Short; safe to buffer and close | Often a stream held open for the whole generation (03.3) |
| Work profile | CPU- or I/O-bound briefly | Almost entirely waiting on a slow, expensive downstream call |
| Cost of a request | Negligible marginal cost | Real money per call: tokens × price, plus retries that bill again |
| Load shape | Steady, predictable | Bursty and token-driven: one viral feature or one tenant's batch job can 10× traffic in minutes |
| Payloads | Small JSON | Text plus images, PDFs and audio — megabytes per request |
| Determinism | Same input, same output | Same input, different output; you cannot cache your way to identical answers everywhere |
| Failure modes | 4xx/5xx, timeouts | All of those plus mid-stream errors, refusals, truncation, provider degradation, and silent quality regressions |
| Secrets | Database credentials | Provider API keys that must never reach a browser, a log, or an image layer |
| State | Usually stateless | Stateless too — but long requests make "stateless" harder: in-flight work is the state |
Two consequences dominate deployment design. First, a request is a held connection: while the model generates, your service holds a client socket, a worker slot, and provider quota. Ten thousand concurrent streams is ten thousand open sockets and ten thousand in-flight billable generations. Second, the expensive work is downstream: your server is mostly a proxy with policy — auth, limits, caching, routing, logging — so its own CPU use says almost nothing about how loaded it really is.
1.2 Why "just deploy it like any API" fails#
Each classic shortcut has an LLM-specific failure:
- Serverless functions with short timeouts. AWS Lambda's default function timeout is 3 seconds, with 900 seconds (15 minutes) as the maximum (Lambda docs); Vercel Functions default to 300 s; and while Cloudflare Workers have no hard HTTP duration limit, they cancel work when the client disconnects. Streaming on Lambda needs
RESPONSE_STREAMinvoke mode plus a custom runtime — for Python the documented shortcut is the Lambda Web Adapter. A reasoning model that thinks for 90 seconds then streams for 60 more needs a platform that both allows the duration and streams bytes through — and per 1.5, Lambda bills the full duration even after the caller hangs up. - CPU-based autoscaling. An async Python service waiting on
await client.astream(...)uses ~0% CPU. Scale-on-CPU sees an idle fleet while thousands of streams pile up. - Retry-unaware load balancers. A 502 during a deploy isn't just a failed request; if the client retries, you pay for the generation twice. Lesson 11C.3 owns the retry policy; deployment must not multiply it.
- Secrets in environment files baked into images. Provider keys in an image layer are recoverable by anyone who can pull the image. Keys belong in a secret manager injected at runtime (Part 4).
- Treating
/askas idempotent. Replaying a non-idempotent generation endpoint on retry can return a different answer and bill again; 07.11 flagged the idempotency-key pattern for exactly this reason.
1.3 The deployment targets#
There is no single right target; there is a right shape for your traffic. The table compares the five families as of November 2026. Every row links to the official page you should re-check before relying on a number — these limits change.
| Target | What it is | Request duration | Streaming (SSE) | Concurrency model | Best fit |
|---|---|---|---|---|---|
| Containers on a PaaS (Cloud Run, Amazon ECS Express Mode, Azure Container Apps, Fly.io, Render, Railway) | Your Docker image on someone else's orchestrator | Minutes to ~1 hour depending on platform | Yes on all of them, subject to platform timeouts | Per-instance concurrency limits you set; scale on concurrency or custom metrics | The default choice for a FastAPI LLM service: real containers, real sockets, generous timeouts |
| Kubernetes (EKS, GKE, AKS, self-hosted) | You run the orchestrator | Whatever you configure | Yes, if ingress and timeouts are set right | Pods × replicas; HPA on custom metrics | Teams that already run K8s and need its control (GPU nodes, service mesh, multi-region) |
| Serverless functions (AWS Lambda, Vercel Functions, Cloudflare Workers) | Ephemeral per-request compute | Seconds to ~30 min depending on plan/runtime | Possible but constrained: Lambda needs RESPONSE_STREAM mode and a custom runtime for Python; Workers have no hard HTTP duration limit but cancel work on disconnect; Vercel caps function duration |
One request per invocation; concurrency is the platform's problem | Thin proxies, webhooks, edge auth — not long-lived generation endpoints, except carefully configured Lambda/Workers |
| VMs / bare processes | A box you manage | Unlimited (your own timeouts) | Yes, trivially | Whatever you build | GPU serving (11C.6), weird compliance needs, or cost at sustained high volume |
| Edge / CDN-fronted | Workers, CDN functions | Very short | Some support WebSockets/SSE, most buffer | Geographic distribution | Static assets, auth at the edge, geo-routing — the LLM call itself still needs an origin |
The three serverless families differ enough that "serverless" alone is not a decision. As of November 2026 (re-check each platform's limits page — they move):
| Platform | Max request duration | Streaming (SSE) | Client disconnect | Auth model | Source |
|---|---|---|---|---|---|
AWS Lambda (function URLs / InvokeWithResponseStream) |
Default 3 s timeout, max 900 s (15 min); the 5,400 s ceiling applies only to async/event-source invocations on Lambda Managed Instances, not the HTTP path | Yes via RESPONSE_STREAM: managed Node.js runtimes, or a custom runtime / Lambda Web Adapter for Python |
Streamed responses are not interrupted and are billed for the full duration; function URLs do not stream inside a VPC (use InvokeWithResponseStream) |
Function-URL AuthType (NONE/AWS_IAM) or your own bearer check inside |
timeout, response streaming |
| Vercel Functions | Node/Bun/Python: 300 s default, 800 s max, 1,800 s extended beta (Pro/Enterprise); Edge runtime must begin the response within 25 s and can stream up to 300 s | Yes (SSE and WebSockets on Fluid compute) | Billed for execution time; disconnect semantics vary by runtime — verify the current docs before relying on them | Vercel Authentication / OIDC, or your own bearer check inside | functions limits, duration |
| Cloudflare Workers | No hard HTTP duration limit while the client is connected; ctx.waitUntil() extends cleanup up to 30 s after the response |
Yes — SSE works when bytes flow inside the ~100 s origin window (community-tested, not officially guaranteed; see 2.15) | Disconnect may cancel the invocation — the work can stop mid-generation | Cloudflare Access / your own bearer check inside | Workers limits |
1.4 The decision table#
| Your situation | Pick | Why |
|---|---|---|
| First production deployment, small team, steady-to-bursty HTTP traffic | Cloud Run, Amazon ECS Express Mode or Azure Container Apps | Containers you already know how to build; concurrency-based scaling; timeouts measured in tens of minutes; SSE works |
| Variable, spiky, cost-sensitive traffic with tolerance for cold starts | Fly.io (Machines with autostop/autostart) or Render/Railway | Machines stop when idle and start in ~seconds; you pay for running machines only. Cold starts of ~2 s are fine behind a warm pool or for async jobs |
| You already run Kubernetes and need GPU nodes, mesh, or multi-region control | Kubernetes | Everything is yours to configure; the ingress/timeout work in 2.15 is on you |
| The endpoint is a thin, fast proxy (auth, flag check, webhook receiver) | Lambda / Vercel / Workers | Perfect fit: short requests, huge concurrency, pay per invocation — but check the duration table above first |
| The endpoint streams a 2-minute generation to a browser | Lambda RESPONSE_STREAM + custom runtime, or a container platform |
Lambda can stream (200 MB max, billed for full duration even if the client disconnects — see 1.5); containers are simpler |
| Self-hosted open-weight model serving | VMs or GPU nodes | vLLM/Ollama servers are long-lived GPU processes, not request handlers — 11C.6 owns this |
| Regulated data that can't leave a region/account | Same cloud's container platform with private ingress, or VMs | Data residency is an architecture constraint, not a setting — see 5.8 |
flowchart TD
subgraph clients ["Clients"]
B["Browser / mobile app"]
S["Other services / jobs"]
end
subgraph edge ["Edge and ingress"]
CDN["CDN / WAF<br/>(static assets, TLS, geo-rules)"]
PROXY["Reverse proxy<br/>nginx / ALB / platform ingress"]
end
subgraph svc ["llm_service (FastAPI, N replicas)"]
API["/v1/chat, /v1/chat/stream<br/>auth · limits · routing · cache"]
JOBS["/v1/jobs<br/>background work API"]
end
subgraph async ["Async path"]
Q["Queue (Redis / SQS / Cloud Tasks)"]
W["Workers<br/>same image, different command"]
end
subgraph down ["Downstream (via provider_agnostic client)"]
HOSTED["Hosted providers<br/>OpenAI · Anthropic · Gemini · OpenRouter"]
LOCAL["Self-hosted models<br/>vLLM / Ollama (11C.6)"]
end
OBS["Observability<br/>traces · metrics · logs (11A.1, 11A.2)"]
B --> CDN --> PROXY
S --> PROXY
PROXY --> API
PROXY --> JOBS
API --> HOSTED
API --> LOCAL
API --> Q
Q --> W --> HOSTED
API -.-> OBS
W -.-> OBSThe shape to internalise: the HTTP service is a thin, stateless, I/O-bound shell; slow work that shouldn't hold a request goes through a queue to workers running the same image; observability is a side-channel that must never be on the request path's critical failure mode (telemetry fails open — 11A.1).
1.5 The failure modes that only appear at scale#
Unit tests and staging won't show you these; production traffic will:
- The 60-second cliff. nginx's
proxy_read_timeout, the AWS ALB's idle timeout (60 s default, adjustable 1–4000 s — ALB docs), and Cloudflare's ~100-second origin window all kill a stream that goes quiet. A reasoning model's "thinking" phase produces no bytes — exactly the silence these timeouts punish. - The billed orphan. AWS Lambda response streaming "are not interrupted or stopped when the invoking client connection is broken. Customers are billed for the full function duration" (Lambda docs). Your user closed the tab; the generation ran to completion and you paid for all of it.
- The timeout that lies. Cloud Run returns 504 at the request timeout "but the container might continue processing the aborted request" (Cloud Run docs). Your client saw a failure; your server kept working — and kept billing.
- The deploy massacre. Rolling a new revision kills in-flight streams mid-sentence unless the platform drains connections. Every stream killed is a partial answer and a billed generation.
- The cold-start stampede. Scale-to-zero platforms wake machines in ~2 s (Fly.io documents "about 2 seconds or more"), which is fine once — but a thundering herd of wakes on a viral morning is a queue of 2-second delays before your app even starts.
Part 2: The production FastAPI service#
2.1 The project layout#
The module's running project is one deployable unit: a Python package llm_service that earlier lessons extend file by file, plus the deployment artefacts this lesson adds.
llm-service/
├── pyproject.toml # uv-managed; lists fastapi, uvicorn, ... (resolved versions live in uv.lock)
├── .env # secrets for local dev — never committed
├── .env.example
├── .gitignore
├── .dockerignore # Part 3.3
├── Dockerfile # Part 3.1
├── compose.yaml # Part 3.2 — local dev stack
├── nginx/
│ └── llm_service.conf # Part 2.15 — SSE-safe reverse proxy snippet
├── .github/
│ └── workflows/
│ └── deploy.yml # Part 6.1 — reference deploy workflow (11C.2 owns CI detail)
├── llm_service/
│ ├── __init__.py
│ ├── settings.py # 2.2 — pydantic-settings
│ ├── schemas.py # 2.4 — API request/response models
│ ├── serialize.py # 2.3 — canonical <-> API mapping
│ ├── deps.py # 2.3, 2.5, 2.6 — client, auth, limits
│ ├── errors.py # 2.10 — LLMError → HTTP mapping
│ ├── jobs.py # 2.9 — background job API (in-process reference)
│ ├── logging.py # 2.11 — request IDs + JSON logs
│ ├── main.py # 2.7, 2.8, 2.12–2.14 — the app factory and routes
│ ├── telemetry.py pipeline.py tracekit.py demo.py trace_view.py # added in 11A.1
│ ├── metrics.py metrics_hook.py metrics_prometheus.py otel_metrics.py # added in 11A.2
│ ├── cache.py # added in 11B.3
│ ├── budget.py economics.py waste_report.py # added in 11B.1
│ ├── router.py router_eval.py # added in 11B.5
│ ├── resilience.py # added in 11C.3
│ ├── stream_fallback.py # added in 11C.3 (stdlib only; streaming fallback)
│ └── demo_router.py demo_allowlist.py demo_stream.py # demos saved beside router.py / stream_fallback.py (11B.5, 11C.3)
│ economics_demo.py hedge_demo.py quota_demo.py buildvsbuy_demo.py make_fixture.py # 11B.1 drivers
├── slo_calc.py cost_anomaly.py probe.py provider_health.py locustfile.py # 11A.2 stdlib tools
├── cache_economics.py # 11B.3 calculator (stdlib)
├── test_resilience_attacks.py # 11C.3 attack tests (unittest), run beside llm_service/
├── gpu_sizing.py breakeven.py fake_server.py bench_openai_compatible.py # 11C.6 standalone (stdlib)
├── prepare_dataset.py ftecon.py fteval.py # 13A.8 standalone (stdlib)
├── provider_agnostic/ # the 03.11 package — installed wheel or copied folder
├── cost_calc.py prices.py prices.yaml llm_errors.py retry_after.py check_response.py
│ # top-level modules provider_agnostic BORROWS (03.7/03.8) —
│ # needed only when the package is copied as sources, not
│ # wheel-installed (Setup); the Dockerfile in 3.1 covers the image.
├── main.tf # Part 7.1 — Terraform Cloud Run sketch (reference, abridged)
├── scripts/ # deploy.sh and smoke.sh, named by deploy.yml (6.1); yours to write, not shown
└── tests/
├── test_app.py # 2.16 — runs with a fake client, no keys
└── test_chaos.py # added in 11C.3 — chaos suite for resilience.pyTwo rules keep this maintainable. The app is a composition root: main.py wires together pieces that each have one job, and the LLM call always goes through the injected client so the whole service is testable with fakes (the same seam 03.10, Part 6 teaches). Deployment files live at the repo root, not inside the package, because they describe the artifact, not the code.
2.2 Settings with pydantic-settings#
Configuration comes from environment variables and .env, parsed once into a typed object. pydantic-settings (checked against 2.16.2) is installed in Setup.
# llm_service/settings.py
"""llm_service/settings.py — all runtime configuration, parsed once at startup.
Rules this file enforces:
- Secrets are NOT fields with defaults. Provider keys are read from the environment
by the SDKs themselves (OPENAI_API_KEY etc.); our own service keys arrive as one
JSON env var so they can be rotated without a code change.
- Everything a deployment might vary lives here, so dev/staging/prod differ only
in environment variables, never in code.
"""
from functools import lru_cache
from pydantic import Field, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_prefix="LLM_", extra="ignore")
# --- identity -----------------------------------------------------------------
environment: str = "dev" # dev | staging | prod — drives log level, docs
service_name: str = "llm_service"
version: str = "0.1.0"
# --- models -------------------------------------------------------------------
default_model: str = "fast" # an ALIAS from provider_agnostic/models.yaml
max_output_tokens: int = 4096 # service-wide ceiling; per-request may lower it
# --- auth (our own API, not the providers') -----------------------------------
# JSON object mapping bearer token -> tenant id: {"tok_live_abc": "acme"}
# Demo-grade: Module 12 owns real authN/Z (JWT verification, scopes, rotation).
service_api_keys_json: str = "{}"
# --- limits -------------------------------------------------------------------
rate_limit_requests_per_minute: int = 60 # per tenant, per process (see 2.6 for the multi-instance caveat)
rate_limit_max_concurrent: int = 20 # per tenant, in-flight LLM calls
max_request_bytes: int = 32_000_000 # 413 over this; schemas.py holds the real per-field limits
# --- jobs ---------------------------------------------------------------------
job_result_ttl_seconds: int = 3600 # how long GET /v1/jobs/{id} keeps a result
job_max_per_tenant: int = 10 # queued+running jobs per tenant
webhook_signing_secret: str = "" # HMAC key for job callback signatures; "" = unsigned (dev only)
# --- cors ---------------------------------------------------------------------
# Explicit origins only. "*" is never right once Authorization is involved (03.3, 11C.6).
cors_origins: list[str] = Field(default_factory=lambda: ["http://localhost:3000"])
# --- observability ------------------------------------------------------------
log_level: str = "INFO"
log_json: bool = True # JSON lines in every deployed env
cost_log_path: str = "logs/llm_cost.jsonl" # JsonlCostHook output (03.7/03.10)
@field_validator("service_api_keys_json")
@classmethod
def _keys_must_be_a_json_object(cls, v: str) -> str:
import json
try:
parsed = json.loads(v or "{}")
except json.JSONDecodeError as exc:
raise ValueError("LLM_SERVICE_API_KEYS_JSON must be a JSON object") from exc
if not isinstance(parsed, dict) or not all(isinstance(k, str) and isinstance(t, str) for k, t in parsed.items()):
raise ValueError("LLM_SERVICE_API_KEYS_JSON must map string keys to string tenant ids")
return v
@property
def service_api_keys(self) -> dict[str, str]:
import json
return json.loads(self.service_api_keys_json)
@lru_cache
def get_settings() -> Settings:
"""Parsed once per process. create_app() calls it when no settings are passed;
tests build Settings(...) themselves and hand them to create_app(settings=...)."""
return Settings()2.3 The client: built once, injected everywhere#
The LLM client is expensive to build (it owns SDK clients and connection pools, 03.1, 7.5) and must be shared, so it is created in the lifespan and stored on app.state. Dependencies hand it to routes; tests substitute a fake.
# llm_service/deps.py
"""llm_service/deps.py — FastAPI dependencies: settings, the shared LLM client,
the authenticated principal, and the per-tenant limiter."""
from __future__ import annotations
import time
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from fastapi import HTTPException, Request
from llm_service.settings import Settings
# --- the client -----------------------------------------------------------------
def build_client(settings: Settings):
"""Production wiring: the 03.11 LLMClient over the models.yaml registry.
Imported lazily so `import llm_service.main` works in tests that never
touch a provider. Prices come from prices.yaml (03.7) so `cost_usd` is a
real number, not None; hooks are the module's observability taps — 03.10's
logging and cost file now, and each 11.x lesson adds its own below.
"""
from prices import PriceTable
from provider_agnostic.client import LLMClient
from provider_agnostic.hooks import JsonlCostHook, LoggingHook
from provider_agnostic.registry import Registry
registry = Registry.load() # provider_agnostic/models.yaml
client = LLMClient(
registry,
prices=PriceTable.load(), # prices.yaml beside prices.py -> real cost_usd
hooks=[
# Order matters: a tracing hook goes FIRST so its span wraps the
# others (11A.1). Observers never break a call; fail-closed hooks
# (budgets, redaction) are a deliberate choice — see 03.11, Part 9.
LoggingHook(), # one JSON line per attempt/call (03.10)
JsonlCostHook(settings.cost_log_path), # durable per-call cost record (03.7)
# Later lessons slot their hooks in here:
# OTelHook(tracer) — 11A.1 (telemetry.py)
# ServiceMetricsHook(metrics) — 11A.2 (metrics_hook.py)
# a budget `before` hook — 11B.1 (budget.py)
],
)
return client
@asynccontextmanager
async def lifespan(app):
"""One client per process. Preflight checks every credential the default
alias's fallback chain needs BEFORE traffic arrives (03.11, LLMClient.preflight),
and aclose() returns the SDK connection pools on shutdown (2.14)."""
settings: Settings = app.state.settings
client = build_client(settings)
try:
client.preflight(settings.default_model) # raises ConfigError if a key is missing
except Exception as exc:
# A missing provider key is a deploy-time bug: fail fast, don't limp.
await client.aclose()
raise RuntimeError(f"LLM client preflight failed: {exc}") from exc
app.state.client = client
app.state.client_ready = True
yield
app.state.client_ready = False
await client.aclose()
def get_client(request: Request):
"""Routes depend on this; tests override it with a fake (2.16)."""
return request.app.state.client
# --- auth -----------------------------------------------------------------------
@dataclass(frozen=True)
class Principal:
tenant: str
key_id: str = "" # first 8 hex of SHA-256(key): correlates log lines to a
# configured key WITHOUT storing credential material.
# Module 12 replaces the map with real key records.
def get_principal(request: Request) -> Principal:
"""Bearer-token auth against the configured key map. Reads the settings
the app was built with (app.state.settings), NOT the global get_settings():
that is what lets a test build the app with its own key map (2.16).
DEMO GRADE — see settings.py. Constant-time comparison matters even here:
a timing oracle on key lookup is a real attack. Module 12 replaces this
with verified JWTs and scopes.
"""
import hashlib
import secrets
settings: Settings = request.app.state.settings
header = request.headers.get("authorization", "")
scheme, _, token = header.partition(" ")
if scheme.lower() != "bearer" or not token:
raise HTTPException(status_code=401, detail="missing bearer token")
presented = token.encode("utf-8") # bytes: compare_digest raises TypeError on a
for key, tenant in settings.service_api_keys.items(): # non-ASCII str, a 500 for a bad header
if secrets.compare_digest(presented, key.encode("utf-8")):
if not tenant: # a key bound to no tenant must not authenticate
raise HTTPException(status_code=401, detail="invalid token")
return Principal(tenant=tenant,
key_id=hashlib.sha256(key.encode()).hexdigest()[:8])
raise HTTPException(status_code=401, detail="invalid token")
# --- per-tenant limits ----------------------------------------------------------
@dataclass
class TenantLimiter:
"""In-memory per-tenant limits: requests/minute (token bucket) and max
concurrent in-flight calls. PER PROCESS — with N replicas each tenant gets
N× the limit. For shared limits use Redis or the gateway (11C.3 owns the
shared limiter); this class is the seam."""
rpm: int
max_concurrent: int
_buckets: dict[str, tuple[float, float]] = field(default_factory=dict) # tenant -> (tokens, last_ts)
_inflight: dict[str, int] = field(default_factory=dict)
def check_rate(self, tenant: str) -> None:
now = time.monotonic()
tokens, last = self._buckets.get(tenant, (float(self.rpm), now))
tokens = min(float(self.rpm), tokens + (now - last) * self.rpm / 60.0)
if tokens < 1.0:
raise HTTPException(status_code=429, detail="rate limit exceeded", headers={"Retry-After": "60"})
self._buckets[tenant] = (tokens - 1.0, now)
def try_acquire(self, tenant: str) -> bool:
"""Take one in-flight slot; False when the tenant is at max_concurrent.
Pair every True with exactly one release() — including on streams that
end by client disconnect (see the /v1/chat/stream route)."""
if self._inflight.get(tenant, 0) >= self.max_concurrent:
return False
self._inflight[tenant] = self._inflight.get(tenant, 0) + 1
return True
def release(self, tenant: str) -> None:
self._inflight[tenant] = max(0, self._inflight.get(tenant, 0) - 1)
def get_limiter(request: Request) -> TenantLimiter:
"""The per-process limiter, created by the app factory and stored on app.state."""
return request.app.state.limiter2.4 Request and response schemas#
The service's public API is deliberately small: chat completions (plain and streaming) and the jobs API. It accepts simple {role, content} messages and converts them to the canonical provider_agnostic types — the wire format to providers stays inside the client package.
# llm_service/schemas.py
"""llm_service/schemas.py — the service's public API shapes (Pydantic)."""
from __future__ import annotations
import ipaddress
import re
from typing import Literal
from urllib.parse import urlsplit
from pydantic import BaseModel, Field, field_validator
class MessageIn(BaseModel):
"""One chat turn as the API accepts it. System prompts are NOT accepted
from clients: they come from the prompt registry (04.10) server-side, so a
caller can't overwrite your instructions. Tool turns are v2 — the
provider_agnostic Message type already supports them."""
role: Literal["user", "assistant"]
content: str = Field(min_length=1, max_length=200_000)
class ChatRequest(BaseModel):
messages: list[MessageIn] = Field(min_length=1, max_length=100)
model: str | None = None # alias; None -> settings.default_model
max_output_tokens: int | None = Field(default=None, ge=1, le=32_768)
# No `stream` flag: the ROUTE chooses the shape (/v1/chat vs /v1/chat/stream).
# A caller-supplied idempotency key applies to POST /v1/jobs; ignored on /chat.
class JobRequest(ChatRequest):
"""POST /v1/jobs body: a chat request plus an optional result callback.
callback_url must be http(s); on completion the worker POSTs the finished
JobStatusOut there, HMAC-signed (jobs.py). Omitted -> poll GET /v1/jobs/{id}."""
callback_url: str | None = Field(default=None, max_length=2048)
@field_validator("callback_url")
@classmethod
def _callback_must_be_http(cls, v: str | None) -> str | None:
if v is None:
return v
if not v.startswith(("http://", "https://")) or any(
ord(c) <= 32 or c == "\\" for c in v):
raise ValueError("callback_url must be an http(s) URL")
# A first, string-level SSRF screen: the worker POSTs to whatever is here.
# It cannot see where a NAME resolves, so production still needs the egress
# allow-list and a re-check after DNS resolution (12.5's url_is_safe is the
# fuller version); this keeps the obvious internal targets out of the demo.
parts = urlsplit(v)
host = (parts.hostname or "").lower().rstrip(".")
if not host or parts.username or parts.password:
raise ValueError("callback_url needs a plain host and no credentials")
try:
ip = ipaddress.ip_address(host)
except ValueError:
ip = None
last_label = host.rsplit(".", 1)[-1]
if ((ip is not None and (not ip.is_global or ip.is_multicast))
or host == "localhost" or host.endswith((".local", ".internal", ".localhost"))
or (ip is None and re.fullmatch(r"0x[0-9a-f]+|[0-9]+", last_label))):
# ^ numeric hosts ipaddress does not parse but resolvers do: 2130706433, 0x7f.1
raise ValueError("callback_url must name a public host")
return v
class UsageOut(BaseModel):
"""Field-for-field mirror of provider_agnostic.types.Usage, plus the
read-only total_input_tokens — cache writes by lifetime, geo/regional
modifiers, server-side searches, per-modality input and the
provider-reported cost all stay visible at the API boundary."""
uncached_input_tokens: int = 0
cached_input_tokens: int = 0
cache_write_tokens: dict[str, int] = Field(default_factory=dict)
output_tokens: int = 0
reasoning_tokens: int = 0
total_input_tokens: int = 0
tier: str = "standard"
geo: str | None = None
regional: bool = False
web_searches: int = 0
grounding_searches: int = 0
modality_input: dict[str, int] = Field(default_factory=dict)
reported_cost_usd: float | None = None
class ChatResponse(BaseModel):
id: str # OUR call id (Response.call_id)
request_id: str | None # the provider's id, for support tickets
model: str # alias requested
served_by: str # model_key that actually answered
resolved_model: str | None # the dated snapshot the provider ran
text: str
finish_reason: str
usage: UsageOut | None # None = unknown, never a silent zero
cost_usd: float | None
latency_ms: int
attempts: int # how many tries it took (fallbacks included)
class JobAccepted(BaseModel):
job_id: str
status: str # "queued" on first accept; the job's CURRENT status on an idempotent replay
poll_url: str
class JobStatusOut(BaseModel):
job_id: str
status: Literal["queued", "running", "succeeded", "failed"]
result: ChatResponse | None = None
error: str | None = None2.5 Mapping canonical types to the API#
One small pure module keeps main.py readable and is unit-testable without FastAPI:
# llm_service/serialize.py
"""llm_service/serialize.py — provider_agnostic types -> our API schemas.
Pure functions: no I/O, fully unit-testable."""
from __future__ import annotations
from provider_agnostic.types import Message, Request, Response
from llm_service.schemas import ChatRequest, ChatResponse, MessageIn, UsageOut
def to_canonical_messages(messages: list[MessageIn]) -> list[Message]:
"""API messages -> canonical messages. Assistant turns round-trip as plain
text; tool parts are a v2 concern (see MessageIn's docstring)."""
return [
Message.user(m.content) if m.role == "user" else Message.assistant(m.content)
for m in messages
]
def to_request(chat: ChatRequest, *, default_model: str, tenant: str,
token_ceiling: int) -> Request:
"""API request -> canonical Request. metadata carries OUR labels only
(tenant, feature): it never reaches the provider (03.11, Request.metadata).
max_output_tokens is clamped to the service ceiling: a client may lower it,
never raise it (settings.max_output_tokens is the ceiling, not a default)."""
return Request(
model=chat.model or default_model,
messages=to_canonical_messages(chat.messages),
max_output_tokens=min(chat.max_output_tokens or token_ceiling, token_ceiling),
metadata={"tenant": tenant, "feature": "chat"},
)
def to_chat_response(resp: Response, *, request_id: str | None = None) -> ChatResponse:
usage = resp.usage
return ChatResponse(
id=resp.call_id,
request_id=resp.request_id or request_id,
model=resp.requested_model,
served_by=resp.model_key,
resolved_model=resp.resolved_model,
text=resp.text,
finish_reason=resp.finish_reason.value,
usage=UsageOut(**usage.model_dump(),
total_input_tokens=usage.total_input_tokens) if usage else None,
cost_usd=resp.cost.usd if resp.cost else None,
latency_ms=resp.latency_ms,
attempts=len(resp.attempts),
)2.6 Error mapping: LLMError → HTTP#
03.11's error hierarchy gives every failure a class and a retryable flag. The service maps those classes to HTTP statuses — this is the boundary where "provider problem" becomes "HTTP problem".
# llm_service/errors.py
"""llm_service/errors.py — one mapping from the client's LLMError hierarchy to
HTTP statuses. Keep it a pure function: it is the contract your API docs promise."""
from __future__ import annotations
from fastapi import HTTPException
from provider_agnostic.errors import (
AuthFailed, BadRequest, ConfigError, ContextTooLong, ContentBlocked,
ConnectionFailed, HookError, LLMError, OutputInvalid, Overloaded,
PermissionDenied, QuotaExceeded, RateLimited, Refused, ResponseFailed,
ServerError, Timeout, Truncated, UnsupportedFeature,
)
def to_http(exc: LLMError) -> HTTPException:
"""LLMError -> HTTPException. Status choice is a product decision:
- 4xx = the CALLER can fix it (bad request, context too long, refused content policy)
- 429 = slow down (rate limit, overload)
- 5xx = our side or the provider's side failed transiently
- Never leak provider internals: `detail` is a short safe string; the full
error (with provider, status, request_id) goes to the log, not the client.
"""
detail = {
BadRequest: (400, "bad request"),
ContextTooLong: (400, "input too long for the model's context"),
UnsupportedFeature: (400, "requested feature not supported by this model"),
OutputInvalid: (502, "model output failed validation"),
Refused: (422, "the model declined this request"),
ContentBlocked: (422, "content blocked by safety policy"),
Truncated: (502, "model output was truncated"),
ResponseFailed: (502, "model provider reported a failure"),
RateLimited: (429, "rate limited, retry later"),
Overloaded: (503, "model provider overloaded, retry later"),
QuotaExceeded: (503, "model provider quota exhausted"),
ServerError: (502, "model provider error"),
Timeout: (504, "model provider timed out"),
ConnectionFailed: (502, "could not reach model provider"),
AuthFailed: (503, "model provider authentication failed"), # OUR key is bad: not the caller's 401
PermissionDenied: (503, "model provider denied access"),
ConfigError: (500, "service misconfigured"),
HookError: (500, "internal pipeline error"),
}
# isinstance walk: subclasses (ContextTooLong is a BadRequest) must hit first
for cls in (ContextTooLong, BadRequest, UnsupportedFeature, OutputInvalid, Refused,
ContentBlocked, Truncated, ResponseFailed, RateLimited, Overloaded,
QuotaExceeded, ServerError, Timeout, ConnectionFailed, AuthFailed,
PermissionDenied, ConfigError, HookError):
if isinstance(exc, cls):
status, msg = detail[cls]
headers = {"Retry-After": "5"} if status in (429, 503) else None
return HTTPException(status_code=status, detail=msg, headers=headers)
return HTTPException(status_code=500, detail="internal error")2.7 The app factory and routes#
create_app() is the composition root: it builds settings, the limiter, mounts middleware, and registers routes. Tests build the same app with a fake client.
# llm_service/main.py — the COMPLETE import list for the finished file.
# Snippets in 2.8–2.10 add routes and helpers inside create_app(); they need
# no further imports because everything is listed here.
from __future__ import annotations
import asyncio
import uuid
from collections.abc import AsyncIterator
from contextlib import aclosing, asynccontextmanager
from dataclasses import dataclass
from fastapi import Depends, FastAPI, Header, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.sse import EventSourceResponse, ServerSentEvent
from provider_agnostic.errors import LLMError
from provider_agnostic.types import Done, ReasoningDelta, StreamEvent, TextDelta, UsageEvent
from llm_service import jobs as jobs_mod
from llm_service.deps import (
Principal, TenantLimiter, get_client, get_limiter, get_principal, lifespan,
)
from llm_service.errors import to_http
from llm_service.logging import RequestIdMiddleware, configure_logging
from llm_service.schemas import (
ChatRequest, ChatResponse, JobAccepted, JobRequest, JobStatusOut,
)
from llm_service.serialize import to_chat_response, to_request
from llm_service.settings import Settings, get_settings
class MaxBodySizeMiddleware:
"""Pure ASGI body cap -> 413 before routing. Buffers the body (bounded by
the cap itself), then replays it to the app, so chunked bodies without a
Content-Length are covered too. Bodies here are small JSON; the cap is a
first-line guard — schemas.py holds the real per-field limits."""
def __init__(self, app, max_bytes: int):
self.app, self.max_bytes = app, max_bytes
async def __call__(self, scope, receive, send):
if scope["type"] != "http" or scope.get("method") in ("GET", "HEAD", "OPTIONS"):
await self.app(scope, receive, send)
return
body = bytearray()
while True:
message = await receive()
if message["type"] == "http.disconnect":
return # client went away mid-upload
body += message.get("body", b"")
if len(body) > self.max_bytes:
await JSONResponse({"detail": "request body too large"},
status_code=413)(scope, receive, send)
return
if not message.get("more_body", False):
break
sent = False
async def replay():
nonlocal sent
if not sent:
sent = True
return {"type": "http.request", "body": bytes(body), "more_body": False}
return await receive() # disconnects pass through
await self.app(scope, replay, send)
def create_app(settings=None, *, client=None, job_store=None) -> FastAPI:
"""App factory. `client` and `job_store` are the test seams: pass fakes and
the whole app runs with no keys and no network (2.16)."""
settings = settings or get_settings()
configure_logging(settings.log_level, settings.log_json) # real call, not a comment (2.11)
@asynccontextmanager
async def app_lifespan(app: FastAPI):
app.state.settings = settings
app.state.limiter = TenantLimiter(
rpm=settings.rate_limit_requests_per_minute,
max_concurrent=settings.rate_limit_max_concurrent,
)
app.state.jobs = job_store or jobs_mod.InMemoryJobStore(
ttl_seconds=settings.job_result_ttl_seconds
)
app.state.bg_tasks = set() # strong refs to running job tasks (see 2.10)
if client is not None: # tests: inject, don't build
app.state.client = client
app.state.client_ready = True
yield
return
async with lifespan(app): # production: build + preflight + close
yield
app = FastAPI(
title=settings.service_name,
version=settings.version,
lifespan=app_lifespan,
docs_url="/docs" if settings.environment != "prod" else None,
redoc_url=None,
openapi_url="/openapi.json" if settings.environment != "prod" else None,
)
app.state.settings = settings
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins, # explicit list — never "*" with credentials
allow_methods=["GET", "POST"],
allow_headers=["Authorization", "Content-Type", "Idempotency-Key"],
allow_credentials=True,
)
app.add_middleware(MaxBodySizeMiddleware, max_bytes=settings.max_request_bytes)
app.add_middleware(RequestIdMiddleware) # outermost: IDs on every request, even 413s
# --- probes -------------------------------------------------------------------
@app.get("/healthz") # liveness: the process is up
def healthz() -> dict:
return {"status": "ok"}
@app.get("/readyz") # readiness: can it serve? (2.14 uses it for drains)
def readyz(request: Request) -> JSONResponse:
ready = getattr(request.app.state, "client_ready", False)
return JSONResponse({"ready": ready}, status_code=200 if ready else 503)
# --- chat ---------------------------------------------------------------------
@app.post("/v1/chat", response_model=ChatResponse)
async def chat(
body: ChatRequest,
request: Request,
principal: Principal = Depends(get_principal),
limiter: TenantLimiter = Depends(get_limiter),
) -> ChatResponse:
settings: Settings = request.app.state.settings
limiter.check_rate(principal.tenant)
if not limiter.try_acquire(principal.tenant):
raise HTTPException(status_code=429, detail="too many concurrent requests",
headers={"Retry-After": "5"})
try:
client = get_client(request)
req = to_request(body, default_model=settings.default_model,
tenant=principal.tenant,
token_ceiling=settings.max_output_tokens)
try:
resp = await client.acomplete(req)
except LLMError as exc:
request.state.llm_error = exc # for the log middleware (2.11)
raise to_http(exc) from exc
return to_chat_response(resp, request_id=request.state.request_id)
finally:
limiter.release(principal.tenant)
return app
# Re-exported so `uvicorn llm_service.main:app` has an app object too.
app = create_app()Notes on what this skeleton already gets right:
docs_url=Nonein prod: OpenAPI docs are an attack surface and a leak (they describe your whole API). Keep them in dev/staging only, or behind auth.- Health vs readiness are different probes:
/healthzanswers "is the process alive" (restart it if not);/readyzanswers "should traffic be sent here" (drain it during deploys). Kubernetes and every PaaS distinguish these — mixing them causes deploys that kill live traffic or restart loops on a slow dependency. client_readyis set in lifespan afterpreflight; a process whose provider keys are missing reports not-ready instead of serving 500s.request.state.request_idis set by the logging middleware in 2.11;to_chat_responsefalls back to it when the provider sends no ID.- Idempotency-Key: accepted in CORS headers here; the jobs API below implements the actual dedupe (2.9).
/v1/chatis not idempotent — a retry is a new, billed generation. That's honest: synchronous chat retries belong inside the client layer (03.8), not around the endpoint.
2.8 The streaming endpoint#
This is where LLM deployment differs most from ordinary APIs. 03.3, Part 11 built the browser side and the event protocol; here is the server side wired to client.astream, with the two error boundaries streaming forces on you: failures before the first byte can still be HTTP statuses, failures after can only be SSE error events.
The pieces live in main.py: _sse_for maps canonical stream events to our SSE events, _prime_stream is a dependency that does auth-adjacent work, opens client.astream and pulls the first forwardable event before the response starts, and the route itself is an async generator that yields ServerSentEvents.
# llm_service/main.py — module level, before create_app() (all imports already above)
def _sse_for(ev) -> ServerSentEvent | None:
"""Canonical stream event -> OUR SSE event (03.3, 11A.2's protocol).
Returns None for events we don't forward in v1 (ToolCallStart/ToolCallDelta;
the client consumes the adapters' internal Opened marker itself).
The provider's raw vocabulary never reaches the browser: swapping
providers changes this mapping, not the front end."""
if isinstance(ev, TextDelta):
return ServerSentEvent(event="delta", data={"text": ev.text})
if isinstance(ev, ReasoningDelta):
return ServerSentEvent(event="reasoning", data={"text": ev.text})
if isinstance(ev, UsageEvent):
return ServerSentEvent(event="usage", data=ev.usage.model_dump(mode="json"))
if isinstance(ev, Done):
return ServerSentEvent(event="done",
data=to_chat_response(ev.response).model_dump(mode="json"))
return None
@dataclass
class _StreamPrimed:
"""Hand-off from the priming dependency to the SSE endpoint: the open
upstream iterator plus the events already pulled and converted."""
stream: AsyncIterator[StreamEvent]
primed: list[ServerSentEvent]
tenant: str
async def _aclose_stream(stream) -> None:
"""client.astream returns an async generator; aclose() is the
deterministic close that fires the client's `abandoned` hook for the
billed partial. Safe on an already-finished stream (a no-op)."""
aclose = getattr(stream, "aclose", None)
if aclose is not None:
await aclose()
async def _prime_stream(
body: ChatRequest,
request: Request,
principal: Principal = Depends(get_principal),
limiter: TenantLimiter = Depends(get_limiter),
) -> AsyncIterator[_StreamPrimed]:
"""Yield-dependency: everything before `yield` runs BEFORE the SSE
response starts, so its failures are real HTTP statuses. It takes the
concurrency slot, opens client.astream and pulls until the first
forwardable event — which is what runs LLMClient._start (hooks,
preflight, capability checks) and opens the provider connection."""
settings: Settings = request.app.state.settings
limiter.check_rate(principal.tenant)
if not limiter.try_acquire(principal.tenant):
raise HTTPException(status_code=429, detail="too many concurrent requests",
headers={"Retry-After": "5"})
stream = None
try:
client = get_client(request)
req = to_request(body, default_model=settings.default_model,
tenant=principal.tenant,
token_ceiling=settings.max_output_tokens)
stream = client.astream(req) # async generator: nothing sent yet
primed: list[ServerSentEvent] = []
# PRIME: pull until the first forwardable event. Everything raised
# here happens before any byte reaches the client -> to_http applies.
async for ev in stream:
out = _sse_for(ev)
if out is not None:
primed.append(out)
break
else:
pass # stream ended with nothing forwardable
yield _StreamPrimed(stream=stream, primed=primed, tenant=principal.tenant)
except LLMError as exc:
request.state.llm_error = exc
raise to_http(exc) from exc
finally:
limiter.release(principal.tenant) # slot held for the stream's whole life
if stream is not None:
await _aclose_stream(stream) # no-op if the endpoint already closed itThen inside create_app():
# llm_service/main.py — inside create_app() (shown dedented for readability)
@app.post("/v1/chat/stream", response_class=EventSourceResponse)
async def chat_stream(
request: Request,
primed: _StreamPrimed = Depends(_prime_stream),
) -> AsyncIterator[ServerSentEvent]:
"""Async generator — REQUIRED for FastAPI's SSE encoding. Auth, limits,
priming and the first pull already happened in _prime_stream (real HTTP
errors); from here on the only error channel left is an `error` event."""
try:
for ev in primed.primed: # replay what priming pulled
yield ev
async with aclosing(primed.stream) as stream:
async for ev in stream: # the SAME iterator, mid-generation
out = _sse_for(ev)
if out is not None:
yield out
except LLMError as exc:
request.state.llm_error = exc
yield ServerSentEvent(event="error",
data={"message": "generation failed",
"retryable": exc.retryable})
# asyncio.CancelledError is deliberately NOT caught: on client
# disconnect it must propagate so aclosing() closes the provider
# stream and the client's `abandoned` hook records the billed partial.Three details in this version are load-bearing:
- Priming pulls the first forwardable event before the response exists.
client.astream(req)is an async generator: calling it does nothing; the first__anext__runs_start()(hooks, preflight, capability checks) and opens the provider stream.ConfigError,RateLimited,UnsupportedFeatureraised there become real HTTP statuses throughto_http. OnceEventSourceResponsestarts iterating, headers are committed and onlyerrorevents remain. - One iterator, two consumers.
streamis created once inside_prime_stream; priming consumes its head, the endpoint replaysprimedthen continues the same iterator viaaclosing. Opening a secondclient.astream(req)would pay for a second generation. - The slot spans the whole stream, released by the dependency's
finally._prime_streamacquires the concurrency slot beforeyieldand releases it infinally— which runs when the request's exit stack unwinds, after the SSE producer is torn down and the endpoint generator closed. A stream holds its slot for its whole life — potentially minutes — which is correct (it is an in-flight, billable call) but meansmax_concurrentreally means "max open streams plus calls". If you don't hold it, one tenant opens 500 tabs and eats your provider quota. On client disconnect,CancelledErrorpropagates through the endpoint'sasync for,aclosingcloses the upstream iterator,client.astream's ownexcept (GeneratorExit, asyncio.CancelledError)records the abandoned partial's billed usage via theabandonedhook (03.11), and only then does the dependency'sfinallyrelease the slot.
2.9 Background jobs: slow work off the request path#
Some work shouldn't hold an HTTP request at all: a 500-document batch summarisation, a report that takes three provider calls, anything a user would rather submit-and-poll. The pattern is accept-and-poll: POST returns 202 Accepted with a job ID immediately; a worker does the LLM calls; GET polls for the result.
# llm_service/jobs.py
"""llm_service/jobs.py — the accept-and-poll job layer.
IN-PROCESS REFERENCE IMPLEMENTATION: state lives in this process's memory,
so it is lost on restart and invisible to other replicas. That is honest for
a single instance and a teaching tool for the SHAPE. Production swaps
InMemoryJobStore for Redis/DB and runs the worker as a separate process or
replicas (Part 5.5: Celery/RQ/Dramatiq/arq/Temporal/Cloud Tasks). The design
rules that carry over: deterministic job IDs, explicit states, idempotent
submission, results stored before they're reported done (03.9, Part 11)."""
from __future__ import annotations
import asyncio
import hashlib
import hmac
import json
import logging
import time
import uuid
from dataclasses import dataclass, field
from typing import Protocol
import httpx
from provider_agnostic.types import Request, Response
log = logging.getLogger("llm_service.jobs")
class JobStore(Protocol):
"""The seam a real store (Redis, Postgres, SQS+DB) implements. The job
methods carry state; idem_lookup/idem_store carry the submission
idempotency key; count_active feeds the per-tenant concurrency cap."""
def create(self, job_id: str, kind: str, tenant: str,
callback_url: str | None = None) -> None: ...
def get(self, job_id: str) -> "Job | None": ...
def save_result(self, job_id: str, result: Response | None, error: str | None) -> None: ...
def idem_lookup(self, tenant: str, key: str) -> str | None: ...
def idem_store(self, tenant: str, key: str, job_id: str) -> None: ...
def count_active(self, tenant: str) -> int: ...
@dataclass
class Job:
job_id: str
kind: str
tenant: str
status: str = "queued" # queued | running | succeeded | failed
result: Response | None = None
error: str | None = None
callback_url: str | None = None # set => worker POSTs the result here (2.10)
created_at: float = field(default_factory=time.time)
finished_at: float | None = None
class InMemoryJobStore:
"""Per-process store with TTL eviction. Fine for one replica; the Protocol
above is what a shared store implements — a Redis/DB version keeps the
same six methods and the routes never notice."""
def __init__(self, ttl_seconds: int = 3600):
self.ttl = ttl_seconds
self._jobs: dict[str, Job] = {}
self._idem: dict[tuple[str, str], str] = {} # (tenant, idempotency_key) -> job_id
def create(self, job_id: str, kind: str, tenant: str,
callback_url: str | None = None) -> None:
self._jobs[job_id] = Job(job_id=job_id, kind=kind, tenant=tenant,
callback_url=callback_url)
def get(self, job_id: str) -> Job | None:
job = self._jobs.get(job_id)
if job and time.time() - job.created_at > self.ttl:
del self._jobs[job_id]
return None
return job
def save_result(self, job_id: str, result: Response | None, error: str | None) -> None:
job = self._jobs.get(job_id)
if job:
job.result, job.error = result, error
job.status = "succeeded" if error is None else "failed"
job.finished_at = time.time()
# --- idempotency ---------------------------------------------------------
def idem_lookup(self, tenant: str, key: str) -> str | None:
return self._idem.get((tenant, key))
def idem_store(self, tenant: str, key: str, job_id: str) -> None:
self._idem[(tenant, key)] = job_id
def count_active(self, tenant: str) -> int:
return sum(1 for j in self._jobs.values()
if j.tenant == tenant and j.status in ("queued", "running"))
async def _deliver_callback(job: Job, payload: dict, *, secret: str) -> None:
"""POST the terminal JobStatusOut to job.callback_url, HMAC-signed.
Best-effort BY DESIGN: the durable retry/DLQ story belongs to the queue
(03.9, 11C.3); this reference worker tries 3 quick attempts, then logs
loudly and moves on — polling GET /v1/jobs/{id} remains the fallback.
Module 12 owns signature verification and callback_url SSRF checks
(an http(s) URL can still point at your own internal network)."""
body = json.dumps(payload).encode()
headers = {"Content-Type": "application/json", "X-LLM-Event": "job.finished"}
if secret:
headers["X-LLM-Signature"] = "sha256=" + hmac.new(
secret.encode(), body, hashlib.sha256).hexdigest()
else:
log.warning("job %s callback delivered UNSIGNED "
"(LLM_WEBHOOK_SIGNING_SECRET unset)", job.job_id)
try:
async with httpx.AsyncClient(timeout=10.0) as http:
for attempt in range(3):
try:
r = await http.post(job.callback_url, content=body, headers=headers)
if r.status_code < 500:
return # 2xx/3xx/4xx: delivered or permanently rejected
except httpx.HTTPError:
pass
await asyncio.sleep(0.5 * (2 ** attempt))
log.warning("job %s callback undelivered after 3 attempts", job.job_id)
except Exception:
log.exception("job %s callback delivery crashed", job.job_id)
async def run_chat_job(store: JobStore, client, req: Request, job_id: str,
*, webhook_secret: str = "") -> None:
"""The worker side: run the call, store the result, then push it to the
job's callback_url if one was supplied. Errors are captured, not raised —
a failed job is a RESULT the poller/callback reads, not a crash."""
job = store.get(job_id)
if job is None:
return
job.status = "running"
try:
resp = await client.acomplete(req)
store.save_result(job_id, resp, None)
except Exception as exc: # noqa: BLE001 — a failed job is a RESULT, not a crash
log.exception("job %s failed", job_id) # but it must still be logged, with the traceback
store.save_result(job_id, None, f"{type(exc).__name__}: {exc}")
job = store.get(job_id) # re-read: save_result mutated it
if job and job.callback_url:
from llm_service.serialize import to_chat_response # local: keeps jobs.py light
await _deliver_callback(job, {
"job_id": job.job_id, "status": job.status,
"result": to_chat_response(job.result).model_dump(mode="json")
if job.result else None,
"error": job.error,
}, secret=webhook_secret)(log is defined at the top of jobs.py itself; RequestIdFilter in 2.11 puts the request_id on its lines too.)
2.10 Jobs routes and idempotency#
# llm_service/main.py — these two routes are added inside create_app(),
# after the stream route (shown dedented for readability). No new imports:
# JobRequest, Header, asyncio and jobs_mod are all in the 2.7 import list.
@app.post("/v1/jobs", response_model=JobAccepted, status_code=202)
async def submit_job(
body: JobRequest, # chat fields + optional callback_url (2.9)
request: Request,
principal: Principal = Depends(get_principal),
idempotency_key: str | None = Header(default=None, alias="Idempotency-Key"),
):
"""Accept-and-poll (or accept-and-callback). Idempotent on
(tenant, Idempotency-Key): a retry with the same key returns the SAME
job — with its CURRENT status, never a second billed run."""
settings: Settings = request.app.state.settings
store = request.app.state.jobs
limiter: TenantLimiter = request.app.state.limiter
limiter.check_rate(principal.tenant)
if idempotency_key:
existing = store.idem_lookup(principal.tenant, idempotency_key)
if existing:
job = store.get(existing)
if job is not None:
# Replay reports the job's REAL state: a client that retries
# after a timeout must not be told "queued" about a job that
# already succeeded — the 202 body is a status resource, and
# lying here is how double-submits happen.
return JobAccepted(job_id=existing, status=job.status,
poll_url=f"/v1/jobs/{existing}")
# The job expired (TTL): the idempotency window is the job's
# lifetime, so fall through and accept a fresh run.
if store.count_active(principal.tenant) >= settings.job_max_per_tenant:
raise HTTPException(status_code=429, detail="too many active jobs",
headers={"Retry-After": "30"})
job_id = uuid.uuid4().hex[:16]
store.create(job_id, "chat", principal.tenant, callback_url=body.callback_url)
if idempotency_key:
store.idem_store(principal.tenant, idempotency_key, job_id)
req = to_request(body, default_model=settings.default_model,
tenant=principal.tenant,
token_ceiling=settings.max_output_tokens)
client = get_client(request)
task = asyncio.create_task(jobs_mod.run_chat_job(
store, client, req, job_id,
webhook_secret=settings.webhook_signing_secret))
# The event loop keeps only a WEAK reference to a task: a fire-and-forget
# task nobody else references can be garbage-collected mid-run. Hold it.
request.app.state.bg_tasks.add(task)
task.add_done_callback(request.app.state.bg_tasks.discard)
return JobAccepted(job_id=job_id, status="queued", poll_url=f"/v1/jobs/{job_id}")
@app.get("/v1/jobs/{job_id}", response_model=JobStatusOut)
async def get_job(job_id: str, request: Request,
principal: Principal = Depends(get_principal)):
job = request.app.state.jobs.get(job_id)
# Tenant check: a job belongs to the tenant that created it.
if job is None or job.tenant != principal.tenant:
raise HTTPException(status_code=404, detail="job not found")
return JobStatusOut(
job_id=job.job_id, status=job.status,
result=to_chat_response(job.result) if job.result else None,
error=job.error,
)Push vs poll: callback_url. Polling GET /v1/jobs/{id} is the default contract because it needs nothing inbound — no public endpoint, no signature verification, no retry bookkeeping on your side. JobRequest.callback_url adds the push option for clients that can't or won't poll: on terminal state the worker POSTs the finished JobStatusOut JSON with an X-LLM-Signature: sha256=<hmac> header keyed by LLM_WEBHOOK_SIGNING_SECRET. Three cautions before you ship it: (1) callback_url is client-supplied input — the schema screens the string (no credentials or backslashes, no IP literal that is not public, no localhost, .local or .internal name, no 2130706433-style numeric host), but it cannot see where a name resolves, so production still needs an egress allow-list and DNS-rebinding checks (Module 12 owns that); (2) the reference delivery is best-effort — durable retry and dead-lettering belong to the queue (03.9, 11C.3), and a real queue (SQS, Cloud Tasks) gives you delivery guarantees asyncio.create_task never will; (3) receivers must dedupe on job_id — at-least-once delivery means the same callback can arrive twice.
2.11 Structured logging with request IDs#
03.10, Part 4 owns the full logging kit (what to log, redaction, the Completion record). Deployment adds one thing it didn't need: correlating every log line of one HTTP request. A middleware stamps a request ID; a JSON formatter puts it on every line.
# llm_service/logging.py
"""llm_service/logging.py — request IDs + JSON logs. Thin on purpose:
the what-to-log rules live in 03.10; this is the transport glue."""
from __future__ import annotations
import contextvars
import json
import logging
import sys
import time
import uuid
_request_ctx: contextvars.ContextVar[dict] = contextvars.ContextVar("llm_request_ctx", default={})
class RequestIdFilter(logging.Filter):
"""Adds request_id to every record emitted while a request is in flight,
via a contextvar (the VALUE is a dict set by RequestIdMiddleware)."""
def filter(self, record: logging.LogRecord) -> bool:
record.request_id = _request_ctx.get().get("request_id", "-")
return True
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
payload = {
"ts": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(record.created)),
"level": record.levelname,
"logger": record.name,
"msg": record.getMessage(),
"request_id": getattr(record, "request_id", "-"),
}
if record.exc_info:
payload["exc"] = self.formatException(record.exc_info)
return json.dumps(payload, default=str)
def configure_logging(level: str = "INFO", json_logs: bool = True) -> None:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter() if json_logs else logging.Formatter(
"%(asctime)s %(levelname)s %(name)s %(message)s"))
handler.addFilter(RequestIdFilter())
root = logging.getLogger()
root.handlers[:] = [handler] # replace, don't stack, on reload
root.setLevel(level)
# --- the ASGI middleware ---------------------------------------------------------
class RequestIdMiddleware:
"""Pure ASGI (no BaseHTTPMiddleware: it buffers bodies and breaks SSE).
Honours an inbound X-Request-ID (your edge's ID joins your logs to the
load balancer's), else mints one."""
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
headers = dict(scope.get("headers", []))
rid = headers.get(b"x-request-id", uuid.uuid4().hex[:16].encode()).decode()
token = _request_ctx.set({"request_id": rid})
scope.setdefault("state", {})["request_id"] = rid
async def send_with_id(message):
if message["type"] == "http.response.start":
message.setdefault("headers", []).append((b"x-request-id", rid.encode()))
await send(message)
try:
await self.app(scope, receive, send_with_id)
finally:
_request_ctx.reset(token)Already wired in 2.7's create_app() — app.add_middleware(RequestIdMiddleware) (outermost, after CORS and the body cap, so even 413s carry an ID) and configure_logging(settings.log_level, settings.log_json) near the top. No extra snippet needed; the call sites live in the finished main.py above.
2.12 OpenAPI, versioning and docs#
The /v1/ prefix is your API version: when /v2/ ships, /v1/ keeps working for existing clients. Rules that keep it honest:
- Version the URL, not the payload silently. Add
/v2/chatas a new route; never change/v1/chat's contract under existing clients. Deprecate withDeprecation/Sunsetheaders and a date, then remove on that date. - Docs are config, not decoration.
docs_url=Nonein prod (done in 2.7) — but also write the OpenAPI descriptions (description=on routes/models) as if a stranger will integrate against them at 2 a.m. They are your contract. - The service API ≠ the provider API. Clients see
served_by,finish_reasonas a plain string,usageflattened — your schema, notprovider_agnostic's. That boundary is what lets you change providers without a client release.
2.13 Running it: uvicorn, gunicorn, workers#
# Development (auto-reload):
uv run uvicorn llm_service.main:app --reload --port 8000
# Production, single process, many async tasks (the default shape for I/O-bound LLM work):
uv run uvicorn llm_service.main:app --host 0.0.0.0 --port 8000 \
--workers 1 --limit-concurrency 500 --timeout-keep-alive 75| Flag | What it does | LLM-service guidance |
|---|---|---|
--workers N |
N OS processes (each with its own event loop, limiter, job store!) | Start at 1–2; scale replicas, not workers, unless CPU-bound. Remember: per-process state multiplies — the in-memory limiter and job store exist per worker |
--limit-concurrency N |
503 immediately beyond N connections — a cheap backstop | Set above your expected peak; it's the last line before the provider melts, not your real limiter |
--backlog (default 2048) |
OS accept-queue size | Leave it; the real queueing belongs in your job layer |
--timeout-keep-alive (default 5 s) |
idle keep-alive between requests | Raise to ~75 s to match typical LB idle timeouts; irrelevant to stream duration (SSE is one long request, not keep-alives) |
--timeout-graceful-shutdown |
seconds to drain before hard kill | Set ≥ your longest expected stream tail, or accept that drains cut streams (6.2) |
--proxy-headers / --forwarded-allow-ips |
Take the client IP from X-Forwarded-For, but only from trusted peers (default: 127.0.0.1 and ::1) |
Behind a platform proxy set the allow-list to its address range (or FORWARDED_ALLOW_IPS); see the Dockerfile table in 3.1 |
WEB_CONCURRENCY env |
--workers default |
PaaS platforms set this; know it exists before "fixing" worker counts |
One process or many? An LLM service is almost purely I/O-bound: one async worker can hold hundreds of streams because it's waiting, not computing. Add workers only when CPU work (JSON parsing of huge payloads, Pydantic validation of big schemas) saturates a core — measure first (11A.2). And remember the multiplier: --workers 4 = 4 limiters, 4 job stores, 4 client pools. If you need shared state, you need shared storage — or fewer processes.
gunicorn is the alternative when you want its process manager (max-requests recycling, worker timeouts): uv add gunicorn uvicorn-worker, then gunicorn llm_service.main:app -k uvicorn_worker.UvicornWorker -w 2. The older uvicorn.workers.UvicornWorker path still appears in many tutorials, but uvicorn's deployment page now marks the uvicorn.workers module as deprecated in favour of the separate uvicorn-worker package (checked 8 November 2026). The same page notes that some uvicorn flags (--limit-concurrency) are not supported under gunicorn's config model — pick one supervisor and learn its knobs.
2.14 Graceful shutdown and draining#
When a deploy replaces a replica, in-flight streams die unless the platform gives them time. Three layers cooperate:
- The platform's drain window. Cloud Run, Kubernetes (
terminationGracePeriodSeconds), Fly machines and ACA revisions all offer a grace period between "stop sending new traffic" and "SIGKILL". Set it ≥ your longest reasonable stream (or accept partial answers). - uvicorn's
--timeout-graceful-shutdownstops accepting new connections and lets running requests finish up to the limit. /readyzflipping to 503 before shutdown starts is what actually drains traffic gracefully: the load balancer stops routing new requests while old streams finish. Wire your deploy to mark-not-ready → wait → terminate (KubernetespreStophooks are the explicit version). One honesty note about the skeleton in 2.7: itsclient_readyflag only turnsFalsein the lifespan shutdown, which uvicorn runs after it has stopped accepting connections, so an earlier drain needs one more piece, a drain flag that/readyzalso checks and that yourpreStophook or deploy script sets. Many platforms also stop routing to a terminating instance on their own; the flag matters most for load balancers that keep sending traffic until a health check fails.
# Optional: track open streams so shutdown can log/drain them deliberately.
# (Skeleton — production would expose a gauge to /metrics via 11A.2.)
class StreamTracker:
def __init__(self):
self.open = 0
def __call__(self, scope, receive, send): # wrap only /v1/chat/stream via middleware
...Keep it simple: the platform drain + readiness probe covers 95% of cases. The tracker matters when you must guarantee N seconds of drain for very long streams — then you need app-level awareness of open streams, which is also what 11A.2's "open streams" gauge reports.
2.15 SSE through proxies#
Your app sets X-Accel-Buffering: no (FastAPI does) and pings every 15 s (FastAPI does). That is necessary but not sufficient: every hop between client and app has its own buffering and idle timeout. The failure signature is always the same — works on localhost, arrives all-at-once or dies silently in production.
| Hop | What breaks SSE | Fix |
|---|---|---|
| nginx | proxy_buffering on (default) collects the whole body; proxy_read_timeout 60 s kills silent streams |
proxy_buffering off; for the stream location (or rely on X-Accel-Buffering: no, which nginx honours for proxied responses); raise proxy_read_timeout for stream routes |
| AWS ALB | Idle timeout 60 s default (range 1–4000 s); HTTP/2 PING does not reset it | Keep-alives every <60 s (FastAPI's 15 s ping covers it); raise idle_timeout.timeout_seconds for the target group if reasoning gaps exceed it |
| Cloudflare | ~100 s origin window → 524 if nothing arrives; works when bytes flow, but not an officially guaranteed feature | Ensure pings <100 s; for guaranteed long streams use Cloudflare Workers or grey-cloud the API hostname |
| API gateways / CDN | Some buffer or cap response duration | Check each platform's streaming docs; disable caching on stream routes |
| Serverless | Some don't stream at all | Verify before choosing (1.4) |
# nginx/llm_service.conf — the stream-safe location block (reference)
upstream llm_service {
server 127.0.0.1:8000;
keepalive 32; # reuse upstream connections
}
server {
listen 443 ssl;
server_name api.example.com;
location /v1/chat/stream {
proxy_pass http://llm_service;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off; # THE line that makes SSE work through nginx
proxy_cache off;
proxy_read_timeout 3600s; # >= longest legitimate stream; app pings cover idle
proxy_send_timeout 3600s;
chunked_transfer_encoding on;
}
location / {
proxy_pass http://llm_service;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_read_timeout 120s;
}
}2.16 Tests with a fake client#
The whole point of dependency injection: test the service's behaviour (auth, limits, error mapping, SSE protocol, job lifecycle) with a scripted client — no keys, no network, deterministic.
# tests/test_app.py — runs with `uv run pytest` — no keys needed
"""Tests for llm_service: the app is exercised through httpx ASGITransport
against a FAKE client. This is the pattern 03.10's fakes teach, applied to
the whole service."""
import asyncio
import json
import logging
from contextlib import asynccontextmanager
import httpx
import pytest
from provider_agnostic.types import (
Cost, FinishReason, Response as CanonicalResponse, TextPart,
Usage as CanonicalUsage,
)
from llm_service.logging import RequestIdFilter, _request_ctx
from llm_service.main import create_app
from llm_service.settings import Settings
SERVICE_KEY = "test-key-abc"
AUTH = {"Authorization": f"Bearer {SERVICE_KEY}"}
def make_settings() -> Settings:
return Settings(
environment="test",
service_api_keys_json=json.dumps({SERVICE_KEY: "acme"}),
cors_origins=["http://localhost:3000"],
)
class FakeClient:
"""Stands in for LLMClient: acomplete/astream return canned provider_agnostic
objects. In a real suite you'd build real Response objects; for the service
tests a tiny stand-in with the same attributes is enough."""
def __init__(self, resp=None, events=None, error=None):
self.resp, self.events, self.error = resp, events, error
async def acomplete(self, req):
if self.error:
raise self.error
return self.resp
def astream(self, req):
async def gen():
if self.error:
raise self.error
for ev in self.events or []:
yield ev
return gen()
async def aclose(self):
pass
def make_response(text="Hello"):
"""A REAL provider_agnostic.types.Response — the fake client returns
canonical objects, so a field rename in 03.11's types breaks loudly."""
return CanonicalResponse(
parts=[TextPart(text=text)],
finish_reason=FinishReason.STOP, raw_finish_reason="completed", # required: no default
usage=CanonicalUsage(uncached_input_tokens=20, output_tokens=10),
cost=Cost(usd=0.001, source="computed", price_version="test"),
provider="openai", api="responses",
model_key="gpt-6-luna", requested_model="fast",
request_id="req_1", call_id="call_1", latency_ms=12,
)
def make_app(client):
return create_app(settings=make_settings(), client=client)
@asynccontextmanager
async def running(client):
"""Yield an httpx client wired to the app AFTER its lifespan has started.
httpx.ASGITransport does not run ASGI lifespan events by itself, and
create_app() builds the limiter, job store and client holder in its
lifespan, so without this the first request would hit a bare app.state."""
app = make_app(client)
async with app.router.lifespan_context(app):
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app),
base_url="http://t") as c:
yield c
@pytest.mark.anyio
async def test_chat_requires_auth():
async with running(FakeClient(resp=make_response())) as c:
r = await c.post("/v1/chat", json={"messages": [{"role": "user", "content": "hi"}]})
assert r.status_code == 401
@pytest.mark.anyio
async def test_chat_happy_path():
async with running(FakeClient(resp=make_response("Hi there"))) as c:
r = await c.post("/v1/chat", json={"messages": [{"role": "user", "content": "hi"}]},
headers=AUTH)
assert r.status_code == 200
body = r.json()
assert body["text"] == "Hi there"
assert body["served_by"] == "gpt-6-luna"
assert body["usage"]["total_input_tokens"] == 20
@pytest.mark.anyio
async def test_chat_maps_llm_error():
from provider_agnostic.errors import RateLimited
async with running(FakeClient(error=RateLimited("slow down", provider="openai", status=429))) as c:
r = await c.post("/v1/chat", json={"messages": [{"role": "user", "content": "hi"}]},
headers=AUTH)
assert r.status_code == 429
assert r.headers.get("retry-after") == "5"
@pytest.mark.anyio
async def test_job_lifecycle_and_idempotency():
async with running(FakeClient(resp=make_response())) as c:
r1 = await c.post("/v1/jobs", json={"messages": [{"role": "user", "content": "summarise"}]},
headers={**AUTH, "Idempotency-Key": "k1"})
assert r1.status_code == 202
job_id = r1.json()["job_id"]
# Same key -> same job, not a second billed run
r2 = await c.post("/v1/jobs", json={"messages": [{"role": "user", "content": "summarise"}]},
headers={**AUTH, "Idempotency-Key": "k1"})
assert r2.json()["job_id"] == job_id
# Poll until done (the fake returns immediately)
for _ in range(50):
g = await c.get(f"/v1/jobs/{job_id}", headers=AUTH)
if g.json()["status"] in ("succeeded", "failed"):
break
await asyncio.sleep(0.05)
assert g.json()["status"] == "succeeded"
assert g.json()["result"]["text"] == "Hello"
# Idempotent replay reports the job's CURRENT status, not "queued"
r3 = await c.post("/v1/jobs", json={"messages": [{"role": "user", "content": "summarise"}]},
headers={**AUTH, "Idempotency-Key": "k1"})
assert r3.json()["job_id"] == job_id
assert r3.json()["status"] == "succeeded"
def test_request_id_filter_reads_the_contextvar():
"""RequestIdFilter stamps request_id on records inside a request's
context and "-" outside one — the wiring 2.7/2.11 depends on."""
record = logging.LogRecord("t", logging.INFO, __file__, 1, "msg", (), None)
token = _request_ctx.set({"request_id": "abc123"})
try:
assert RequestIdFilter().filter(record)
assert record.request_id == "abc123"
finally:
_request_ctx.reset(token)
other = logging.LogRecord("t", logging.INFO, __file__, 1, "msg", (), None)
RequestIdFilter().filter(other)
assert other.request_id == "-"Part 3: Containerisation#
3.1 The Dockerfile#
A production image for llm_service: multi-stage build, uv for dependency resolution, non-root user, pinned bases, the lockfile copied before source so dependency layers cache.
# Dockerfile — llm_service. Build context: the llm-service repo root.
# Reference only: not run in this lesson. Verify base-image tags on Docker Hub.
# ---- stage 1: resolve dependencies with uv (cached layer) ---------------------
FROM ghcr.io/astral-sh/uv:python3.13-bookworm-slim AS builder
WORKDIR /app
# Copy ONLY the dependency manifests first: this layer caches until deps change.
COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev --no-install-project
# ---- stage 2: runtime ----------------------------------------------------------------
FROM python:3.13-slim-bookworm
# Non-root: a container escape lands as an unprivileged user. Create it explicitly
# (the base image has no 'app' user) and never run as root "just for this deploy".
RUN groupadd -r app && useradd -r -g app -d /app -s /sbin/nologin app
WORKDIR /app
COPY --from=builder /app/.venv /app/.venv
COPY llm_service/ ./llm_service/
COPY provider_agnostic/ ./provider_agnostic/
# Two routes from Setup. WHEEL: delete the COPY provider_agnostic/ line above, and make
# sure the wheel sits INSIDE the build context (for example vendor/agnostic_client-0.1.0-
# py3-none-any.whl, added with `uv add ./vendor/<wheel>`): a `../agnostic-client` path
# outside the context makes `uv sync --frozen` fail in the builder. With the wheel, the
# borrowed modules (cost_calc.py, prices.py, prices.yaml, llm_errors.py, retry_after.py,
# check_response.py) already live inside .venv: nothing more to copy.
# SOURCES: keep the COPY line above and add the borrowed files too:
# COPY cost_calc.py prices.py prices.yaml llm_errors.py retry_after.py check_response.py ./
ENV PATH="/app/.venv/bin:$PATH" \
PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1
USER app
EXPOSE 8000
# Liveness probe for orchestrators that support it (K8s, some PaaS health checks).
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=4).status==200 else 1)"
# --proxy-headers is uvicorn's default, but it trusts X-Forwarded-For/Proto only
# from 127.0.0.1 and ::1. Behind a platform proxy also set FORWARDED_ALLOW_IPS (or
# --forwarded-allow-ips) to the proxy's address range, or logs and per-IP limits
# keep seeing the proxy's own address. --workers: tune per Part 2.13.
CMD ["uvicorn", "llm_service.main:app", "--host", "0.0.0.0", "--port", "8000", \
"--proxy-headers", "--timeout-graceful-shutdown", "30"]The choices, and why each matters for an LLM service specifically:
| Choice | Why |
|---|---|
Multi-stage + uv sync --frozen |
The builder stage resolves deps once; the runtime stage copies only .venv. --frozen fails the build if uv.lock is stale — reproducible images, no "worked on my machine" dep drift |
python:3.13-slim-bookworm pinned |
slim keeps the image small (faster pulls = faster cold starts); the bookworm tag pins the Debian release; still floating on the Python patch — pin 3.13.x-slim-bookworm in real repos |
Non-root USER app |
Container security baseline; the app needs no privileges |
COPY manifests before source |
Docker layer caching: dep install only reruns when pyproject.toml/uv.lock change, not on every code edit — the difference between 30 s and 5 min builds |
--proxy-headers and FORWARDED_ALLOW_IPS |
Behind every PaaS or load balancer the real client IP arrives in X-Forwarded-For. uvicorn applies --proxy-headers by default, but trusts it only from the addresses in --forwarded-allow-ips (default 127.0.0.1 and ::1), so until you set that to your proxy's range, logs and per-IP limits see the proxy's address (uvicorn's settings page, checked 11 November 2026). Trusting too much (*) lets clients spoof their IP, so use * only when nothing but the proxy can reach the container port |
HEALTHCHECK on /healthz |
Liveness only. Readiness (/readyz) is the orchestrator's probe concern — don't conflate them (2.7) |
| No secrets in the image | Provider keys and LLM_SERVICE_API_KEYS_JSON arrive as runtime env vars from the platform's secret store (Part 4). docker history and image layers are readable by anyone who can pull the image |
3.2 Build-time vs runtime secrets#
The cardinal rule: a secret that enters a build layer is in the image forever. RUN export KEY=..., ARG values used in RUN, .env files COPYed in — all leak into docker history and any registry that stores layers. The correct split:
| Secret | When it arrives | How |
|---|---|---|
Provider API keys (OPENAI_API_KEY...) |
Runtime | Platform secret manager → env var → SDK reads it (03.1, 3.8) |
LLM_SERVICE_API_KEYS_JSON |
Runtime | Same path; rotate by updating the secret, rolling the replicas |
| Database/cache credentials | Runtime | Same |
| Build-time values that are not secret (version, git SHA, feature flags) | Build | ARG/--build-arg is fine — they're public by definition |
For local dev, compose.yaml reads .env at run time (not build):
# compose.yaml — local dev stack (reference; not run in this lesson)
# Brings up the service plus the dependencies dev needs: Redis (shared rate
# limiter / cache / queue backend the 11.x lessons build on) and an OTel
# collector sink. This chat-only skeleton has no vector dependency, so the
# vector store stays commented out; Module 07 (RAG) owns retrieval and adds the
# store its index actually uses (pgvector shown as the common choice).
services:
llm_service:
build: .
ports: ["8000:8000"]
env_file: .env # runtime secrets, never baked in
environment:
LLM_ENVIRONMENT: dev
LLM_LOG_LEVEL: DEBUG
LLM_CORS_ORIGINS: '["http://localhost:3000"]'
# Point provider calls at a local stand-in for key-free practice:
# OPENAI_BASE_URL: http://host.docker.internal:11434/v1 # Ollama (03.1, Part 12)
depends_on: [redis]
# For compose dev only; production uses the platform's probe config.
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request;urllib.request.urlopen('http://127.0.0.1:8000/healthz')"]
interval: 15s
timeout: 5s
retries: 5
redis:
image: redis:7-alpine # shared limiter/cache/queue backend
ports: ["6379:6379"]
# Optional: an OTLP collector so 11A.1's tracing has somewhere to send spans.
# otel-collector:
# image: otel/opentelemetry-collector:0.1xx-contrib # pin a real tag
# ports: ["4317:4317", "4318:4318"]
# volumes: ["./otel-collector-config.yaml:/etc/otelcol/config.yaml"]
# Optional: a vector store, uncommented by whichever lesson first needs one
# (07's RAG index). pgvector = Postgres + vectors in one service.
# pgvector:
# image: pgvector/pgvector:pg17
# environment:
# POSTGRES_USER: dev
# POSTGRES_PASSWORD: dev-only
# POSTGRES_DB: llm_service
# ports: ["5432:5432"]
# volumes: ["pgdata:/var/lib/postgresql/data"]
#
# volumes:
# pgdata:3.3 .dockerignore and image hygiene#
# .dockerignore — keep the build context small and secret-free
.git
.github
.env
.env.*
!.env.example
__pycache__
*.pyc
.pytest_cache
.mypy_cache
.ruff_cache
.venv
venv
tests/
docs/
*.md
Dockerfile
compose.yaml
.dockerignore
nginx/Two effects: smaller build context (faster COPY, smaller cache keys) and a hard guarantee no .env or VCS data can be COPYed in by accident. The !.env.example exception keeps the template copyable if you want it in the image for docs — usually you don't need it at all.
Part 4: Configuration and secrets#
4.1 12-factor config#
The 12-factor app rule — config in the environment, not in the code — is what makes the same image promotable dev → staging → prod. settings.py (2.2) is that rule in Pydantic: every deployment difference is an env var, the image is identical everywhere. The practical checklist:
- ✅ Model aliases, timeouts, limits, CORS origins, log level: env vars via
LLM_* - ✅ Provider keys: env vars the SDKs already read
- ❌ Never:
if environment == "prod"branches in business logic — that's config pretending to be code - ❌ Never: prompts or model names hard-coded — they are config too (4.4)
4.2 Secret managers#
| Option | What it is | When to use |
|---|---|---|
| Cloud-native (AWS Secrets Manager, GCP Secret Manager, Azure Key Vault) | Managed, IAM-scoped, audit-logged, integrates with the platform's env-var injection | Default choice on any cloud PaaS — zero extra infra |
| HashiCorp Vault | Self-hosted or HCP; dynamic secrets, leases, fine-grained policies | Multi-cloud or strict self-hosting requirements |
| SOPS / git-crypted secrets | Encrypted files in git, decrypted at deploy | Small teams, secrets-as-code workflow |
| Doppler / 1Password Secrets Automation | Hosted secret managers with CLI/SDK injection | Teams wanting a vendor-neutral secret UI |
The pattern is always the same: the platform fetches the secret at container start and injects it as an env var; your code reads os.environ (via the SDK or Settings) exactly as in dev. Keyless alternatives — workload identity federation (OpenAI, Anthropic) or cloud IAM roles (Bedrock, Vertex, Azure) — eliminate the long-lived key entirely where supported; 03.1, 3.8 covers them.
4.3 Key rotation without downtime#
Provider keys leak (logs, screenshots, a bad commit). Rotation that doesn't drop traffic:
- Issue the new key in the provider console alongside the old (providers support multiple active keys).
- Update the secret, roll the replicas: put the new key in the secret-store entry — providers let you keep the old key active while you switch — then trigger a rolling deploy (zero downtime by definition). There is no
*_NEWfallback variable: the SDKs read exactly the env var named inapi_key_env, so "both keys at once" means two deployments at different rollout stages, not one process holding two secrets. - Verify via a canary call or the readiness probe, then revoke the old after a safety window (hours–days, depending on cache TTLs).
LLM_SERVICE_API_KEYS_JSONrotates the same way: it's a JSON map, so add the new tenant key, roll, remove the old.
4.4 Model names and prompts as configuration#
Two kinds of "config" people forget:
- Model selection is already config:
LLM_DEFAULT_MODELpoints at an alias inmodels.yaml(03.11, Part 7), so "which model servesfast" is a registry edit, not a deploy. Per-requestmodeloverrides come from the API caller; your allow-list of aliases is a settings concern. - Prompts are config too. 04.10 builds the prompt library (
promptlib,aliases.yaml,PromptSpec): prompts are versioned files with aliases likeprod/staging. Deploy the app and the prompt alias independently — but never let an unreviewed prompt reach prod without an eval gate (11C.2).
4.5 Feature flags#
A feature flag is a runtime switch for behaviour that ships dark: new prompt variant, new model route, a tool that's not ready. Store them in env vars for simple cases (LLM_FLAGS_NEW_ROUTER=1), a flag service (LaunchDarkly, Flagsmith, Unleash — verify current options) when you need per-tenant or percentage rollouts. The deployment rule: flags decouple deploy from release — ship code with the flag off, enable per environment, ramp, remove the flag and dead code later. 11C.2 owns flag-driven prompt/model rollouts in CI.
Part 5: Scaling#
5.1 Stateless by design#
The service holds no durable state: conversations live client-side or in your store, jobs live in app.state.jobs (per-process — the seam for a shared store), the limiter is per-process. That means any replica can serve any request — the property that makes horizontal scaling trivial. The moment you add in-memory session state (WebSocket affinity, in-process caches that must agree), you inherit the hard problems: sticky sessions, cache coherence, drain-aware deploys. Keep the default stateless; reach for state only with a reason and a consistency story.
5.2 Workers vs processes vs async#
Three knobs, three different axes:
| Knob | Axis | LLM-service answer |
|---|---|---|
| Async (one event loop) | Concurrency within a process | The default: hundreds of streams per process because it's I/O-bound |
Workers (--workers N, gunicorn -w) |
Processes per machine | Only for CPU-bound work or to isolate a crash; multiplies per-process state (2.13) |
| Replicas (platform autoscaling) | Machines | The real scale axis: add containers, each stateless |
5.3 Autoscaling signals that matter#
CPU-based autoscaling is wrong for LLM services: a process holding 500 streams uses ~0% CPU. The signals that reflect real load:
| Signal | Where it comes from | Notes |
|---|---|---|
| Concurrent connections / in-flight requests | Platform metric (Cloud Run concurrency, ACA HTTP scaler, ALB RequestCount) |
The closest proxy for "open streams" — your best default |
| Queue depth | Your job queue's pending count | For worker autoscaling, not the API tier |
| Custom metric: open streams / provider concurrency | Your /metrics endpoint (11A.2) |
Most accurate; requires the platform to scale on custom metrics (K8s HPA external metrics, ACA KEDA, Cloud Run can't natively) |
| CPU/memory | Platform default | Only a backstop — a memory leak or JSON-parsing spike, not load |
Cloud Run scales on concurrency (default ~80 per instance); ACA scales on HTTP requests via KEDA (+1 replica per N concurrent requests, configurable); K8s HPA needs a custom metric for stream count. Fly.io's soft_limit/hard_limit on Machines is the same idea manually tuned. Tune the signal to "concurrent requests", not "requests per second" — RPS lies for long-lived streams.
5.4 Provider connection limits#
Your service is a client of the providers too. Each replica holds its own connection pool to OpenAI/Anthropic/Gemini/OpenRouter; N replicas × M workers = N×M pools hammering the same rate limits. Manage it:
- Bounded concurrency per provider: the
TenantLimiterpattern, applied per-upstream — cap simultaneous calls per provider key so one feature can't exhaust the account's rate limit for everyone (03.9, 4.7). - Shared limiter in Redis for fleet-wide caps (11C.3 builds it).
- Watch 429s as a scaling signal: sustained rate-limit errors mean you're over-provisioned relative to provider quota — scale down or ask for a tier upgrade, not up.
5.5 Queue plus worker for async jobs#
When work outgrows asyncio.create_task (2.9), the pattern is universal: API enqueues, workers consume. The queue decouples "accept the request" from "do the work" — workers scale independently, retries and dead-lettering live in the queue, and the API stays fast.
| System | Model | Best fit |
|---|---|---|
| Celery (5.7) | Task queue + broker (Redis/RabbitMQ) + workers | Mature, batteries-included; heavier ops |
| RQ (3.0) | Redis-backed Python task queue | Simple, Redis you likely have anyway |
| Dramatiq (2.2.1) | Redis/RabbitMQ task queue, simpler than Celery | Middle ground |
| arq (0.28) | Async-native Redis queue | Fits this async codebase naturally |
| Temporal (1.35) | Durable workflow engine | Long-running, multi-step, must-not-lose jobs (sagas, retries with state) |
| Cloud Tasks / SQS | Managed queues | Serverless workers, no broker to run |
The migration path from 2.9's InMemoryJobStore: keep POST /v1/jobs returning 202 + JobStatusOut; swap the store for Redis/DB and create_task for "enqueue message". Workers run python -m llm_service.worker — the same image, different command — consuming jobs and calling client.acomplete. 03.9, Part 11 owns the job-design discipline (deterministic IDs, manifest, idempotent steps); 05.9, 6.2 compares the same libraries for ingestion.
5.6 Backpressure and load shedding#
When load exceeds capacity, the choices are: queue it, reject it fast, or degrade it. 11C.3 owns circuit breakers and load shedding; deployment's part:
--limit-concurrency/ platform max concurrency is the crude shed: 503 immediately rather than accept-then-timeout.- The tenant limiter sheds per-customer before global saturation.
- A bounded job queue sheds by rejecting submissions when full ("queue depth > N → 429 with Retry-After"), not by letting jobs pile up invisibly.
- Never shed silently: a shed request must be a fast, honest 429/503 with
Retry-After, logged and counted — a timeout after 30 s is worse than an instant 503 (the caller retries into the same wall).
5.7 Cold starts and warm-up#
Scale-to-zero and scale-from-zero both pay a cold start: container pull + process boot + (for LLM services) client/pool warm-up. Fly.io documents "about 2 seconds or more" for a cold machine (Fly docs, checked 12 November 2026); serverless is similar or worse; always-on containers avoid it entirely.
Mitigations, cheapest first:
min_instances/min_machines_running> 0 for latency-sensitive endpoints — pay for one warm replica.- Suspend vs stop (Fly.io): suspended machines resume in hundreds of ms vs ~2 s for stopped.
- Slim images (3.1) — pull time dominates cold start.
- Lazy vs eager init: build the LLM client in lifespan (2.3) — it's lazy inside
LLMClientanyway (adapters build on first use), so first request pays SDK client setup. A warm-up call on startup (/readyzhitting a trivial completion) hides it — but costs a real API call; use a cheap model or skip it. - Provisioned concurrency (Lambda, some PaaS) — pay to keep warm instances.
5.8 Multi-region and data residency#
LLM calls cross the public internet to provider endpoints; your service can be regional. The constraints:
- Data residency: if tenant data can't leave a region, the provider endpoint must also be regional (OpenAI data-residency endpoints, Gemini regional endpoints, Bedrock/Vertex regional) — not just your container. 02.9, Part 9 covers provider privacy; 11C.3 covers fallback chains that must not violate residency.
- Latency: put replicas near users and near the provider's nearest endpoint — a US-East service calling a US-West-only model is a transcontinental hop per stream.
- State that must follow the user: job stores, conversation stores — replicate or accept regional affinity.
5.9 Cost controls on autoscaling#
Autoscaling multiplies everything: more replicas = more provider concurrency = more spend. The guardrails:
- Max replicas cap — the ultimate spend ceiling.
- Budget alerts (11B.1, 11A.2) on cost per request and total spend; a runaway autoscaler is a billing incident.
- Scale-down lag: stream-heavy services hold connections for minutes, so scale-down is slow by nature — don't expect instant cost drops.
- Right-size the floor:
min_instancesis your baseline spend; set it to actual minimum load, not "just in case".
5.10 Load testing before launch#
Don't discover the 60-second cliff or the provider rate limit in production. 11A.2 owns the load-testing detail (Locust/k6, streaming-specific patterns); the deployment checklist:
- Sustained concurrent streams at expected peak + 2×.
- A reasoning-model-length stream through the full proxy chain (nginx/ALB/Cloudflare), not just localhost.
- A deploy during load — watch how streams drain.
- Provider rate-limit behaviour at your concurrency ceiling.
5.11 Sync or async: choosing the deployment shape#
You have now met three ways to serve one piece of LLM work. They differ in who waits, and where the work lives, so they scale, fail and deploy differently. A sync shape keeps the caller's connection open until the work is done. An async shape answers at once and does the work somewhere else.
| Sync stream (2.8) | Async, in-process (2.9) | Async, queue + worker (5.5) | |
|---|---|---|---|
| Client contract | One request, a stream of SSE events back | POST returns 202 plus a job ID; poll GET or receive a webhook |
The same 202 contract as 2.9 |
| Connection held | The whole generation | Milliseconds | Milliseconds |
| Who waits | A person, watching tokens appear | A person or a system, coming back later | The same |
| Timeout exposure | High: every proxy idle timeout and the platform's maximum duration apply (2.15) | Low on the request path; the job needs its own deadline | Low; the worker's timeout is yours to set |
| Failure after work starts | An SSE error event; the 200 is already sent |
Job state failed |
The queue retries, then dead-letters |
| Survives a restart or deploy | No: the stream dies unless you drain (6.2) | No: job state lives in this process's memory | Yes: the job stays in the queue for another worker |
| Scale signal | Concurrent streams (5.3) | The same API replicas, now busier | Queue depth, on the worker tier (5.3) |
| Backpressure | A fast 503 or 429 at the concurrency limit (5.6) |
A per-tenant cap on active jobs | A bounded queue that rejects new submissions when full |
| Retry safety | A retried stream bills again | Idempotency-Key on submit (2.10) |
The same key plus idempotent worker steps |
| Best for | Interactive chat and anything a person reads as it arrives | One instance, prototypes, work of a few seconds you cannot stream | Batches, reports, long agent runs, anything that must not be lost |
How to pick, in order:
- Is a person watching the answer form? Use the sync stream. Time to first token is the experience, and a job queue adds delay the user feels.
- Can the work run longer than your shortest timeout (often about a minute through a proxy), or must it survive a deploy? Use async with a queue. Do not stretch a stream past the 60-second cliff with pings and hope.
- Is it a prototype on one instance? The in-process jobs of 2.9 are honest for the shape. Move to a queue the day you run a second replica or care about losing work on restart.
- Is the caller a machine? Prefer async with a webhook or polling, even for short work: machines do not need tokens as they arrive, and the queue absorbs their bursts.
Most real services use both. The chat endpoint streams, and the "export this report" endpoint is a job. They share the same image and the same settings, and only the scale signal differs: scale the API on concurrent streams and the workers on queue depth. Retries multiply cost in every shape, so keep one retry owner (11C.3) and never let a queue retry on top of a client retry on top of a provider retry.
Part 6: Release strategies#
6.1 The release pipeline shape#
flowchart LR
subgraph ci ["CI (11C.2 owns detail)"]
PR["PR: lint, types, unit tests,<br/>eval smoke suite"] --> B["Merge: full evals,<br/>cost report, regression gate"]
B --> IMG["Build + scan image<br/>tag: git-sha"]
end
subgraph deploy ["Deploy"]
IMG --> STG["Staging deploy<br/>post-deploy smoke + canary evals"]
STG --> PROG["Progressive rollout<br/>flags / traffic %"]
PROG --> PROD["Production<br/>monitors + auto-rollback triggers"]
end
PROMPT["Prompt registry<br/>aliases.yaml (04.10)"] -.->|independent promotion| PROG
PROD --> OBS["Dashboards + alerts (11A.2)"]The artefacts: an image tagged by git SHA (immutable, rollback = redeploy old tag), a deploy workflow, and — separately — prompt/model changes promoted through their own gates (11C.2).
6.2 Rolling updates and draining#
The default: replace replicas gradually. For an SSE service the hazard is killing in-flight streams mid-sentence. The mitigations stack:
- Readiness flip first (2.14):
/readyz→ 503 drains new traffic while streams finish. - Drain window ≥ longest stream: platform grace period +
--timeout-graceful-shutdown. - Client reconnect: browsers/
fetchstreams that drop should reconnect and resume or restart — your event protocol'sidfields (03.3, 11.2) enable resume where the provider supports it (OpenAI background responses, Gemini Interactionslast_event_id). - Accept partial answers: a stream cut at 95% is a degraded-but-honest outcome; log it as
abandoned, noterror.
6.3 Blue/green and canary#
| Strategy | How | LLM-service fit |
|---|---|---|
| Blue/green | Two full environments; switch the load balancer | Clean rollback (flip back), but doubles infra cost; best for risky releases |
| Canary | New version gets 1–5% of traffic, compare metrics, ramp | The right default for prompt/model changes: compare quality metrics on real traffic before committing |
| Rolling | Gradual replica replacement | Default for routine deploys; combine with draining |
| Shadow | New version processes real requests silently, results compared not shown | Safest for eval-gated prompt/model swaps (02.10's shadow-traffic advice) |
Azure Container Apps and Cloud Run both support traffic splitting between revisions natively — canary is a config change, not a second environment. The decision input is what changed: a bugfix → rolling; a new prompt/model → canary with eval metrics; a schema/API change → blue/green or versioned routes.
6.4 Database and index migrations#
LLM services usually have less DB surface than CRUD apps, but the vector index and conversation store still migrate:
- Migrate before deploy or after? For additive changes (new column, new index version): deploy code that tolerates both, migrate, then deploy the strict version. For destructive changes: expand-contract (add new → dual-write → backfill → switch reads → drop old).
- Vector index changes are the LLM-specific case: embedding-model or chunking changes require reindexing — 05.9, Part 5 owns blue/green indexes and alias flips: build the new index beside the old, shadow-evaluate, flip the alias, keep the old for rollback. Never reindex in-place on the live alias.
- Conversation/history schema changes ride the same expand-contract rule.
6.5 Feature flags for prompts and models#
The release unit for an LLM feature is often not code — it's a prompt version or model alias. Flags make those promotable independently: prompt_alias=prod vs prompt_alias=canary, model_route=fast vs model_route=smart. 11C.2 owns the CI machinery; the deployment rule is: every prompt/model change goes through the same promote-cautiously path as code — canary traffic, eval gate, rollback = flip the alias back (seconds, not a redeploy).
6.6 Rollback plans and zero-downtime config#
- Code rollback = redeploy the previous image tag. Keep the last N tags; never delete the one you're rolling back to.
- Config rollback = the previous env var values. Treat config changes with the same care as code: a
LLM_DEFAULT_MODELflip is a release. - Zero-downtime config changes: secret rotation and flag flips are designed to be rolling-safe (4.3); anything requiring coordinated multi-service change gets a maintenance window or a two-phase deploy.
- The rollback test: if you can't answer "how do I undo this in <5 minutes?" before deploying, don't deploy.
6.7 Environment parity#
Dev, staging and prod should run the same image with different config — never "works on staging" because staging runs different code. Practical parity:
- Same
Dockerfile, sameuv.lock, same base image. - Different env vars only:
LLM_ENVIRONMENT, keys (per-env provider keys!),LLM_CORS_ORIGINS, log level. - Cheap/fake models in dev: point
OPENAI_BASE_URLetc. at a local stand-in (03.1, Part 12) or themodels.local.yamlregistry so dev costs nothing and needs no keys. Staging uses real keys but low rate limits and small eval traffic. - Staging mirrors prod's proxy chain: if prod sits behind nginx+ALB+Cloudflare, staging should too — otherwise the SSE-through-proxies bugs only appear in prod.
6.8 The deploy workflow (reference)#
# .github/workflows/deploy.yml — REFERENCE deploy job (11C.2 owns the full CI design)
# Builds the image, pushes to a registry, deploys to staging, smoke-tests, then
# promotes to prod behind a manual approval. Provider keys come from environment
# secrets — never PR-visible (fork-PR safety is 11C.2's subject).
name: deploy
on:
push:
branches: [main]
workflow_dispatch:
jobs:
build-and-deploy:
runs-on: ubuntu-latest
environment: production # required reviewers gate this environment
permissions:
contents: read
id-token: write # OIDC to cloud — no long-lived cloud keys in CI
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.3.3 # exact tag: the project publishes no floating v10
with: { version: "latest-known" } # newest uv with published checksums
- run: uv sync --frozen
- run: uv run pytest -q # unit tests with fakes — no keys needed
- name: Build image
run: docker build -t llm-service:${{ github.sha }} .
- name: Push image
run: |
docker tag llm-service:${{ github.sha }} ${{ vars.REGISTRY }}/llm-service:${{ github.sha }}
docker push ${{ vars.REGISTRY }}/llm-service:${{ github.sha }}
- name: Deploy to staging # platform-specific: gcloud run deploy,
run: ./scripts/deploy.sh staging ${{ github.sha }} # ./deploy.sh prod ... etc.
- name: Smoke test staging
run: ./scripts/smoke.sh https://staging.example.com
- name: Deploy to production
run: ./scripts/deploy.sh prod ${{ github.sha }}
- name: Smoke test production
run: ./scripts/smoke.sh https://api.example.comPart 7: Infrastructure as code and managed platforms#
Reference
7.1 IaC awareness#
For anything beyond a single PaaS service, infrastructure is described as code: Terraform (HCL, cloud-agnostic-ish), Pulumi (real languages — TypeScript/Python), AWS CDK (CloudFormation via code), or the platform's own config (fly.toml, render.yaml, gcloud run flags in CI). The deployment lesson for an LLM service: your IaC needs to express the things that differ per environment — service config, env vars (secret references, never values), concurrency limits, probe paths, domain/ingress — because "click-ops" config drifts and can't be reviewed. A minimal Cloud Run service definition:
# main.tf — Terraform, Cloud Run service (reference, abridged)
resource "google_cloud_run_v2_service" "llm" {
name = "llm-service-${var.env}"
location = var.region
template {
scaling { min_instance_count = var.min_instances
max_instance_count = var.max_instances }
containers {
image = var.image_tag # immutable SHA tag
ports { container_port = 8000 }
env { name = "LLM_ENVIRONMENT" value = var.env }
env { name = "OPENAI_API_KEY" value_source {
secret_key_ref { secret = "openai-api-key" version = "latest" } } }
startup_probe { http_get { path = "/readyz" } }
liveness_probe { http_get { path = "/healthz" } }
}
}
}Note secret_key_ref: Terraform references the secret, the platform injects the value at runtime — the value never appears in state files or code.
7.2 Managed AI platforms#
When the LLM call itself should be managed: AWS Bedrock, Google Vertex AI, Azure AI Foundry offer model access inside the cloud's IAM/VPC boundary — no provider API keys in your env at all, data stays in-account, compliance inherits the cloud's posture. Trade-offs: fewer models than aggregators, cloud lock-in, and you still write the same service. 03.1, Part 11 covers calling them; the deployment question is whether the managed endpoint removes enough key/egress management to justify the narrower model choice. For most teams the provider_agnostic client + secret manager is more flexible; for regulated workloads the managed platform can be the compliance answer.
7.3 Private networking and egress#
Your service makes outbound calls to provider APIs — that's egress, and it's a security surface (Module 12 owns the treatment):
- VPC/private endpoints where the provider offers them (Bedrock/Vertex/Azure private link) keep traffic off the public internet.
- Egress allow-listing: restrict outbound to known provider domains/IPs; an LLM service that can reach arbitrary hosts is an exfiltration path if prompt injection succeeds.
- No inbound beyond the API port: the service needs no other listeners; default-deny ingress.
- DNS/egress proxies for inspection where compliance requires.
7.4 GPU deployment#
Serving open-weight models needs GPUs and long-lived model processes — a different deployment shape entirely (vLLM/Ollama servers, not request handlers). 11C.6 owns it; the connection point is that your llm_service can route to a self-hosted OpenAI-compatible endpoint via base_url in models.yaml — same client, same service, different upstream.
Part 8: Frontend integration (brief)#
Deep-dive
The browser never holds provider keys — it calls your /v1/chat/stream with your auth (03.3, 11.1). Deployment concerns specific to the frontend path:
- CORS is configured, not wildcard:
LLM_CORS_ORIGINSlists exact origins;Authorizationis not CORS-safelisted so preflights must succeed (2.2, 03.3 11.7). - Per-user limits, not just per-tenant: a tenant's API key may be shared; real per-user quotas need the user identity in the token (JWT claims — Module 12) mapped through
Principal. fetch()+ReadableStreamoverEventSourcefor POST bodies andAuthorizationheaders (03.3, 11.5); the event protocol from 2.8 is the contract.- The website/app phase of this project builds the actual UI; this lesson's job is that the API it calls is deployable, authenticated, limited and streaming correctly.
Failure gallery#
Deployment failures rarely announce themselves in staging — they appear at the intersection of long-lived streams, billing and platform defaults. The five scale-only failures from 1.5 are the first rows; the rest collect the deployment-specific traps from Parts 2–7.
| Failure | Symptom | Root cause | Detection | Fix |
|---|---|---|---|---|
| The 60-second cliff | A stream dies silently after ~60 s of model "thinking" with no bytes sent | Proxy, ALB and Cloudflare idle timeouts kill quiet connections; reasoning phases emit nothing | Works on localhost, dies in production; no keep-alives configured |
Ping under the shortest idle timeout; raise proxy_read_timeout; X-Accel-Buffering: no (2.15) |
| The billed orphan | The user hangs up; the generation runs to completion and bills in full | Lambda RESPONSE_STREAM and Cloud Run 504s don't stop server-side work |
Billed tokens far exceed delivered tokens; the client's abandoned hook fires |
Cancel upstream on disconnect; record billed partials; idempotency keys for jobs (2.8, 2.9) |
| The deploy massacre | In-flight streams die mid-sentence on every release | Rolling updates and revision swaps don't drain open connections | Error spike and partial answers aligned with deploy timestamps | Readiness-flip → grace period → SIGTERM drain (6.2) |
| The cold-start stampede | First requests after idle queue behind ~2 s platform wakes, multiplied by a herd | Scale-to-zero wake latency compounds when many requests arrive together | Latency spike at burst-onset after idle periods | Minimum instances or a warm pool for known peaks (5.7) |
| The buffering proxy | SSE headers arrive, then the body lands all at once — or never | proxy_buffering on collects the whole response; every hop has its own idle timeout |
Works locally, broken through nginx/ALB/Cloudflare | proxy_buffering off plus X-Accel-Buffering: no; keep-alives under the shortest timeout (2.15) |
| The baked-in secret | A provider key is recoverable by anyone who can pull the image or read the repo | Secrets placed in the Dockerfile or a committed .env end up in image layers |
docker history, image pull access, repo secret scanning |
Runtime secret-manager env vars only; rotation is a secret update + rolling deploy (3.2, 4.2) |
| The CPU-blind autoscaler | The fleet reports ~0% CPU while thousands of streams pile up unserved | Async workers are I/O-bound; CPU sees an idle fleet | Concurrency or queue depth rising while CPU stays flat | Scale on concurrency or queue depth; CPU only as a backstop (5.3) |
| The multiplied limiter | The effective rate limit is N×M× the configured value and triggers far too late | Per-process limiters, job stores and pools multiply across workers × replicas | The configured limit never bites at the expected load | Shared limits in Redis or at the gateway; one worker per replica unless CPU-bound (2.13, 5.4) |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "An LLM endpoint is just another API route." | Requests last seconds-to-minutes, often hold a stream open, and each one bills real money. Timeouts, connection lifetime and cost are first-class deployment concerns (Part 1). |
| "Lambda / serverless is fine for the chat endpoint." | Only with RESPONSE_STREAM + a custom runtime for Python, and streamed responses keep billing after the client disconnects. Containers are simpler for long generations (1.4). |
| "Scale on CPU like a normal web app." | Async LLM workers sit at ~0% CPU while holding hundreds of streams. Scale on concurrency/queue depth, not CPU (5.3). |
"--workers 8 gives us 8× throughput." |
It gives 8× processes — and 8× the per-process limiters, job stores and connection pools. LLM services are I/O-bound; one async worker already multiplexes hundreds of streams (2.13). |
| "Put the API key in the Dockerfile/env file." | Anything in an image layer or .env committed to git is recoverable forever. Secrets arrive at runtime from a secret manager (3.2, 4.2). |
| "A 504 means the request failed." | On Cloud Run the container keeps processing after the 504; on Lambda a disconnected stream keeps billing. Design for "client gave up, work continued" (1.5). |
| "Retries are safe because the SDK handles them." | /v1/chat is not idempotent: a client retry is a new billed generation that may differ. Retries belong inside the client layer; the endpoint needs idempotency keys for jobs (2.9). |
| "nginx will just pass the stream through." | proxy_buffering on collects the whole body; proxy_read_timeout 60 s kills silent reasoning gaps. You need X-Accel-Buffering: no/proxy_buffering off and pings under the shortest idle timeout (2.15). |
| "Health and readiness are the same probe." | /healthz = process alive (restart it); /readyz = serve traffic (drain it). Conflating them causes deploys that kill streams or restart loops on a slow dependency (2.7). |
| "Blue/green is always safer than canary." | Blue/green doubles infra and switches 100% at once; canary exposes the new version to 1–5% and compares real metrics first. Match the strategy to what changed (6.3). |
| "Autoscaling saves money." | It multiplies spend: more replicas = more provider concurrency = bigger bills. Cap max replicas and alert on cost, or the scaler becomes a billing incident (5.9). |
| "The prompt is just a string in the code." | Prompts are versioned, eval-gated config promoted independently of code through aliases — a prompt change is a release, not an edit (4.4, 11C.2). |
| "Per-process rate limits work in production." | N workers × M replicas = N×M× the intended limit. Shared limits need Redis or the gateway (2.3, 5.4). |
Key takeaways#
- LLM requests are long-lived, streamed, expensive and bursty — deployment must reason about connection lifetime and cost, not just CRUD-shaped request/response.
- Pick the target by its streaming and timeout behaviour, not its brand: containers on a PaaS (Cloud Run, ACA, Fly.io) are the default; serverless only for thin/fast endpoints or carefully configured Lambda/Workers; K8s when you already run it; VMs for GPU/self-hosted.
- The production service is a composition root:
create_app()wirespydantic-settings, an injectedLLMClientbuilt once in lifespan, auth, per-tenant limits, routes, and error mapping — all testable with fakes. - Two SSE error boundaries: failures before the first byte are HTTP statuses (prime the stream); failures after are
errorevents. Disconnects cancel upstream and record billed partials via the client'sabandonedhook. - Secrets are runtime, never build-time: provider keys and service keys come from a secret manager as env vars; rotation is a secret update + rolling deploy.
- Scale on concurrency, not CPU; hold concurrency slots for the whole stream; bound provider connections per replica and share limits via Redis/gateway at fleet scale.
- Async jobs are accept-and-poll: 202 + job ID +
GET /v1/jobs/{id}with idempotency keys (replays return the job's current status);callback_urladds a signed push option. The in-memory store is the seam for Redis/Celery/arq/Temporal/Cloud Tasks. - Releases must drain streams: readiness-flip → grace period → SIGTERM; canary/blue-green for prompt and model changes; vector-index changes go through blue/green aliases, never in-place.
- Every proxy hop can break SSE: nginx buffering, ALB/Cloudflare idle timeouts — keep-alives under the shortest timeout and
X-Accel-Buffering: noare table stakes. - Config is the release surface: model aliases, prompts, flags and secrets are promoted through the same canary/eval/rollback discipline as code (11C.2).
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| PaaS | Platform as a Service: run a container image without managing servers (Cloud Run, ACA, Fly.io, Render, Railway) |
| Serverless function | Per-request ephemeral compute with no managed server (Lambda, Vercel Functions, Cloudflare Workers) |
| Lifespan | FastAPI's startup/shutdown hook where expensive resources (the LLM client) are built once and closed |
| App factory | create_app() pattern: build the app in a function so tests can inject fakes and config |
pydantic-settings |
Settings class parsed once from env vars/.env into typed config |
| Dependency injection | FastAPI Depends(): run a function per request to supply auth, settings, clients |
| Principal | The authenticated caller's identity (tenant id) resolved from a bearer token |
| Token bucket | Rate-limit algorithm: tokens refill at a steady rate, each request spends one |
| In-flight slot | A counted unit of concurrent work held for a request's whole life, including streams |
| Idempotency key | Client-supplied key making a retried submission return the same job, not a second run |
| Accept-and-poll | Async job pattern: 202 + job ID immediately, poll GET for the result |
| Webhook (job callback) | Push alternative to polling: worker POSTs the finished job to a client-supplied URL, HMAC-signed |
| Stream priming | Pulling the first forwardable stream event before the SSE response starts, so pre-byte failures stay HTTP statuses |
| Health vs readiness probe | /healthz (process alive → restart) vs /readyz (serve traffic → drain) |
| Graceful shutdown / draining | Stop new traffic, let in-flight requests finish before SIGKILL |
| Multi-stage build | Dockerfile pattern: build deps in one stage, copy only artifacts to a slim runtime |
.dockerignore |
Keeps build context small and secrets/VCS out of image layers |
| 12-factor config | Config in environment variables, identical image across environments |
| Secret manager | Managed store injecting secrets as env vars at runtime (cloud-native, Vault, SOPS, Doppler) |
| Key rotation | Issuing a new credential and revoking the old without downtime |
| Blue/green deployment | Two environments; switch traffic all-at-once, instant rollback |
| Canary deployment | Route a small traffic share to the new version, compare, then ramp |
| Shadow traffic | New version processes real requests silently for comparison |
| Autoscaling signal | The metric that triggers scale-out — concurrency, not CPU, for LLM services |
| Cold start | The delay before a stopped/suspended instance serves its first request |
| Queue + worker | Decouple accepting work (API) from doing it (workers consuming a queue) |
| Backpressure / load shedding | Rejecting or queueing excess load fast rather than accepting-then-timing-out |
| Sync vs async deployment shape | Sync keeps the caller's connection open until the work is done (a stream); async answers at once with a job ID and does the work elsewhere (in-process or queue + worker) |
| Expand-contract migration | Add-new → dual-write → backfill → switch → drop-old, for zero-downtime schema changes |
| Private networking / egress | Keeping service↔provider traffic off the public internet / restricting outbound destinations |
| OIDC in CI | OpenID Connect federation: CI assumes a cloud role without stored keys |
All terms are also collected in the glossary.
Exercises#
- Error mapping (2.6): add a test that a
ContextTooLongmaps to 400 and aQuotaExceededmaps to 503 — then explain to a colleague why the provider-account errors aren't 401/403. - Priming (2.8): make
FakeClient.astreamraiseRateLimitedon the second event instead of the first. What status does the client see, and what event does the stream emit? Explain the boundary. - Limiter (2.6): write a test that fires 25 concurrent
/v1/chatrequests withmax_concurrent=20and asserts exactly 5 get 429 — then explain why the real limit in prod would be higher. - Jobs (2.9–2.10): submit two jobs with the same
Idempotency-Keybut different bodies. What should happen, and is that the right behaviour? Argue both sides. - Dockerfile (3.1): reorder the
COPYlines so a code-only change doesn't reinstall dependencies, then explain which layer cache key changed. - SSE proxy (2.15): given an nginx config without
proxy_buffering off, trace what the browser sees for a 30-second stream. Then add a: pingevery 20 s and explain why it still fails. - Decision table (1.4): your app streams 90-second reasoning answers to 10k daily users on a $50/month budget. Pick a target and justify it against two alternatives.
- Config (4.3): write the rotation runbook for
LLM_SERVICE_API_KEYS_JSONas numbered steps a junior engineer could follow at 3 a.m. - Webhooks (2.10):
callback_urlis client-supplied. List three abuse cases (SSRF to internal hosts, spoofed delivery, replay) and which layer mitigates each — then explain why polling stays the default contract.
Hints for the exercises
- Build
RateLimited-style cases withContextTooLong("too long", provider="openai", status=400)andQuotaExceeded("out of credit", provider="openai", status=429)(note: a 429 from the provider is our quota problem here). Use therunning(...)helper from 2.16 so the app's lifespan has started. The caller cannot fix our provider account, so 401/403 would send them debugging the wrong key. - Write a
FakeClient.astreamthat yields aTextDeltafirst and raises on the second pull. Priming already pulled the first event, so the response starts with200and the failure arrives after it as anerrorSSE event with"retryable": true. Raise on the first pull instead and the client sees a real429. That asymmetry is the boundary. FakeClient.acompletereturns instantly, so requests never overlap. Make the fakeawait asyncio.Event().wait()(or sleep) until the test releases it, fire 25 requests withasyncio.gather, then assert 20 are in flight and 5 returned 429 before releasing. In production the same tenant is spread across replicas and workers, so the effective limit isN × M × 20(2.13).- As written, the second submission returns the first job and silently ignores the different body. For a retry that is right; for a client bug it hides a mismatch. Common practice (for example in payment APIs) is to store a hash of the request body with the key and answer
422or409when the same key arrives with a different body. Argue both: simplicity and safe retries vs catching client mistakes. - Copy
pyproject.tomlanduv.lockfirst, runuv sync(the dependency layer), and only thenCOPY llm_service/. A code-only edit then changes theCOPY llm_service/layer's cache key but not the dependency layer's. - Without
proxy_buffering offnginx holds the body until the upstream response completes or its buffers fill, so the browser sees nothing for 30 s and then everything at once. A 20 s ping does not help because the pings are also buffered: they only prove the connection is alive to nginx, not to the browser. - A defensible answer: a container platform (Cloud Run or similar) with scale-to-zero and a small
max_instancescap; alternatives: Lambda with response streaming (billed for the full duration even after disconnects) and a small always-on VM (cheapest at steady load, but you own patching and drains). Check the arithmetic: 10k users × a few requests of 90 s of held connection is a lot of concurrent seconds, so estimate peak concurrency before pricing. - Include: create the new key in the provider console; update the secret-store entry; trigger a rolling deploy; verify with a canary call and
/readyz; revoke the old key after a safety window; record who did what. For the service's own tenant keys: add the new key to the JSON map, roll, tell the tenant, remove the old key later. - SSRF: egress allow-list and URL validation including resolved IPs (Module 12). Spoofed delivery: the HMAC signature and a shared secret. Replay: a timestamp and
job_iddedupe on the receiver. Polling stays the default because it needs no inbound endpoint, no signing and no retry bookkeeping.
Check yourself#
- Name three ways an LLM request differs from a CRUD request that change deployment.Duration (seconds–minutes vs ms), connection lifetime (streams held open), and cost (real money per call, retries bill again) — plus bursty token-driven load and big payloads.
- Why does CPU-based autoscaling fail for an async LLM service?Async workers wait on I/O at ~0% CPU; CPU metrics see an idle fleet while hundreds of streams pile up. Scale on concurrency/queue depth instead.
- What are the two SSE error boundaries, and how does the route handle each?Before the first byte → HTTP status via
to_http(priming pulls the first event inside the_prime_streamdependency, before the response starts). After → SSEerrorevent, since headers are committed. - Why is
/v1/chatnot idempotent, and where should retries live?A retry is a new billed generation that may return different output. Retries belong inside the client layer (03.8's policy); the endpoint uses idempotency keys for jobs instead. - What breaks if you
COPY .envinto a Dockerfile?.envin a build layer is recoverable by anyone who can pull the image or readdocker history— keys leak permanently. - What's the difference between
/healthzand/readyz, and what goes wrong if you conflate them?/healthz= process alive (liveness → restart);/readyz= can serve traffic (readiness → drain). Conflating them causes deploys that kill live streams or restart loops on a dependency. - Which uvicorn flags matter for an LLM service and why?
--workers(process count, multiplies per-process state),--limit-concurrency(instant 503 backstop),--timeout-graceful-shutdown(drain window),--timeout-keep-alive(idle between requests),--proxy-headerswith--forwarded-allow-ips(real client IPs behind a proxy, trusted only from the proxy's address range). - Why must secrets be runtime env vars rather than build args?Build args/layers persist in the image and its history; runtime env vars from a secret manager never touch the image and rotate without rebuild.
- What does
client.astream'sabandonedhook record, and when does it fire?The abandoned, still-billed partial usage — it fires when the consumer stops reading a stream (disconnect, break, aclose). - Which three proxy/hop timeouts kill SSE, and what's the common fix?nginx
proxy_buffering/proxy_read_timeout(60 s), ALB idle timeout (60 s default), Cloudflare ~100 s window. Fix:X-Accel-Buffering: no/proxy_buffering off, keep-alive pings under the shortest timeout, raised timeouts. - When do you pick blue/green over canary for an LLM release?Blue/green when you need instant all-or-nothing rollback or a risky infra change; canary when you want to compare quality metrics on a traffic slice first (prompt/model changes).
- Why is a vector-index change a blue/green problem, not a simple migration?Reindexing is expensive and the old index must stay available for rollback — blue/green aliases let you build beside, evaluate, flip, and keep the old for instant revert (05.9 owns the pattern).
- Why does
/v1/chat/streamprime inside a dependency rather than inside the endpoint function?FastAPI commits200 OK+text/event-streambefore an async-generator endpoint's body runs, so errors inside it can only beerrorevents. A yield-dependency runs before the response starts — priming there keeps missing-key/RateLimited/UnsupportedFeaturefailures as real HTTP statuses. - An idempotent replay of
POST /v1/jobsreturns the job's current status. Why is returning"queued"for a finished job a bug?The 202 body is a status resource: a client retrying after a timeout must learn the job already succeeded (or failed), not be told "queued" — a false "queued" invites double-submits and wrong client logic.
Further resources#
- FastAPI docs: FastAPI, its Server-Sent Events tutorial, the
EventSourceResponse/ServerSentEventreference, and streaming data —yieldfrom the path operation withresponse_class=EventSourceResponse(added in 0.135.0). - Uvicorn: Settings and Deployment — workers, limits, timeouts, gunicorn notes.
- Docker: Dockerfile best practices and Compose.
- Cloud Run: Request timeout, WebSockets/streaming, Quotas.
- AWS containers: App Runner availability change (closed to new customers; points to Amazon ECS Express Mode).
- AWS Lambda: Response streaming and function URLs; ALB attributes.
- Azure Container Apps: Scaling (KEDA) and Session affinity.
- Fly.io: Autostop/autostart and Concurrency limits.
- Vercel/Cloudflare: Vercel Functions limits, Cloudflare Workers limits, Cloudflare 524.
- nginx: proxy module (
proxy_buffering,proxy_read_timeout,X-Accel-Buffering). - Job queues: Celery, Dramatiq, arq, Temporal, RQ, Cloud Tasks.
- 12-factor: 12factor.net/config; secrets: HashiCorp Vault, SOPS.
- Managed AI: AWS Bedrock, Vertex AI, Azure AI Foundry.
- Earlier in this module: 11A.1 tracing, 11A.2 metrics/SLOs, 11C.3 fallbacks/gateways, 11C.6 open-weight/local, 11C.2 CI/CD; earlier modules: 03.3 streaming, 03.8 errors/retries, 03.9 async/batch, 03.10 logging/testing, 03.11 provider-agnostic client, 04.10 prompt versioning, 05.9 ingestion pipelines.
← Module 11B: Cost, Usage and Token Management | Module 11C overview | 11C.2 — CI/CD for Prompts, Models and Evals →