{"slug": "a-production-readiness-checklist-for-llm-features-in-fastapi", "title": "A Production Readiness Checklist for LLM Features in FastAPI", "summary": "A developer published a production-readiness checklist for running LLM features inside FastAPI services, covering eval gates in CI, Pydantic-validated structured output, OpenTelemetry-based tracing, and timeout, retry and circuit-breaker fallbacks. The checklist recommends building a hand-labeled golden dataset of 50 to 200 real-traffic examples and blocking merges when eval scores drop, and argues that evals protect the behavior users care about while the rest of the list protects the system.", "body_md": "Getting an LLM feature working in a notebook is a different problem from keeping it working in production. The demo path is short: call the model, print the answer. Production adds everything the demo skips. You need evals that catch regressions, guardrails for bad input and worse output, and traces you can debug at 2 a.m. You also need a plan for when the model is down, a cost number you can defend, and secrets handled like secrets.\n\nThis is the checklist I run before an LLM feature goes live in a FastAPI service. It assumes Python, an OpenAI-compatible API or similar, and a team that will maintain the feature after launch.\n\n## \n  \n  \n  1. Evals before features\n\n\"Feels better\" is not a measurement. Before any prompt or model change ships, you want a small eval set that scores the change automatically.\n\n- Build a golden dataset from real traffic. Start with 50 to 200 examples of actual inputs and the outputs you accept. Label them by hand; quality beats size.\n- Score with code, not vibes. For extraction and classification, exact match or JSON-schema validation works. For open-ended text, use a model-graded rubric, but keep the rubric narrow and the pass threshold explicit.\n- Run evals in CI on every prompt or model change. Block the merge when the score drops. This one habit prevents most \"we tweaked the prompt and quality silently degraded\" incidents.\n- Track scores over time. A JSON file committed next to the code, or a table in your observability tool, is enough.\n\nIf you change one thing this month, make it this. Everything else on the list protects the system; evals protect the behavior users care about.\n\n## \n  \n  \n  2. Guardrails and structured output\n\nFree-form text out of a model is a liability in a typed backend. Constrain it.\n\n- Force structured output. Use JSON mode or function calling and validate the result with a Pydantic model. If validation fails, retry once with the error included, then fail loudly.\n- Validate inputs too. Length limits, allowlists, and basic PII detection before the call. A 40,000-character paste belongs in object storage, not in your context window.\n- Treat retrieved and user content as untrusted. Anything from a user or from web pages can attempt to override your instructions. Keep system instructions and retrieved data clearly separated, and never let retrieved text change which tools the model is allowed to call.\n- Set hard output limits. `max_tokens` caps runaway generations and gives you a predictable worst-case cost per call.\n\n## \n  \n  \n  3. Observability you can debug at 2 a.m.\n\nWhen a user reports \"the AI gave a weird answer yesterday,\" you need to answer fast. Four questions cover most incidents: what was sent, what came back, which model and prompt version produced it, and what it cost.\n\n- Trace the full request. OpenTelemetry-based tools (OpenLLMetry, Langfuse, LangSmith) record prompts, completions, token counts, and latency per span. Wire the trace ID into your logs so support can jump from a ticket to the exact call.\n- Log model, prompt version, and parameters. \"We deployed a new prompt at 14:00\" should be a query, not an archaeology project. Version prompts like code and log the version with every call.\n- Watch percentiles, not averages. P95 and P99 latency decide whether users bounce. Model latency varies a lot, so alert on the tail.\n- Alert on error patterns: rising validation-failure rate, fallback activations, sudden token spikes. These catch problems before users do.\n\n## \n  \n  \n  4. Fallbacks and graceful degradation\n\nThe model will be slow, rate-limited, or down. Decide the behavior before it happens.\n\n- Timeouts on every call. In FastAPI, use a client-level timeout or wrap the call with `asyncio.wait_for` . The default \"wait forever\" is a bug at production load.\n- Retry with backoff on transient errors only. Retry 429s and 5xx with exponential backoff plus jitter; do not retry 400s.\n- Circuit breaker for sustained failures. After N consecutive failures, stop calling the model for a cooldown period and take the degraded path. Without a breaker, your outage becomes the provider's outage, amplified.\n- Model fallback. Route to a second provider or a smaller model when the primary fails. The fallback answer can be simpler; slow but working beats fast but down.\n- A non-LLM escape hatch. For some features, a rules-based or cached response is an acceptable degraded mode. Write down what degraded means for your feature before launch.\n\n## \n  \n  \n  5. Cost controls that survive contact with users\n\nCosts are predictable until users arrive. Then someone pastes a book into your chat box.\n\n- Track cost per request and per feature from day one. Token usage is in every response; multiply by your rates and log it. A daily number in a dashboard beats a monthly invoice surprise.\n- Budget per request in code. Derive `max_tokens` from the response budget you can afford, and reject or truncate inputs over a token threshold.\n- Route by difficulty. Classification and extraction often work with a small, cheap model. Reserve the expensive model for the steps that need it. This is the biggest cost lever for most systems.\n- Trim context aggressively. Retrieval should return the minimum text that answers the question. Every token you send is a token you pay for.\n- Cache identical requests. Embeddings especially: identical text in, identical vector out. A cache cuts cost and latency with no quality trade-off.\n\n## \n  \n  \n  6. Wiring it in FastAPI\n\nA few notes that make the checklist cheap to adopt:\n\n- Create the model client in a lifespan handler and store it in app state. Do not create a client per request; connection pooling matters when every request waits on an external API.\n- Inject the client and config through FastAPI dependencies, so tests and evals can swap a fake model without monkey-patching half the codebase.\n- Use background tasks or a queue for anything that does not need the model result to answer. A user-facing request should wait only for what it returns.\n- If you stream, stream end-to-end with `StreamingResponse` , and record token counts from the provider's usage payload when the stream ends.\n\n## \n  \n  \n  7. Secrets, config, and the boring stuff that saves you\n\n- Keys live in a secret manager or environment variables, never in the repo. Rotate them on a schedule and on every offboarding. This is table stakes, and it is still the most common real incident.\n- Pin your model version in config, not in code. When the provider deprecates a model, you change one config line after running evals against the successor, not a scattered set of string literals.\n- Write the runbook before launch: how to switch models, how to disable the feature flag, who gets paged, and what the fallback behavior is. One page is enough.\n- Feature-flag the whole path. Being able to turn the LLM feature off in one click, without deploying, is the cheapest insurance on this list.\n\n## \n  \n  \n  What ready means\n\nReady is not \"the demo worked.\" A feature is ready when a prompt change that hurts quality fails CI. When every call is traced and costed. When a provider outage triggers a fallback instead of an incident review, and turning the feature off takes one flag flip. That bar is reachable in a sprint or two if you build in this order: evals first, then guardrails, then observability, then the rest.\n\nThis checklist came out of shipping Python and AI systems for production teams. I write about this work and take a small number of consulting engagements. Most are FastAPI backends and production AI architecture for teams in the US and Canada. Details are on my site: [https://www.kevynfranco.com/consulting](https://www.kevynfranco.com/consulting). If you run an agency or outsourcing firm that needs extra senior Python or AI delivery capacity, there is a white-label partner path at [https://www.kevynfranco.com/partners](https://www.kevynfranco.com/partners).", "url": "https://wpnews.pro/news/a-production-readiness-checklist-for-llm-features-in-fastapi", "canonical_source": "https://dev.to/kevynfranco/a-production-readiness-checklist-for-llm-features-in-fastapi-dgk", "published_at": "2026-11-24 06:04:20+00:00", "updated_at": "2026-11-24 06:12:52.154571+00:00", "lang": "en", "topics": ["large-language-models", "ai-agents", "mlops", "ai-tools", "developer-tools"], "entities": ["FastAPI", "OpenAI", "OpenTelemetry", "OpenLLMetry", "Langfuse", "LangSmith", "Pydantic"], "also_reported_by": [], "takeaway": "Gate every prompt or model change behind a CI eval run on a hand-labeled golden set of 50-200 real-traffic examples, and force JSON-mode or function-calling output validated by a Pydantic model, retrying once with the error before failing loudly.", "recommendation": {"advice": "Build a 50-200 example golden dataset from real traffic and block merges in CI when eval scores drop on any prompt or model change.", "playbook": "evals-testing", "playbook_url": "https://wpnews.pro/playbooks/evals-testing"}, "alternates": {"html": "https://wpnews.pro/news/a-production-readiness-checklist-for-llm-features-in-fastapi", "markdown": "https://wpnews.pro/news/a-production-readiness-checklist-for-llm-features-in-fastapi.md", "text": "https://wpnews.pro/news/a-production-readiness-checklist-for-llm-features-in-fastapi.txt", "jsonld": "https://wpnews.pro/news/a-production-readiness-checklist-for-llm-features-in-fastapi.jsonld"}}