14. Production AI systems
Taking AI workflows to production. Workflow patterns, determinism, durable execution and checkpoints, idempotency, human in the loop, streaming, observability with OpenTelemetry, cost and latency engineering, versioning, deployment and security.
A demo works once on your laptop. A production system works every time, for many users, when providers are slow, when servers restart, and when someone changes a prompt. This chapter collects the engineering that gets you there.
Workflow patterns
Most production AI is built from a handful of composable patterns (see Anthropic’s Building effective agents, 2024):
| Pattern | Shape | Example |
|---|---|---|
| Prompt chaining | A → B → C, each step one job, with checks between | Extract → validate → summarise |
| Routing | Classify, then send to a specialised path | Billing vs technical tickets |
| Parallelisation | Independent steps at once (sectioning), or the same step several times (voting) | Analyse five documents together; self-consistency |
| Orchestrator-workers | A planner splits, workers execute, a synthesiser combines | Research reports |
| Evaluator-optimizer | Generate, critique, revise | Writing to a quality bar |
| Agent | A model choosing actions in a loop | Open-ended assistants |
Prefer the simplest pattern that works. Each step up in autonomy costs predictability.
Determinism and reproducibility
LLMs are non-deterministic, but your system should be as reproducible as possible:
- Version everything: prompts, graphs, node versions, models, datasets. Record which version produced each result (a content hash of the workflow is ideal).
- Deterministic plumbing: stable ordering of parallel results, stable document IDs, explicit types.
- Pin model versions where providers allow it; re-evaluate when models change.
- Snapshot inputs and configuration with every run.
Durable execution
Long workflows (multi-step agents, approvals that wait for days, batch jobs) will be interrupted by deploys, crashes and timeouts. Durable execution means a run survives that:
- Job queue + leases: work is claimed by a worker for a limited time and renewed by heartbeats; if the worker dies, the lease expires and another worker takes over.
- Checkpoints: after each step, persist its outputs. On recovery, restore finished steps instead of re-running them.
- Idempotency: a step is idempotent if running it twice has the same effect as once (a read, a calculation). Non-idempotent steps (charging a card, sending an email) must not be silently repeated: recover by asking a human, or use idempotency keys.
- Bounded recovery: cap retries so a poison job does not loop forever.
- Graceful shutdown: stop claiming, finish or release in-flight work.
Retries and timeouts
- Retry transient errors (rate limits 429, server errors 5xx, dropped connections) with exponential backoff and jitter; never retry permanent errors (bad request, auth failure).
- Retry streaming calls only before any text reached the user, or the text appears twice.
- Give every external call a timeout, and every run an overall budget.
- Mark tools that failed permanently so agents stop calling them.
Human in the loop (HITL)
Some decisions need a person: publishing content, refunds, irreversible actions, low-confidence cases. A good HITL design:
- pauses durably: no thread or connection held while waiting, survives restarts;
- shows the reviewer the context and lets them approve, reject (with a reason) or edit;
- resumes from the checkpoint, not from scratch;
- validates the reviewer’s response against a schema;
- records who decided what.
Streaming
Users judge speed by time to first token. Streaming tokens as they are generated makes a 10-second answer feel immediate. Engineering points: Server-Sent Events (SSE) are the common transport; tool calls arrive as fragments that must be reassembled; streamed text is a preview, the final output is the source of truth; reconnecting clients should resume without duplicates.
Observability
You cannot fix what you cannot see. An LLM system needs traces: a tree of spans for the run, each step, each model call (model, tokens, cost, latency) and each tool call (arguments, result, duration).
- OpenTelemetry (OTel) is the vendor-neutral standard for traces, metrics and logs; OTLP is its wire protocol.
- The GenAI semantic conventions standardise attribute names (
gen_ai.request.model,gen_ai.usage.input_tokens,gen_ai.tool.name…) so any backend understands them: Jaeger, Grafana Tempo, Honeycomb, Datadog, and LLM-specific tools like Langfuse and Arize Phoenix. - Metrics (Prometheus) for dashboards and alerts: runs by status, latency histograms, tokens and cost by model, tool failures.
- Privacy: prompts and outputs can contain personal data; make content capture opt-in.
Cost and latency engineering
| Technique | Saves |
|---|---|
| Route easy requests to small models | Cost, latency |
| Retrieve fewer, better chunks; compress context | Input tokens |
| Prompt caching of stable prefixes | Cost, latency on repeated prompts |
| Lower reasoning effort where depth is not needed | Latency, output tokens |
| Parallel tool calls and parallel branches | Latency |
| Fixed pipelines instead of agents when the path is known | Calls |
| Bound agent turns and budgets | Runaway cost |
| Local models for embeddings, reranking, OCR | API cost, data exposure |
Measure p95 latency and cost per request in your evaluations, not just quality.
Testing
- Unit tests for deterministic parts with a mock model (scripted responses) so tests are fast, free and repeatable.
- Evaluation sets for model-dependent quality (chapter 12), run on every significant change.
- Opt-in live tests against real providers.
- Contract tests against pinned versions of external APIs.
Versioning and collaboration
Store workflows as text (a canonical, diff-friendly format) in Git; review changes in pull requests; run validation and evaluations in CI; tag releases; roll back by redeploying an earlier version.
Deployment
- Package the workflow as a service with a clear API (OpenAPI), authentication, rate limits and health checks.
- Know your platform’s limits: request timeouts (serverless platforms often cap at a few minutes), persistent disk (embedded indexes need one), memory (local models need gigabytes), statefulness (in-process memory pins you to one replica).
- Secrets from a secret manager, never baked into images or code.
- Health-checked rollouts and rollback.
Security in production
Authentication and roles; HTTPS; secrets as references; least-privilege tools; sandboxed code; read-only data access; input and output guardrails; audit trails; dependency and plugin isolation (chapter 11).
Try it in AgenticMind
| Concern | Feature |
|---|---|
| Versioning, reproducibility | Append-only revisions with content hashes; runs snapshot the IR; GitHub sync |
| Durable execution | Job queue, leases, checkpoints, automatic resume, workers (Durable runs) |
| HITL | Human Approval |
| Streaming | Token streaming over SSE, runs/stream |
| Observability | OpenTelemetry GenAI traces, Prometheus metrics |
| Cost and latency | Model Router, reasoning effort, parallel tool calls, run targets, local models |
| Testing | Mock provider, Evaluation Lab, CLI validation |
| Deployment | Export app, Deployment Center with capability checks and rollback |
| Triggers | Webhooks, schedules, queues, chat channels |
Key takeaways
Production AI is mostly software engineering: version everything, make runs durable with checkpoints and leases, never silently repeat side effects, retry only transient errors, pause durably for humans, stream for perceived speed, trace every model and tool call with OpenTelemetry, engineer cost and latency deliberately, and deploy with an honest view of platform limits.

