Deploying Agents to Production

A demo runs once on your laptop. Production runs thousands of times, through restarts, outages and impatient users.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Beginner From demo to service

What changes in production

In a demoIn production
One userMany users who must never see each other's data
State in variablesState that survives restarts and moves between machines
Failures are rerun by handAutomatic, safe recovery
Your own credentialsScoped identity per user and agent
Cost unnoticedBudgets, quotas and attribution
You watch the outputMonitoring, alerts and an on-call owner
Change anything any timeVersioned releases with rollback

A reference architecture

ClientsWeb, chat, mobile, other systems
API and gatewayAuthenticate, rate limit, validate, accept work, stream progress
Queue and session servicePending work, conversation state, ordering per session
Agent workersRun loops, enforce limits, save checkpoints
Model accessRouting, quotas, fallbacks
Tool layerAuthorization, sandbox, audit
State storesCheckpoints, memory, files
Operations, including tracing, evaluation, configuration, secrets and release control, apply to every layer.
ComponentResponsibilityIf it is missing
API gatewayIdentity, limits, request checksAnyone can spend your budget
QueueAbsorb bursts, retry deliveryOverload drops work
Session storeConversation and run stateRestarts lose conversations
WorkersExecute agent steps within limitsLong work blocks request handling
Model access layerCredentials, quotas, timeouts, fallbackEvery service handles outages differently
Tool layerPermission, validation, idempotencyThe model's request acts unchecked
Control planeVersions, flags, off switchYou cannot stop or roll back quickly
Start smaller than the diagram

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.

  1. The gateway authenticates the user, checks their quota and rejects oversized input.
  2. The API creates a run with an id, records the release version and places it on a queue.
  3. A worker claims the run, loads the session and builds the context from permitted data.
  4. It calls the model through the model access layer, with a deadline.
  5. The model requests records. The tool layer checks the user's rights and returns selected fields.
  6. After each step the worker saves a checkpoint and emits a progress event.
  7. Sending the summary needs approval, so the run is saved as waiting and the worker moves on.
  8. The approval arrives, the run is queued again and another worker finishes it.
  9. 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.

Intermediate Runtime design

Three ways to run

ModeHow it worksFits
Request and responseThe caller waits for the full resultShort, bounded tasks
StreamingProgress and text are sent as they appearInteractive use
Background jobAccept, return an id, work from a queue, notifyLong 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

ConceptMeaningDesign rule
Process or containerA running copy of your codeDisposable; hold nothing essential in memory
SessionAn ongoing relationship with one user or caseStored externally, owned by one identity
RunOne attempt to satisfy a requestHas an id, version, limits and status
StepOne model call or actionCheckpointed when finished
WorkerTakes runs and advances themClaims 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.
Queued
Running
WaitingPerson or event
EndedSucceeded, failed or canceled
↺ A waiting run returns to the queue when its answer arrives

What state to keep, and where

StateTypical storeCare needed
Run status and checkpointsTransactional database or workflow engineVersion checks on every update
Conversation historyDatabase keyed by tenant and sessionRetention, deletion, size limits
Long-term memorySeparate store with its own policyWho may write; correction and expiry
Large files and outputsObject storage, referenced by idAccess control on each retrieval
CachesIn-memory or shared cacheTenant in every key; safe to lose
Audit recordsAppend-only logRestricted 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.

Further care for real systems

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

ProblemResponse
Model rate limitBack off with randomness, queue, respect the provider's guidance
Model outageTested fallback, or a clear "try later"
Slow toolTimeout, then report to the model or user
Failing toolCircuit breaker that stops calls for a while
Burst of trafficQueue 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.

Expert Scale, safety and release

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.

  1. Pass tests and the evaluation gate.
  2. Run in shadow, with actions replaced by stand-ins.
  3. Send a small share of traffic and compare success, cost and safety signals.
  4. Increase in steps, with automatic rollback rules.
  5. 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.

ExerciseWhat should happen
Stop a worker in the middle of an actionAnother resumes; the effect appears once
Make the model service return errorsBackoff, fallback or a clear message; no retry storm
Make one tool very slowTimeouts; other work continues
Deliver the same job twiceNo duplicate effect
Trigger the off switchNew actions stop quickly; users are informed
Roll back with runs in progressOld 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

Next steps