CONTENTS
Shipping AI to Production
A demo answers “can this work?” Production answers “does this work reliably, affordably, safely, for every user, every day, and how will we know when it breaks?” This chapter covers the engineering between those two.
9.1 The production architecture
A typical AI feature’s architecture:
Mobile / Web client
│ (auth, streaming, cancel)
▼
API gateway / BFF ───────────────── rate limiting, auth, quotas per user/plan
│
▼
AI service layer
├── Prompt templates (versioned)
├── Model router (which model for which request; fallbacks)
├── Retrieval / tools / agents
├── Guardrails (input + output checks)
├── Cache (exact + prompt caching)
└── Tracing (every call: inputs, outputs, tokens, latency, versions)
│
▼
Model providers (primary + fallback) / self-hosted models
Never call model providers directly from client apps. Keys leak (anyone can decompile an app bundle), and you lose control of cost, abuse, logging, and model routing.
9.2 Reliability
Model APIs are external dependencies with real failure modes: rate limits (429s), overload errors, timeouts, regional outages, and occasional quality regressions.
- Retries with exponential backoff and jitter for transient errors. Respect
retry-afterheaders. - Timeouts appropriate to the task. Streaming helps here, because you can detect a stalled stream.
- Fallback models / providers. If the primary fails, route to a secondary. Multi-provider gateways (OpenRouter, LiteLLM, Vercel AI Gateway, cloud-provider endpoints) make this easier. Remember: a fallback model behaves differently, so it needs its own evals.
- Graceful degradation. If the AI feature fails, what does the user see? A helpful non-AI fallback beats an error toast. (You already design offline states. Same idea.)
- Idempotency for agent actions. If a retry re-runs a tool call that sends an email, you’ve sent two emails. Use idempotency keys for side-effecting tools.
- Durable execution for long-running agents. Agent tasks that run for minutes or hours shouldn’t die with a server restart. Workflow engines (Temporal, Inngest, and similar) or checkpointed state let you resume.
9.3 Latency: where frontend engineers shine
LLM features are slow by web standards. Users perceive latency through:
- Time to first token (TTFT): how long until something appears.
- Tokens per second: how fast the text flows.
- Total time to useful result.
Backend levers:
- Smaller or faster models for latency-critical paths.
- Prompt caching: stable prefixes cut TTFT and cost significantly.
- Shorter prompts and outputs. Every output token is sequential time. Ask for concise formats.
- Parallelize independent calls (
Promise.allfor LLM calls). - Speculative work: start likely calls before the user finishes (e.g., prefetch on input focus).
- Cache complete responses for repeated identical requests; semantic caching for near-duplicates (carefully, since a wrong cache hit is a wrong answer).
Frontend levers (your advantage):
- Stream everything. Show tokens as they arrive.
- Show progress for agentic steps (“Checking your calendar… Found 3 conflicts… Drafting options…”). Visible progress makes waits feel shorter and builds trust.
- Optimistic and skeleton UI shaped like the expected output.
- Progressive structured rendering: with partial-JSON parsing, render cards as fields arrive.
- Background + notify for long tasks. Don’t hold the user on a spinner for a 3-minute agent run; let them leave and push-notify when done.
- Interruptibility: a Stop button is a latency feature. Users are happier when they control the wait.
9.4 Cost management
AI costs can scale unexpectedly. One power user with an agent loop can burn more tokens than 10,000 casual users.
- Measure cost per feature, per request, and per user. Attach token usage to traces and aggregate.
- Per-user and per-plan quotas with clear UX when they’re reached.
- Model routing: small models for easy cases.
- Prompt caching and batch APIs for non-real-time work (overnight summaries, bulk classification).
- Cap agent loops: max turns, max tokens, max wall-clock time, max spend per task.
- Trim context: summarize history, limit retrieved chunks, clean tool outputs.
- Distillation: once a big model works well on a narrow task, generate training data with it and fine-tune a small model (Chapter 10).
Unit economics matter: if a feature costs $0.04 per use and users use it 30 times a month on a $5/month plan, do the math before launch.
9.5 Guardrails and safety
Guardrails are checks around the model:
Input guardrails:
- Moderation / abuse detection.
- Prompt injection heuristics and classifiers (helpful, not sufficient; see Chapter 7).
- PII detection and redaction before sending data to third-party models, where required.
- Scope checks: is this request something the feature should handle at all?
Output guardrails:
- Schema validation (always).
- Policy checks (no medical diagnoses, no financial advice, brand-safety constraints).
- Grounding checks: are claims supported by the retrieved sources?
- Safe rendering: sanitize model-generated markdown and HTML (XSS is real if you render model output as HTML), and never auto-follow model-generated links or execute model-generated code outside a sandbox.
Domain responsibility: in health, finance, legal, and children’s products, the bar is much higher. Know relevant regulations (data protection law such as GDPR, the EU AI Act’s risk-based obligations, sector rules like HIPAA) and involve legal and compliance early.
9.6 Observability
You can’t fix what you can’t see. For every model call, log:
- Full input (prompt version, rendered prompt, retrieved context, tools offered) and full output (including tool calls).
- Model, parameters, tokens, cost, latency (TTFT and total), stop reason.
- User/session/trace IDs linking multi-step agent runs together.
- User feedback signals (thumbs, edits, regenerations, abandonment).
OpenTelemetry has emerging semantic conventions for generative AI, and most LLM observability tools (Langfuse, Braintrust, LangSmith, Arize, Datadog, Sentry’s AI monitoring, and others) ingest traces in compatible formats.
Respect privacy: production traces contain user data. Apply retention limits, access controls, redaction, and honor user deletion requests.
9.7 Shipping and iterating
- Feature flags for prompts and models, so you can roll out gradually and roll back instantly.
- A/B tests with real product metrics (task completion, retention, satisfaction), not just eval scores. Evals tell you “is it correct?”; experiments tell you “does it help?”
- Shadow mode: run a new model or prompt on live traffic without showing results, and compare offline.
- Feedback loops: every user-flagged failure goes into triage, then the eval set, then a fix.
9.8 AI UX principles
A few principles worth internalizing, from teams that ship AI features well:
- Set expectations honestly. Show what the AI can and can’t do. Overpromising makes every failure feel like a betrayal.
- Make AI output editable and reversible. Drafts, not decisions. Undo everywhere.
- Show sources for factual claims so users can verify.
- Design for failure first. What does the user see when the model is wrong, slow, or down?
- Match autonomy to stakes. Autocomplete-level help can be invisible; booking a flight needs confirmation.
- Don’t make chat the default UI. Chat is flexible but hard to discover. Often the best AI features are embedded: a smart default, a one-tap action, a summary card. Use chat when open-endedness is the point.
- Capture feedback in the flow. Edits, acceptances, and rejections are better signals than rating prompts.
Key takeaways
- Proxy all model calls through your backend: auth, quotas, routing, logging.
- Engineer for unreliable dependencies: retries, fallbacks, idempotency, durable execution, graceful degradation.
- Latency is both a backend problem (models, caching, parallelism) and a frontend problem (streaming, progress, background tasks). The frontend half is your edge.
- Track cost per feature and per user; cap agents; route to small models; cache; batch.
- Guard inputs and outputs, render model output safely, and know the regulatory context.
- Trace everything, flag everything, and close the loop from production failures back to evals.
Exercises
- Add a fallback model to an AI feature you’ve built. Run your eval suite against both. How different are they?
- Instrument an AI feature with tracing (Langfuse is easy to self-host). Build a dashboard of cost per user and p50/p95 latency.
- Redesign one slow AI interaction in your app using three frontend latency techniques from §9.3. Measure perceived performance with five users.
- Write a one-page unit-economics analysis for an AI feature: cost per use, expected usage, plan pricing, margins, and which optimizations change the picture most.