Deploying Agents to Production
A demo runs once on your laptop. Production runs thousands of times, through restarts, outages and impatient users.
A production agent system separates the front door that accepts requests, the workers that run agent loops, durable state that survives restarts, a controlled tool layer and the operations around them. Keep workers replaceable, save progress after each step and make every action safe to attempt twice.
What you will learn: the components of a production system, how to choose between request-response and background runs, sessions and workers, recovery with leases and idempotency, scaling, release safety and a readiness checklist.
Prerequisites: The Agent Loop: Observe, Reason, Plan, Act, Reflect. Experience running web services is helpful.
What changes in production
| In a demo | In production |
|---|---|
| One user | Many users who must never see each other's data |
| State in variables | State that survives restarts and moves between machines |
| Failures are rerun by hand | Automatic, safe recovery |
| Your own credentials | Scoped identity per user and agent |
| Cost unnoticed | Budgets, quotas and attribution |
| You watch the output | Monitoring, alerts and an on-call owner |
| Change anything any time | Versioned releases with rollback |
A reference architecture
| Component | Responsibility | If it is missing |
|---|---|---|
| API gateway | Identity, limits, request checks | Anyone can spend your budget |
| Queue | Absorb bursts, retry delivery | Overload drops work |
| Session store | Conversation and run state | Restarts lose conversations |
| Workers | Execute agent steps within limits | Long work blocks request handling |
| Model access layer | Credentials, quotas, timeouts, fallback | Every service handles outages differently |
| Tool layer | Permission, validation, idempotency | The model's request acts unchecked |
| Control plane | Versions, flags, off switch | You cannot stop or roll back quickly |
A low-volume internal assistant can be one service and one database. Keep the boundaries in the code, such as a separate tool layer and saved state, and split them into separate services when load or ownership requires it.
One request through the system
Follow an illustrative request, "Prepare the renewal summary for this customer", from arrival to result.
- The gateway authenticates the user, checks their quota and rejects oversized input.
- The API creates a run with an id, records the release version and places it on a queue.
- A worker claims the run, loads the session and builds the context from permitted data.
- It calls the model through the model access layer, with a deadline.
- The model requests records. The tool layer checks the user's rights and returns selected fields.
- After each step the worker saves a checkpoint and emits a progress event.
- Sending the summary needs approval, so the run is saved as waiting and the worker moves on.
- The approval arrives, the run is queued again and another worker finishes it.
- The result, cost and outcome are recorded, and the user is notified.
No single machine had to stay alive from start to finish. That one property removes a large family of production problems.
Three ways to run
| Mode | How it works | Fits |
|---|---|---|
| Request and response | The caller waits for the full result | Short, bounded tasks |
| Streaming | Progress and text are sent as they appear | Interactive use |
| Background job | Accept, return an id, work from a queue, notify | Long tasks, approvals, bursts |
Web servers, proxies and browsers have time limits. If a run can exceed them, or may wait for a person, make it a background job. Return an id immediately and offer status, progress, cancel and result operations.
Processes, sessions and workers
| Concept | Meaning | Design rule |
|---|---|---|
| Process or container | A running copy of your code | Disposable; hold nothing essential in memory |
| Session | An ongoing relationship with one user or case | Stored externally, owned by one identity |
| Run | One attempt to satisfy a request | Has an id, version, limits and status |
| Step | One model call or action | Checkpointed when finished |
| Worker | Takes runs and advances them | Claims work with an expiring lease |
- One writer per session. Two messages arriving together must not run two loops over the same state. Order them, or reject the second clearly.
- Waiting is not working. While waiting for approval, save state and release the worker.
- Cancel for real. Check for cancellation between steps and pass deadlines to model and tool calls.
- Drain on shutdown. Stop claiming work, finish or checkpoint the current step, then exit.
What state to keep, and where
| State | Typical store | Care needed |
|---|---|---|
| Run status and checkpoints | Transactional database or workflow engine | Version checks on every update |
| Conversation history | Database keyed by tenant and session | Retention, deletion, size limits |
| Long-term memory | Separate store with its own policy | Who may write; correction and expiry |
| Large files and outputs | Object storage, referenced by id | Access control on each retrieval |
| Caches | In-memory or shared cache | Tenant in every key; safe to lose |
| Audit records | Append-only log | Restricted access and protection from change |
Save enough to resume: the messages or their references, completed steps, pending approval, budget used and versions. Saved state is data that outlives releases, so give it a schema version and test loading old records with new code.
Recovery: leases, checkpoints and idempotency
Workers crash. The queue may deliver the same job twice. The program below shows the three ideas that make this safe, using an in-memory database. A worker takes a job with a lease that expires. It saves a checkpoint after each step. The one external action carries a key, so a repeat is recognized. Worker A crashes after sending but before saving.
"""Durable agent jobs: leases, checkpoints and idempotent side effects."""
import json
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE jobs(id TEXT PRIMARY KEY, step INTEGER, state TEXT, owner TEXT, lease INTEGER);
CREATE TABLE effects(key TEXT PRIMARY KEY, detail TEXT);
INSERT INTO jobs VALUES ('job-1', 0, '{}', NULL, 0);
""")
STEPS = ["gather", "draft", "send", "record"]
def claim(worker, now, ttl=30):
"""Take a job that is unfinished and not leased by anyone else."""
cur = db.execute(
"UPDATE jobs SET owner=?, lease=? WHERE id='job-1' AND step<? AND lease<=?",
(worker, now + ttl, len(STEPS), now))
db.commit()
return cur.rowcount == 1
def send_once(key, detail):
"""Stands for a service that remembers idempotency keys it has accepted."""
cur = db.execute("INSERT OR IGNORE INTO effects VALUES (?, ?)", (key, detail))
db.commit()
return "sent" if cur.rowcount else "skipped: already sent"
def work(worker, crash_after=None):
step, state = db.execute("SELECT step, state FROM jobs").fetchone()
state = json.loads(state)
while step < len(STEPS):
name = STEPS[step]
note = send_once("job-1:send", "report") if name == "send" else "ok"
print(f" {worker} ran {name}: {note}")
if name == crash_after:
print(f" {worker} crashed before saving its checkpoint")
return
state[name] = "done"
step += 1
db.execute("UPDATE jobs SET step=?, state=? WHERE owner=?",
(step, json.dumps(state), worker))
db.commit()
print("t=0 A claims:", claim("worker-A", 0))
work("worker-A", crash_after="send")
print("t=10 B claims:", claim("worker-B", 10))
print("t=31 B claims:", claim("worker-B", 31))
work("worker-B")
print("effects recorded:", db.execute("SELECT COUNT(*) FROM effects").fetchone()[0])
Output:
t=0 A claims: True
worker-A ran gather: ok
worker-A ran draft: ok
worker-A ran send: sent
worker-A crashed before saving its checkpoint
t=10 B claims: False
t=31 B claims: True
worker-B ran send: skipped: already sent
worker-B ran record: ok
effects recorded: 1
At time 10 worker B may not take the job, because A's lease is still valid. After it expires, B resumes from the last saved step. It repeats the send step, and the key prevents a second delivery. That protection must be honored by the service performing the action; a note kept only in your own database cannot cover a crash between the external call and your write.
Renew leases during long steps. A slow worker whose lease expired must not overwrite its successor, so check ownership with a version number on every write. Cap attempts and move repeatedly failing jobs aside for a person to inspect.
Workflow engines provide much of this machinery; see Durable Execution, Checkpoints and Approvals.
Living with dependencies
| Problem | Response |
|---|---|
| Model rate limit | Back off with randomness, queue, respect the provider's guidance |
| Model outage | Tested fallback, or a clear "try later" |
| Slow tool | Timeout, then report to the model or user |
| Failing tool | Circuit breaker that stops calls for a while |
| Burst of traffic | Queue limits, per-user quotas, refuse early |
Retry in one layer only. If the client library, the worker and the queue each retry three times, one failing call can become twenty-seven. A fallback model behaves differently, so evaluate it before relying on it.
Scaling
Agent workers spend much of their time waiting for models and tools, so processor use is a poor scaling signal. Watch queue age, runs in progress and provider quota. A useful estimate is that average runs in progress equals arrival rate multiplied by average duration: 2 runs per second lasting 15 seconds means about 30 at once, before allowing for peaks. Adding workers cannot raise throughput beyond a model or tool quota. Isolate heavy customers and long jobs, so they do not delay everyone else. More in Scaling, Hardware, Quotas and Caching.
Environments and configuration
Keep development, test and production separate, with separate credentials and data. The test environment needs tool fakes or sandbox accounts that behave like the real systems, including their errors. Hold prompts, limits, model choices and tool lists as versioned configuration that goes through the same review as code. A change typed straight into a production console may be quick, but nobody can later explain which behavior was running at a given time.
Feature flags are useful for turning on a new tool for a small group, or turning one off during an incident without a release. List the flags that act as safety controls, restrict who may change them and log every change.
Security and tenancy
- Take user and tenant identity from the authenticated request, never from model output.
- Scope every query, cache key, memory entry and file path by tenant.
- Keep secrets in a secret manager; do not place them in prompts or traces.
- Run generated code in an isolated sandbox with restricted network access.
- Require approval for high-impact actions, bound to exact parameters.
- Set per-run and per-tenant spending limits.
Review these with Agent Threat Model and OWASP Agentic Risks.
Releasing safely
An agent version is more than code: it includes the model and settings, prompts, tool definitions, policies and retrieval data. Give each release an identifier and record it on every run.
- Pass tests and the evaluation gate.
- Run in shadow, with actions replaced by stand-ins.
- Send a small share of traffic and compare success, cost and safety signals.
- Increase in steps, with automatic rollback rules.
- Decide what happens to runs already in progress: finish on the old version, or migrate saved state carefully.
The last point is easy to miss. A paused run may resume days later, so new code must read old state, or old workers must stay until those runs end. Pipeline details are in CI/CD, Infrastructure as Code and Safe Releases.
Operations
Before launch, name an owner and write short procedures for: pausing the agent, disabling one tool, revoking a credential, rolling back, replaying failed jobs safely and telling users. Test restore from backup. Define what the product does when the agent is unavailable, such as showing a form or routing to a person. Dashboards and objectives are described in What to Measure: Metrics, Dashboards and SLOs.
Rehearse the bad day
Before launch, and now and then afterward, run short exercises in a test environment and write down what surprised you.
| Exercise | What should happen |
|---|---|
| Stop a worker in the middle of an action | Another resumes; the effect appears once |
| Make the model service return errors | Backoff, fallback or a clear message; no retry storm |
| Make one tool very slow | Timeouts; other work continues |
| Deliver the same job twice | No duplicate effect |
| Trigger the off switch | New actions stop quickly; users are informed |
| Roll back with runs in progress | Old and new state are handled correctly |
Production readiness checklist
Behavior and quality
- Success criteria, evaluation suite and release gate exist
- Step, time, token and money limits are enforced in code
- Escalation to a person works and has capacity
Reliability
- State survives restarts; recovery was tested by killing a worker
- Changing actions are idempotent or require manual confirmation
- Timeouts, bounded retries and fallbacks are defined
- Load test covers peaks and provider rate limits
Security and data
- Threat model reviewed; injection scenarios tested
- Per-user authorization and tenant isolation verified
- Retention, deletion and logging rules are implemented
Operations
- Dashboards, alerts, runbooks and an on-call owner are in place
- Rollback and the off switch were rehearsed
- Budget alerts and cost attribution are active
- Users are told they are dealing with an automated system where required
Frequently asked questions
Do I need Kubernetes?
No. Use what your team can operate. Containers, serverless functions with a queue, or a managed agent platform can all work. See Docker and Kubernetes for Agents and Serverless, Streaming APIs, Queues and State.
Where should conversation state live?
In a durable store keyed by tenant and session, with access control and a retention period.
Can I guarantee an action happens exactly once?
Delivery systems commonly repeat work. Aim for effects that happen once by combining retries with idempotency at the receiving service, plus reconciliation.
When is a managed platform better?
When its runtime, identity and monitoring fit your needs and you would rather not operate them. Compare limits, data location and exit options: see Managed vs Custom Platforms and Total Cost.
References and further reading
- Kubernetes documentation
- Service level objectives (Google SRE book)
- OWASP Top 10 for Agentic Applications 2026
- SQLite INSERT documentation
Next steps
Docker and Kubernetes for Agents
Package and run workers.
High Availability and Disaster Recovery
Survive larger failures.
LLMOps, AgentOps and Maturity
Operate agents over time.