SysDesignAtlas

Agent Infrastructure

Durable execution, sandboxing, concurrency, and cost ceilings — the platform an agent needs to survive a process restart, a hostile input, and a runaway loop.

HLDHard10 min readaiagentsdurable-executionsandboxing
Confidence

#The workload shape

Agents break the assumptions a normal request handler is built on:

   HTTP REQUEST                  AGENT EXECUTION

   milliseconds to seconds       seconds to HOURS
   stateless                     accumulating state across steps
   in-memory is fine             must survive restarts
   bounded, predictable cost     unbounded without limits
   fails cleanly                 may fail after side effects
   one process                   may pause for human approval
   retry = re-run                retry may double-charge someone

Every row is a platform requirement. An agent running inside a request handler works until the first deploy restarts the pod mid-trajectory, at which point you discover you needed durable execution.

#Durable execution

A trajectory is one agent run — the whole sequence of steps it took from goal to result. The core requirement: the trajectory survives process death. Because steps have real effects in the world, restarting from the beginning isn't a neutral do-over; it sends the email again. So write down what you're about to do before doing it, and a crash can resume from where it stopped.

   EPHEMERAL                        DURABLE

   loop in memory                   each step:
     step 1 ✓                         1. persist the intent
     step 2 ✓                         2. execute
     step 3 ✓ (sent an email)         3. persist the result
     ── CRASH ──                      4. commit the new state
     everything lost;                 ── CRASH ──
     restart re-sends the email       reload state, resume at
                                      the step after the last
                                      committed one

Three ways to build it:

ApproachMechanismTrade
Workflow engine (Temporal, Restate, DBOS)Code looks sequential; the engine records every side effect and replays deterministically on recoveryBest ergonomics; a significant dependency
Explicit state machinePersist a state row; each step is a transition; a worker picks up pending workFull control, more code, easy to reason about
Event-sourced trajectoryAppend every event to a log; rebuild state by replayExcellent auditability; replay must be pure — rebuilding state only reads the log, never calls a tool again

For most teams the state-machine approach on top of an existing job scheduler is the pragmatic choice: an agent run is a row with a status, a step index, and a serialised trajectory. Workers lease runs — claim one for a limited time, so that if the worker dies the lease expires and another worker picks the run up — and advance them one step at a time.

#Sandboxing

Agents that execute code, run shell commands, or browse the web are executing untrusted input — because the model's output is derived from user input. A prompt injection turns the model into a confused deputy: a program that legitimately holds powers (run code, read files) and is tricked into using them on an attacker's behalf.

   ESCALATING ISOLATION

   In-process eval          ✗ never. Trivially escapable.
   Container (Docker)       ⚠ all containers share the host's
                              kernel, so one kernel bug lets
                              code escape
   gVisor / Kata            ✓ syscall interception or a
                              lightweight VM
   Firecracker microVM      ✓ real VM boundary, ~125 ms boot
   Separate machine         ✓ strongest, slowest

   REGARDLESS of the mechanism:
     · no network, or a strict egress allowlist
     · read-only filesystem plus one writable scratch mount
     · CPU, memory, and PID limits
     · hard wall-clock timeout
     · no credentials in the environment — ever
     · destroy after use; never reuse a sandbox across users

Network egress is the control that matters most. A sandbox with unrestricted outbound access can exfiltrate — quietly send out to an attacker's server — anything it can read, including data the agent legitimately retrieved for the user. Default-deny with an allowlist of specific hosts is the only defensible posture.

Startup latency drives the design. A Firecracker microVM boots in ~125 ms; a container in tens of milliseconds; a fresh VM in seconds. For interactive agents, maintaining a warm pool of pre-booted sandboxes turns a visible delay into an invisible one — the same pooling logic as database connections, with a stronger reason.

#Concurrency and resource control

An agent platform is a scheduler for long-running, resource-hungry, variable-duration work.

   LIMITS AT EVERY LEVEL

   per run:     max steps · max tokens · max cost · max wall time
   per user:    max concurrent runs · tokens/hour · spend/day
   per tenant:  aggregate quota, fair share against other tenants
   global:      total concurrent runs · model API rate limit budget

   Without ALL of these, one user with a script can consume
   the entire platform, and one buggy loop can produce a
   five-figure bill.

The model API is a shared, rate-limited resource, and it is usually the real bottleneck. Fifty concurrent agents each making a call is fifty concurrent requests against a quota shared with the rest of your product. This needs a token-bucket budget (an allowance of requests that refills at a fixed rate) with per-tenant fair queueing, so one busy tenant can't starve the rest, and it needs backpressure — when the budget is exhausted, queue or shed, never retry blindly into a rate limit.

Long-running work must not hold a request thread. The correct shape is: accept the request, persist the run, return an ID immediately, and stream or poll for progress. An agent that pauses for human approval may wait hours; no connection should be held open for that.

#Observability for agents

Tracing matters more here than anywhere else, because a failure is a trajectory, not an exception.

What to captureWhy
Every step: model call, tool call, resultThe trajectory is the debug log
Token counts and cost per stepWhere the money went; cost p99
Tool latency and error rate, per toolThe slow tool is usually the problem, not the model
Step count distributionA rising tail means agents are struggling
Termination reasonSuccess, iteration limit, cost limit, error — the ratio is your health metric
Approval wait timeHuman-in-the-loop bottlenecks

Termination-reason distribution is the single best health metric. A shift from "completed" toward "hit iteration limit" is a quality regression, visible immediately, with no ground truth required. It's the agent equivalent of tool-call validity from AI observability.

Make trajectories replayable in a viewer. When someone reports "the agent did something weird," the fix starts with reading exactly what it saw and did, step by step. A trajectory viewer is a small tool with a very high return.

#Cost control

The controls, all of which are cheap to add and expensive to omit:

  1. Hard per-run cost ceiling. Terminate and return partial results. Not a warning — a stop.
  2. Per-user and per-tenant daily budgets, enforced at admission — checked before a run is allowed to start, not after it has spent.
  3. Global spend rate alarm on a short window, not a daily total. A daily total only fires once the day's damage is done; spend measured over, say, 10 minutes catches the $4,000-an-hour loop within minutes.
  4. Cost estimate before starting, from the task shape, so an obviously expensive run can be rejected or confirmed.
  5. Cheaper models for cheap steps. Classification, routing, and simple extraction do not need the frontier model. This often halves the cost of a trajectory.

#Multi-agent coordination

When runs spawn sub-runs, you have a distributed system with a dependency graph.

  • Parent/child runs with propagated budgets. A child's cost counts against the parent's ceiling, or the ceiling means nothing.
  • Cancellation must propagate. Cancelling a parent must terminate its children, or you leak expensive orphans — child runs that keep working and billing with nobody waiting for their result.
  • Deadlines propagate too — the same deadline propagation as any RPC chain.
  • Fan-out limits. An agent that can spawn agents needs a depth limit and a total-descendant limit, or a single request can recursively consume the platform.

That last one is not hypothetical. An agent whose plan includes "spawn a sub-agent per file" applied to a large repository is a fork bomb with a language model attached — like the classic program that copies itself until the machine is full, each sub-agent can spawn more until every limit is exhausted.

#Check yourself

Why can't agents run inside ordinary request handlers?Show answer
They run seconds to hours, accumulate state, may pause for approval, and cause side effects — so they need durable execution: accept, persist, return an ID, then stream or poll.
What is the replay rule for durable agents?Show answer
Persist each step's result before advancing; on recovery read recorded results instead of re-executing, and record nondeterminism (time, IDs, model output) rather than recompute it.
Name three ways to build durable execution.Show answer
A workflow engine (Temporal, Restate, DBOS), an explicit state machine on a job scheduler (often the pragmatic choice), or an event-sourced trajectory.
How should agent sandboxes be built?Show answer
gVisor, Kata or Firecracker microVMs rather than plain containers; default-deny egress; read-only root plus scratch; resource and time limits; no credentials; destroyed after use; a warm pool hides boot time.
Why is the model API the usual bottleneck?Show answer
It's a shared, rate-limited quota. Use a token-bucket budget with per-tenant fair queueing and backpressure — queue or shed, never retry blindly into a rate limit.
What is the best single agent health metric?Show answer
The termination-reason distribution: a shift from "completed" to "hit iteration limit" reveals regressions immediately with no ground truth. Keep trajectories replayable in a viewer.
What cost controls do agent platforms need?Show answer
A hard per-run ceiling that stops the run, per-user and per-tenant budgets at admission, a short-window global spend alarm, pre-run cost estimates and cheaper models for cheap steps.
What must propagate from parent to child runs?Show answer
Budgets, deadlines and cancellation — plus depth and total-descendant limits, or "spawn an agent per file" becomes a fork bomb.

#What to carry forward

  • Agents are long-running, stateful, expensive, and side-effecting — every one of those is a platform requirement.
  • Durable execution: persist before and after each step; replay must never repeat side effects.
  • Record nondeterminism rather than recomputing it.
  • Sandbox with default-deny egress; keep a warm pool to hide boot latency.
  • Limits at every level — run, user, tenant, global — including a hard cost ceiling.
  • Termination-reason distribution is the best agent health metric.
  • Propagate budgets, deadlines, and cancellation to child runs, and cap fan-out depth.
00:00
/ 10m