hzerrad@insights:~$cat posts/softeng/ai-agents-are-a-distributed-systems-problem.md
AI Agents Are a Distributed Systems Problem
Production AI agents are not just smarter chatbots. They are long-running, stateful systems that must survive crashes, retries, partial failures, and human approvals without repeating irreversible actions. Building them reliably requires durable execution, idempotency, authorization, sandboxing, observability, and other principles familiar from distributed systems.
HZOn this page
- The Workload Is Different
- Durable Execution Comes Before Intelligence
- Retries Become Dangerous When Agents Can Act
- The Security Boundary Belongs Outside the Model
- Observability Means Reconstructing Execution
- Testing Changes Too
- Protocols Do Not Eliminate Orchestration
- We Have Seen Most of These Problems Before
- The Model Is Only One Failure Domain
For the last few years, most of the conversation around AI agents has revolved around models: which one reasons better, which one is cheaper, which framework to use, how large the context window should be. Those questions matter, but they matter progressively less once an agent leaves a demo environment and starts doing real work.
Getting an LLM to call a tool is the easy part of operating an agent in production. The difficult part is a system that remains correct when an execution lasts twenty minutes, calls twelve external services, partially succeeds, waits for human approval, loses a worker halfway through, retries an operation, and resumes without performing the same irreversible action twice. That is not primarily an AI problem. It is a distributed systems problem.
The Workload Is Different
Most backend infrastructure has been optimized around some variation of a bounded request-response cycle:
Diagram source
flowchart LR
A[Request] --> B[Compute]
B --> C[Response]Even when the underlying architecture is complicated, the unit of work is usually reasonably bounded. A request enters the system. A service processes it. Durable state is stored somewhere if necessary. The request eventually succeeds or fails.
Agent execution looks very different:
Diagram source
flowchart TD
A[Goal] --> B[Reason]
B --> C[Tool call]
C --> D[Observe result]
D --> E[Update state]
E --> F{Task complete?}
F -- No --> G{Need external input?}
G -- No --> B
G -- Yes --> H[Wait]
H --> I{Human approval required?}
I -- Yes --> J[Request approval]
J --> K[Resume]
I -- No --> K
K --> B
F -- Yes --> L[Result]An agent may remain logically alive long after the process that was executing it has disappeared. That distinction has consequences. The infrastructure question stops being "where do I run the model?" and becomes:
What does execution mean when the process performing the work cannot be trusted to stay alive?
That is a problem software engineers have dealt with before.
Durable Execution Comes Before Intelligence
Consider an agent responsible for resolving a customer support issue. It might:
- read the ticket;
- query the customer database;
- determine that a refund is appropriate;
- request human approval;
- wait thirty minutes;
- receive approval;
- call the payment provider;
- update the ticket.
Now suppose the worker crashes immediately after step 7. The process restarts. If the runtime simply reconstructs the conversation and asks the model to continue, the agent might issue the refund again. The model did nothing wrong.
The infrastructure did.
Preventing this takes the same machinery a workflow engine needs: persisted execution state, checkpoints, a durable event history, idempotent operations, explicit state transitions, retry policies, and some way to compensate for steps that cannot be undone. A simplified execution model for the refund agent might look like this:
Diagram source
stateDiagram-v2
[*] --> ReadingTicket
ReadingTicket --> CheckingCustomer
CheckingCustomer --> AwaitingApproval
AwaitingApproval --> IssuingRefund: Approved
AwaitingApproval --> Cancelled: Rejected
IssuingRefund --> UpdatingTicket
UpdatingTicket --> Completed
IssuingRefund --> IssuingRefund: Retry
UpdatingTicket --> UpdatingTicket: Retry
Cancelled --> [*]
Completed --> [*]Checkpointing here is a correctness requirement rather than an optimization. The runtime should be able to disappear at almost any point without destroying the logical execution it was responsible for. Once you adopt that mental model, the architecture starts looking less like a chatbot backend and more like a workflow engine, a job orchestrator, or an event-driven state machine. The LLM becomes one component inside the workflow. It is not the workflow.
Retries Become Dangerous When Agents Can Act
Retries are simple when an operation is read-only. Retrying this is generally harmless:
GET /orders/123 HTTP/1.1
Host: api.example.com
Retrying this may not be:
POST /refunds HTTP/1.1
Host: payments.example.com
Content-Type: application/json
{
"order_id": "123",
"amount": 12500
}
Distributed systems already distinguish between operations that can safely be retried and operations that need idempotency protection. Agents raise the stakes because they chain actions together autonomously. Imagine an infrastructure agent executing:
Diagram source
flowchart LR
A[Create VM] --> B[Configure VM]
B --> C[Update DNS]
C --> D[Notify customer]DNS is updated successfully, but the worker crashes before the new state is durably persisted. Blindly replaying the workflow on resume could create another VM, overwrite DNS, send duplicate notifications, and leave multiple resources allocated for the same task.
Every externally visible agent action therefore needs an execution contract. For each operation, the runtime should be able to answer:
- Is this operation idempotent?
- Can its completion be verified after a crash?
- Can its result be reconstructed?
- What happens if the caller times out but the operation succeeds?
- Can the action be compensated if a later step fails?
- Does retrying it require human confirmation? Those are not prompt-engineering questions. They are transaction semantics.
Take an agent that can create a cloud environment. A naive implementation might expose:
def create_environment(customer_id: str) -> Environment:
return cloud.create_environment(customer_id)
A safer interface makes the execution itself part of the operation:
def create_environment(
customer_id: str,
idempotency_key: str,
) -> Environment:
existing = environments.find_by_idempotency_key(idempotency_key)
if existing is not None:
return existing
environment = cloud.create_environment(customer_id)
environments.save(
environment=environment,
idempotency_key=idempotency_key,
)
return environment
The exact implementation will vary. The principle does not: never rely on an LLM remembering that it already performed an irreversible operation.
The Security Boundary Belongs Outside the Model
Giving an agent tools is easy. Giving it the correct authority to use those tools is much harder.
Consider a coding agent with access to GitHub, AWS, Kubernetes, Slack, production logs, and databases. The naive question is whether the agent can call the AWS tool. The production question is:
Which AWS operations may this particular execution perform, against which resources, under which conditions, and for how long?
The useful analogy is IAM. Nobody hands every backend service administrator privileges on the grounds that the service needs AWS access, and agents should not receive broad authority just because they need tools. Permissions should be scoped to the execution:
Diagram source
flowchart TD
A[Agent execution] --> B[Policy engine]
B --> C[Read repository]
B --> D[Create branch]
B --> E[Open pull request]
B --> F[Merge to main]
B --> G[Deploy production]
C --> C1[Allowed]
D --> D1[Allowed]
E --> E1[Allowed]
F --> F1[Requires approval]
G --> G1[Denied]Another execution by the same agent might receive completely different capabilities. A production system should remain safe even when the model makes a bad decision.
Notice the gradient in that diagram. Reading a repository requires no approval. Opening a pull request requires very little. Merging or deploying to production requires more, and deleting production data should require considerably more, if it is permitted at all. There is a tendency to judge agents by how little human involvement they need, and that is probably the wrong metric. The better question is how much autonomy a given operation can safely tolerate. Autonomy should be constrained by consequence, and this remains true even if models become dramatically more capable. A hypothetical model that makes excellent decisions would still need authorization boundaries. Reliability and permission are different properties.
The same reasoning applies to the execution environment. If an agent can run shell commands, install packages, execute downloaded binaries, modify files, access credentials, and make arbitrary network requests, then its execution environment is part of your security architecture. You would not normally allow untrusted user input to generate unrestricted shell commands on one of your production application servers. Putting an LLM between the user and the shell does not suddenly make that architecture safe.
Diagram source
flowchart LR
U[User task] --> A[Agent runtime]
A --> P[Policy layer]
P --> S[Ephemeral sandbox]
S --> F[Scoped filesystem]
S --> N[Restricted network]
S --> C[CPU / memory limits]
S --> T[Approved tooling]
S --> R[Execution result]
R --> AWhether the sandbox is a container, Linux namespaces, a microVM, WebAssembly, or a dedicated ephemeral VM is secondary. The question that matters is what this execution can actually damage if it behaves unexpectedly. That is a blast-radius problem.
Observability Means Reconstructing Execution
Traditional service observability tells you how many requests are failing, which endpoint is slow, which dependency is timing out, and which deployment introduced a regression. Agents add another question:
How did this execution arrive at this action?
That does not mean trying to persist some hidden chain-of-thought from the model. It means recording the observable execution trajectory: model invocations and their metadata, input artifact versions, tool requests and arguments, authorization decisions, tool responses, state transitions, retries, errors, human approvals, token consumption and cost, and generated artifacts. Conceptually:
execution_id: run-9182
10:01:13 model.invoke
10:01:14 model.completed
10:01:15 tool.github.get_issue
issue=184
result=success
10:01:18 tool.github.read_file
result=success
10:01:24 tool.sandbox.run_tests
result=failed
10:01:26 model.invoke
10:01:29 model.completed
10:01:32 tool.github.write_file
result=success
10:01:38 tool.sandbox.run_tests
result=success
10:01:41 policy.evaluate
capability=merge_to_main
result=requires_approval
10:01:42 approval.requested
Now an engineer can inspect what happened. Without this history, an incident eventually becomes "the agent did something weird," and debugging stops there.
There is a temptation to treat agent observability as an entirely new discipline. Some new primitives are useful, but most of the underlying problem is distributed tracing:
Diagram source
flowchart TD
A[Agent run] --> B[Model invocation]
A --> C[Tool invocation]
A --> D[State transition]
A --> E[Approval]
A --> F[Evaluation]
C --> C1[HTTP request]
C --> C2[Database query]
C --> C3[Sandbox process]
C1 --> G[Existing distributed trace]
C2 --> G
C3 --> GIf an agent calls an API which calls three microservices and a database, you should still be able to correlate that operation with the normal distributed trace. The agent trace complements existing telemetry rather than replacing it, and ideally there is one execution identity connecting both worlds.
Testing Changes Too
Deterministic software gives us a useful abstraction: input X produces output Y. Agent behavior does not always satisfy it. Two executions may take different paths while still producing acceptable results.
Suppose a coding agent receives:
Fix the race condition in the cache.
One execution changes the locking strategy. Another removes the shared mutable state entirely. Both could be correct, so testing the exact generated patch makes little sense. What matters is whether the result satisfies the system's invariants:
requirements:
tests:
unit: pass
integration: pass
race_detector: pass
repository:
unrelated_files_modified: false
performance:
regression_threshold_percent: 5
security:
forbidden_capabilities_used: false
This pushes some testing upward, from exact output matching toward outcome and invariant evaluation. It should not replace conventional testing. Deterministic logic still gets unit tests, deterministic boundaries still get integration tests, invariants still get property-based tests, and agent evaluations cover the parts whose behavior is truly nondeterministic.
Diagram source
flowchart BT
A[Unit tests] --> B[Integration tests]
B --> C[Agent evaluations]
C --> D[Staging / canary execution]
D --> E[Production]The higher you move through the stack, the more expensive and probabilistic validation becomes. That makes the deterministic foundations more important, not less.
Protocols Do Not Eliminate Orchestration
Protocols such as the Model Context Protocol reduce the integration cost of exposing tools and external systems to agents. That is useful, but interoperability and execution architecture are different problems. A protocol defines how an agent discovers or invokes a capability. It does not solve durable execution, retries, idempotency, scheduling, authorization, distributed state, auditing, or failure recovery. Those responsibilities live elsewhere: the runtime owns execution, the state store owns durability, the policy layer owns authorization, the tool servers expose capabilities, and the telemetry stack records what happened. Keeping them separate is considerably easier to reason about than turning every tool integration into part of the agent runtime itself.
It also means the protocol can be stateless while the workload is stateful. A tool invocation can be logically simple, tool(args) -> result, while the workflow using that tool is anything but:
Diagram source
flowchart TD
A[Execution started] --> B[Tool A]
B --> C[Checkpoint]
C --> D[Tool B]
D --> E[Wait 3 hours]
E --> F[Human approves]
F --> G[Checkpoint]
G --> H[Tool C]
H --> I[Complete]There is no contradiction here. Keeping capabilities as stateless as practical while centralizing durable execution state often produces a cleaner system. The tool should not need to know the entire history of the agent. The orchestrator should.
We Have Seen Most of These Problems Before
This might be the most useful realization about production agents. Many supposedly novel agent-infrastructure problems map directly onto mature software-engineering concepts.
| Agent problem | Existing systems concept |
|---|---|
| Long-running execution | Durable workflows |
| Resume after failure | Checkpointing |
| Repeated actions | Idempotency |
| Multi-step tasks | State machines |
| Tool permissions | IAM / capability security |
| Tool isolation | Sandboxing |
| Agent execution history | Distributed tracing |
| Human confirmation | Workflow approval gates |
| Partial failure | Compensation / sagas |
| External events | Event-driven architecture |
| Concurrent agents | Distributed coordination |
The LLM changes the behavior of the worker. It does not repeal the fundamental laws of distributed systems. Networks still fail. Processes still crash. Messages still arrive twice. External APIs still time out after actually completing an operation. Credentials can still be abused. State can still become inconsistent. Humans still need to understand what happened after an incident.
Put everything together and a production agent platform starts looking something like this:
Diagram source
flowchart TB
U[User / Event] --> API[Agent API]
API --> ORCH[Durable Agent Runtime]
ORCH <--> STATE[(Execution State)]
ORCH --> MODEL[Model Provider]
ORCH --> POLICY[Policy Engine]
ORCH --> OBS[Telemetry / Audit]
POLICY --> TOOLGW[Tool Gateway]
TOOLGW --> GH[GitHub]
TOOLGW --> AWS[Cloud APIs]
TOOLGW --> DB[(Databases)]
TOOLGW --> SANDBOX[Execution Sandbox]
ORCH --> APPROVAL{Approval Required?}
APPROVAL -- Yes --> HUMAN[Human]
HUMAN --> ORCH
APPROVAL -- No --> TOOLGW
OBS --> TRACE[(Trace Store)]
OBS --> METRICS[(Metrics)]
OBS --> LOGS[(Logs)]There are many ways to implement each component. What matters is that the model is a relatively small piece of the architecture. Most of the machinery exists to make autonomous execution durable, recoverable, constrained, and auditable.
The Model Is Only One Failure Domain
Better models will improve agents. They will select tools more accurately, understand larger codebases, recover from mistakes more effectively, and complete increasingly complex tasks. But model quality cannot give you exactly-once execution. It cannot make an unsafe permission model safe. It cannot reconstruct state your application never persisted or an execution history you never recorded, and it cannot determine whether retrying a payment request will charge someone twice unless the surrounding system can answer that question.
Those responsibilities belong to the system around the model, which is why I think the next stage of agent engineering will look less like prompt engineering and more like backend, platform, and distributed-systems work. We already know how to make an LLM call tools. The interesting question is:
How do we make autonomous execution reliable when everything around it can fail?
Once agents begin doing real work, that becomes the problem that matters.
hzerrad@insights:~$contact --type architecture-audit
Know what's breaking before you rebuild it.
I review backend and data architectures for teams about to commit a quarter to a migration, a rewrite, or a new platform. Two weeks, fixed scope. You get:
- A map of what actually talks to what
- A ranked list of what's costing you, with numbers
- A sequenced plan to fix it, with the trade-offs named