Distributed Systems, Networking and Databases
An agent is a distributed system the moment it calls a model. Plan for slow, lost, repeated and out-of-order work.
Agents coordinate models, tools, databases and queues across a network, where any call can be slow, fail or succeed without the caller finding out. Set timeouts, retry only what is safe to repeat, use idempotency keys for actions, protect shared records against concurrent writes, save state changes and messages together, and assume messages may arrive more than once.
What you will learn: partial failure, networking and API basics, retries and idempotency, concurrency and coordination, transactions and consistency, and event-driven delivery.
Prerequisites: basic programming and web requests.
Partial failure
Inside one program, a function either returns or raises an error. Across a network there is a third outcome: unknown. If no reply arrives, the request may have been lost, still be running, or have finished while the reply disappeared.
Agents make this sharper. A model that receives "error: timeout" may simply try the action again. Your tool layer, not the prompt, has to make that harmless.
Networking and API fundamentals
| Concept | What to know |
|---|---|
| DNS, TCP, TLS | Name lookup, reliable byte stream, encryption and server identity; each can fail separately |
| HTTP methods | GET reads. PUT and DELETE are defined as idempotent. POST is not by default |
| Status codes | 2xx success, 4xx caller error, 429 too many requests, 5xx server error |
| Streaming | Partial responses arrive over time and can break midway |
| Rate limits | Respect signals such as Retry-After and keep your own limits |
| Pagination | One page is not the whole answer; tell the agent if more exists |
| Asynchronous jobs | Accept the request, return a job identifier, report status later |
| Authentication | Short-lived, scoped credentials held by trusted code |
Tool results should distinguish "no data", "not allowed", "temporary failure" and "unknown outcome". Collapsing them into one error invites the wrong next step. See Reliable Tool Execution and Error Recovery.
Timeouts, retries and backoff
- Every call has a timeout, and the whole task has a deadline that inner calls must fit within.
- Retry only temporary failures, a limited number of times.
- Back off exponentially with jitter, a random spread, so that many clients do not retry together.
- Retry at one layer. Three layers each making three attempts can produce twenty-seven calls.
- Stop calling a failing service for a while (a circuit breaker) and give the agent a clear fallback.
Idempotency
An operation is idempotent if doing it twice has the same effect as doing it once. For actions that are not naturally so, the caller sends a unique key and the server remembers the result.
"""A timeout does not mean failure: make retries safe with a key."""
import uuid
class PaymentService:
def __init__(self):
self.payments, self.seen = [], {}
def pay(self, amount, key=None):
if key in self.seen:
stored_amount, receipt = self.seen[key]
if stored_amount != amount:
raise ValueError("key reused with different request")
return receipt
self.payments.append(amount)
receipt = f"receipt-{len(self.payments)}"
if key:
self.seen[key] = (amount, receipt)
return receipt
def call_with_lost_reply(service, amount, key):
lost = True # first reply never arrives
for attempt in (1, 2):
receipt = service.pay(amount, key)
if lost:
lost = False
continue # caller sees a timeout and retries
return receipt, attempt
for label, key in (("no key", None), ("with key", str(uuid.uuid4()))):
service = PaymentService()
receipt, attempts = call_with_lost_reply(service, 50, key)
print(f"{label:<9} attempts={attempts} payments made="
f"{len(service.payments)} got {receipt}")
try:
service.pay(75, key)
except ValueError as error:
print("refused:", error)
Output:
no key attempts=2 payments made=2 got receipt-2
with key attempts=2 payments made=1 got receipt-1
refused: key reused with different request
Without a key the retry created a second payment. With a key the server returned the original receipt. The final line matters too: reusing a key for a different amount is refused rather than silently answered with the old receipt.
Create the key in trusted code from the task and the intended action, and store it before the first attempt, so that a restarted process reuses it. If the model invents a new key on each try, the protection vanishes. The server must also handle two simultaneous requests with the same key, usually with a unique constraint. An HTTP Idempotency-Key header is widely used, but the IETF specification for it was still an Internet-Draft, not a published standard, in November 2026, so follow each provider's documentation.
Concurrency, parallelism and coordination
Concurrency means several tasks are in progress during the same period. Parallelism means they execute at the same instant. Agents waiting on the network benefit from concurrency even on one processor.
| Hazard | Example | Remedy |
|---|---|---|
| Race condition | Two agents read a balance, both spend it | Atomic update or transaction |
| Lost update | The second write erases the first | Version check on write |
| Deadlock | Each waits for the other's lock | Consistent lock order, timeouts |
| Starvation | Low-priority work never runs | Fair queues |
| Overload from fan-out | One request starts hundreds of calls | Concurrency limits |
| Stale lock holder | A paused worker writes after losing its lease | Fencing tokens |
Optimistic concurrency is often the simplest choice: read a record with its version, and update only if the version is unchanged. On conflict, re-read and reconsider. For an agent, reconsider means looking at the new data, not merely resending the old decision.
Leases and fencing tokens
A distributed lock is usually a lease that expires, so that a crashed holder does not block others for ever. But a holder that merely pauses may wake and carry on.
"""A lease can expire while its holder is paused: use fencing tokens."""
class LockService:
def __init__(self):
self.token, self.expires = 0, 0
def acquire(self, now, lease=10):
if now < self.expires:
return None
self.token += 1
self.expires = now + lease
return self.token
class Storage:
def __init__(self, fenced):
self.fenced, self.highest, self.value = fenced, 0, None
def write(self, token, value):
if self.fenced and token < self.highest:
return f"rejected old token {token}"
self.highest = max(self.highest, token)
self.value = value
return f"written with token {token}"
for fenced in (False, True):
lock, store = LockService(), Storage(fenced)
slow = lock.acquire(now=0)
print(f"fencing {'on' if fenced else 'off'}: agent A holds token {slow}")
print(" agent B at t=5: ", lock.acquire(now=5))
fast = lock.acquire(now=15) # A paused; its lease ran out
print(" agent B at t=15:", store.write(fast, "plan from B"))
print(" agent A wakes: ", store.write(slow, "stale plan from A"))
print(" final value: ", store.value)
Output:
fencing off: agent A holds token 1
agent B at t=5: None
agent B at t=15: written with token 2
agent A wakes: written with token 1
final value: stale plan from A
fencing on: agent A holds token 1
agent B at t=5: None
agent B at t=15: written with token 2
agent A wakes: rejected old token 1
final value: plan from B
Without fencing, the stale plan from agent A overwrites the newer one. With a token that rises at each acquisition, storage rejects the old writer. The essential point is that the resource being written checks the token. A lock service alone cannot stop a late write.
Databases and transactions
A transaction groups changes so that all happen or none do. The classic properties are atomicity, consistency, isolation and durability. Isolation comes in levels, and weaker levels permit specific anomalies, so check your database's definitions instead of assuming.
| Store | Strength | Agent use |
|---|---|---|
| Relational | Transactions, constraints, joins | Task state, approvals, business records |
| Key-value | Simple, fast access | Sessions, caches |
| Document | Flexible nested records | Conversation and artifact storage |
| Search and vector | Ranking by text or similarity | Retrieval; usually a derived copy |
| Log or stream | Ordered, replayable events | Integration and audit |
Do not hold a database transaction open while waiting for a model. Read, decide outside the transaction, then write with a version check.
Delivery semantics
| Guarantee | Meaning | Consequence |
|---|---|---|
| At most once | No redelivery | Messages can be lost |
| At least once | Redeliver until acknowledged | Duplicates happen |
| Exactly once | Effect applied once within a defined boundary | External side effects still need care |
A frequent bug: save a change to the database, then publish a message, and crash between the two. The transactional outbox writes the change and the pending message in one transaction. A relay publishes it afterward, and consumers discard duplicates.
"""Transactional outbox: save the change and the message together."""
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE tickets(id TEXT PRIMARY KEY, state TEXT);
CREATE TABLE outbox(seq INTEGER PRIMARY KEY, body TEXT, sent INT DEFAULT 0);
CREATE TABLE handled(seq INTEGER PRIMARY KEY);
""")
emails = []
def close_ticket(ticket, crash=False):
try:
with db: # one transaction
db.execute("INSERT INTO tickets VALUES (?, 'closed')", (ticket,))
db.execute("INSERT INTO outbox(body) VALUES (?)",
(f"{ticket} closed",))
if crash:
raise RuntimeError("process died")
except RuntimeError as error:
print(f"{ticket}: {error}, nothing saved")
def consume(seq, body):
with db:
cursor = db.execute("INSERT OR IGNORE INTO handled VALUES (?)", (seq,))
if cursor.rowcount == 0:
return "duplicate skipped"
emails.append(body) # real systems need an idempotent send here
return "handled"
def relay(lose_ack):
rows = db.execute("SELECT seq, body FROM outbox WHERE sent=0").fetchall()
for seq, body in rows:
print(f"deliver #{seq} '{body}': {consume(seq, body)}")
if not lose_ack:
with db:
db.execute("UPDATE outbox SET sent=1 WHERE seq=?", (seq,))
close_ticket("T1")
close_ticket("T2", crash=True)
relay(lose_ack=True)
relay(lose_ack=False)
relay(lose_ack=False)
print("tickets:", db.execute("SELECT count(*) FROM tickets").fetchone()[0],
"| emails sent:", len(emails))
Output:
T2: process died, nothing saved
deliver #1 'T1 closed': handled
deliver #1 'T1 closed': duplicate skipped
tickets: 1 | emails sent: 1
The crashed operation saved neither ticket nor message. The first delivery lost its acknowledgment, so the message came again and the consumer skipped it. One ticket produced one email. The comment in the consumer is important: appending to a local list is not a real email, and no database transaction covers a real send. If you commit the "handled" record first and then crash, the email is lost. If you send first and crash before committing, it goes out again. Either use an email service that accepts an idempotency key, or decide which of the two rare outcomes is acceptable.
Event-driven design
- Events state facts ("ticket closed"); commands request actions ("close ticket").
- Order is limited, usually to one key or partition.
- Version your event formats and keep consumers tolerant of added fields.
- Use dead-letter queues with an owner for messages that repeatedly fail.
- Apply back pressure so that producers slow down when consumers fall behind.
- Trace across messages with a correlation identifier.
See Event-Driven and Background Agents for agents triggered this way.
Consistency across copies
When data is replicated, readers may see old values. The CAP result says that during a network partition a replicated system cannot guarantee both linearizable consistency and availability of every non-failing node. In ordinary operation there is also a trade between latency and consistency. For agents, ask for each read: would a few seconds of staleness change the action? Reading your own recent write matters especially, or the agent may conclude that its update failed and repeat it.
Long-running work
For a process spanning several services, a saga records each completed step and defines compensating actions, such as releasing a reservation. Compensation is a new action, not time travel: an email cannot be unsent. Durable execution engines persist progress so work resumes after a crash, as described in Durable Execution, Checkpoints and Approvals.
Agreement
Consensus protocols such as Raft let a group of servers agree on an ordered log despite some failures. Use a proven database or coordination service. Do not ask several language models to vote and call it consensus: their errors can be shared, and voting provides none of those guarantees.
A travel agent occasionally books two rooms. Traces show a slow booking service, a client timeout and a retry chosen by the model. The team adds a stored operation key, a status lookup for unknown outcomes and a unique constraint at the service, then tests by delaying replies on purpose.
Testing failure on purpose
| Inject | Expect |
|---|---|
| Lost reply after success | One effect, correct final report |
| Slow dependency | Deadline respected, clear fallback |
| Duplicate and reordered messages | Same final state |
| Crash between steps | Resume or compensate |
| Concurrent edits | Conflict detected |
| Rate limit responses | Backoff without a retry storm |
Seeing what happened
When work crosses several services, logs from any one of them tell only part of the story. Give each task an identifier at the start and pass it through every model call, tool call and message. Record for each attempt what was sent, the outcome including "unknown", the time taken and the idempotency key. With that, a duplicate booking can be traced to a specific retry in minutes. Without it, the same investigation becomes guesswork about which of several near-simultaneous requests did what.
Watch a few system-level signals: the share of calls retried, queue age, conflicts on version checks and messages in dead-letter queues. A rising retry rate often appears before users notice anything, and retries add load exactly when a dependency is struggling. Clocks on different machines also disagree, so avoid deciding order by comparing their timestamps when a version number or sequence from one source is available. Agent Tracing and OpenTelemetry shows how to propagate context.
Common mistakes
- Treating a timeout as failure.
- Letting the model decide retry behavior.
- Retrying at several layers.
- Generating a fresh idempotency key per attempt.
- Trusting a lease without fencing at the resource.
- Publishing messages outside the transaction that changed the data.
- Assuming ordered, single delivery.
Checklist
- Calls have timeouts and tasks have deadlines.
- Retries are limited, jittered and in one layer.
- State-changing actions use stored idempotency keys.
- Unknown outcomes can be checked.
- Shared records use versions or transactions.
- Locks protect resources with fencing where needed.
- Consumers tolerate duplicates and reordering.
- Failure injection runs in tests.
Frequently asked questions
Do I need all this for one agent?
Timeouts, idempotent actions and saved state matter even for one agent that changes real records. Add queues and locks when concurrency or scale requires them.
Is GET always safe for an agent to repeat?
It is meant to read without side effects, but check the actual service. Repeats also cost money and count against rate limits.
Can a queue guarantee exactly-once processing?
Only within the limits its documentation states. Design consumers and external actions so that a repeat does no harm.
What should an agent do with an unknown outcome?
Query the status using the operation identifier. If that is impossible, report the uncertainty and escalate instead of repeating a consequential action.
References and further reading
- RFC 9110: HTTP semantics, including idempotent methods
- IETF draft: the Idempotency-Key header
- AWS Builders' Library: timeouts, retries and backoff with jitter
- Kleppmann: how to do distributed locking
- Transactional outbox pattern
- The Raft consensus algorithm
Next steps
Graph, Game, Control Theory and Reinforcement Learning
Reason about workflows and feedback.
Workflow Versioning, Testing and Resilience
Apply this to orchestration.
Parallelism, Deadlocks and Conflict Resolution
Coordinate several agents.