Skip to content

    AI Architect

    Multi-Agent and Event-Driven AI Architecture

    When several agents beat one, and how to run them over events safely: partitions, offsets, idempotency keys, outbox, sagas and dead-letter queues.

    By Published 27 min read

    Share

    This lesson is part of AI Architect (Intermediate): Design the System. Enroll for free, then sign in, to read it in full.

    What you'll learn: when several agents beat one, and how to connect agents through events without duplicate side effects: partitions, offsets, idempotency keys, the transactional outbox, sagas and dead-letter queues, each with worked numbers.

    At a glance

    Figure 1. Agents connected by events, with the four safety mechanisms

    Agents connected by events with four safety mechanismsOrchestrator to Outbox row; Outbox row to Event bus (relay publishes); Event bus to Workers (deliver); Workers to Event bus (result event); Event bus to Orchestrator (deliver result); Workers to Tool call; Workers to Dead-letter queue (keeps failing); Orchestrator to Saga (a step failed); Saga to Tool callOrchestrator: durable job recordOrchestratordurable jobrecordOutbox row: same transactionOutbox rowsame transactionEvent bus: keyed by job idEvent buskeyed by job idWorkers: dedupe on event idWorkersdedupe on eventidDead-letter queueDead-letterqueueTool call: idempotency keyTool callidempotency keySaga: compensations in reverseSagacompensations inreverserelay publishesdeliverresult eventdeliver resultkeeps failinga step failed

    How to read this: dotted arrows are asynchronous events, solid arrows are direct calls, and each box is one fix for a duplicate, loss or half-finished-work problem.

    • More than one agent pays off only for valuable, parallelisable work; otherwise use one agent or a fixed workflow.
    • Kafka orders events per partition: the key is your ordering promise, the partition count your parallelism ceiling.
    • Delivery is at-least-once, so commit offsets after processing and make every effect idempotent.
    • An outbox makes a state change and its event atomic, a saga replaces rollback with compensations, and a dead-letter queue keeps one bad message from stopping the line.

    The real-world problem

    Composite scenario, not a real company. An online marketplace chains three steps over an event stream: an intake agent classifies a return, a resolution agent proposes a refund, and an execution step posts it through a payments tool. A deployment restarts all workers, the stream replays recent events and some customers are refunded twice. A week later an approved refund is posted after the customer cancelled the order.

    No prompt was at fault: the design assumed every event arrives once, in order, and that repeating a model call is harmless.

    After this page you will be able to

    • Decide whether a task needs one agent, a fixed workflow or an orchestrator with workers, and state the cost.
    • Trace an event through partitions to a consumer group and say what a restart does under each offset-commit order.
    • Design an idempotent consumer so a side effect is applied once.
    • Choose between an idempotency key, an outbox, a saga and a dead-letter queue for a given failure.
    • Define the ordering you promise and what a poison message does to it.

    Core concepts

    When more than one agent helps, and when it does not

    Source What it says What it means here
    Anthropic, "Building effective agents" (December 2024) Workflows are "systems where LLMs and tools are orchestrated through predefined code paths"; agents are "systems where LLMs dynamically direct their own processes and tool usage". Recommends "finding the simplest solution possible, and only increasing complexity when needed" Start simple; pay for complexity only when it buys something
    Anthropic, multi-agent research system post (13 June 2025) Multi-agent systems "excel at valuable tasks that involve heavy parallelization, information that exceeds single context windows, and interfacing with numerous complex tools" The three conditions that justify several agents
    Same post "In our data, agents typically use about 4× more tokens than chat interactions, and multi-agent systems use about 15× more tokens than chats." Derived, not stated: 15 / 4 = 3.75 times a single-agent run
    Same post "For economic viability, multi-agent systems require tasks where the value of the task is high enough to pay for the increased performance." Shared context or many dependencies are a poor fit; coding has fewer parallelisable tasks than research The value must cover the extra tokens

    Figure 2. Do I need more than one agent?

    flowchart TD accTitle: Choosing between a workflow, one agent and several agents accDescr: A chain of questions leads from a fixed workflow, to a single agent with tools, to an orchestrator with workers. Several agents are chosen only when subtasks are independent, parallelisable and valuable enough to pay for the extra tokens. Tasks whose parts share context or depend on each other stay with one agent. Start(["A task needs an LLM"]) Q1{"Can fixed code paths of LLM calls do it?"} Q2{"Does one agent fit in one context and budget?"} Q3{"Are the subtasks independent and parallelisable?"} Q4{"Is the result valuable enough for roughly 3 to 4 times the tokens?"} A1["Workflow: predefined steps"] A2["Single agent with tools"] A3["Orchestrator with workers"] A4["Single agent, improve tools and prompt"] Start --> Q1 Q1 -->|"yes"| A1 Q1 -->|"no"| Q2 Q2 -->|"yes"| A2 Q2 -->|"no"| Q3 Q3 -->|"no, parts share context or depend on each other"| A4 Q3 -->|"yes"| Q4 Q4 -->|"yes"| A3 Q4 -->|"no"| A4

    How to read this: follow yes or no from the top to the first rectangle; the 3 to 4 times is the derived 15 / 4 = 3.75 ratio.

    If each step succeeds independently with probability p, n steps succeed with probability p^n. Real steps are not independent, so this is the smallest model of the research post's statement that "errors compound", not a forecast.

    Step success p Steps n Chain succeeds (p^n)
    0.98 5 0.9039, about 90%
    0.95 10 0.5987, about 60%
    Check yourself: how likely is a 10-step chain of 0.98-reliable steps to succeed, compared with the 0.95 row?

    0.98^10 is about 0.817, so about 82% against 60%. A small gain per step compounds across a long chain.

    Try the quiz; each answer follows from the table and Figure 2.

    One agent, a workflow or several agents? (interactive when JavaScript is on)

    Five parallel agents would all edit the same repository. What do the published criteria suggest?

    • Go ahead: more agents is faster
    • One agent, with better tools and prompt
    • A fixed workflow with five steps
    Answer

    One agent, with better tools and prompt. Shared context and many dependencies are a poor fit, and coding has fewer parallelisable tasks than research.

    Every return is classified into one of three categories, then routed. The steps never change. Which design?

    • Orchestrator with workers
    • Workflow: predefined steps
    • Handoff chain of five agents
    Answer

    Workflow: predefined steps. Fixed code paths can do it, so Figure 2 stops at the first rectangle.

    A high-value research question spans many independent sources and exceeds one context window. Which design?

    • Orchestrator with workers
    • A single agent in one long context
    • A fixed workflow
    Answer

    Orchestrator with workers. Independent, parallelisable subtasks beyond one context, valuable enough to pay for roughly 3 to 4 times the tokens.

    Orchestrator-worker

    Figure 3. Orchestrator and Workers connected by an Event bus

    Orchestrator and Workers connected by an Event busClient app to API gateway (HTTPS); API gateway to Orchestrator (verified job); Orchestrator to Approval service (approval request); Orchestrator to Event bus (task events); Event bus to Orchestrator (deliver result); Event bus to Worker (deliver task); Worker to Event bus (result event); Orchestrator to Trace store (trace); Worker to Trace store (trace); Worker to Tool server (idempotency key); Worker to Model gateway (prompt); Model gateway to LLM provider (HTTPS)OUR SYSTEMSClient appClient appAPI gatewayAPI gatewayApproval serviceApprovalserviceOrchestrator: plans, splits, mergesOrchestratorplans, splits,mergesTrace storeTrace storeEvent bus: keyed by job idEvent buskeyed by job idWorker: runs one subtaskWorkerruns one subtaskTool serverTool serverModel gatewayModel gatewayLLM provider: externalLLM providerexternalHTTPSverified jobapproval requesttask eventsdeliver resultdeliver taskresult eventtracetraceidempotency keypromptHTTPS

    How to read this: solid arrows are synchronous calls, dotted arrows are events or traces, and the large box is the system the team runs.

    • The research post's design is orchestrator-worker: "a lead agent coordinates the process while delegating to specialized subagents that operate in parallel".
    • The research post says the lead agent saves its plan to memory because context past 200,000 tokens is truncated, and that synchronous subagents "creates bottlenecks in the information flow between agents"; asynchronous execution is a named future improvement.

    An Event bus gives that asynchrony, and with it duplicates, delay and reordering on every hop.

    Handoffs

    A handoff transfers a task to the next agent with no coordinator staying in control (this course's meaning; products use the word differently). It fits a pipeline of specialists.

    Risk What you do
    Context is lost or bloated per hop Pass a structured record or a reference, as the research post does when subagents pass lightweight references back to avoid a "game of telephone"
    Control can loop Carry a hop counter
    Nobody owns the outcome Prefer an Orchestrator when one result is accountable

    Event-driven decoupling

    An event states a fact that happened (refund.proposed); a command asks for something (post_refund). A bus absorbs bursts as backlog instead of timeouts and lets Workers scale and deploy independently. With a log such as Kafka it also allows replay: "events are not deleted after consumption" and retention is a per-topic setting (Apache Kafka introduction). The costs are eventual consistency, duplicates, ordering only within a partition and harder debugging.

    Use it when work can wait; keep a synchronous call when the user is blocked on the answer.

    Human-in-the-loop in async flows

    A person is another slow consumer. Model the wait as a state in a durable record, never a blocked thread, with a deadline and a defined outcome when it passes (here, expire and do nothing). Run the action with a key derived from the event id, so a redelivered approval cannot run it twice.

    Figure 4. Asynchronous refund chain with a human approval

    sequenceDiagram accTitle: Asynchronous refund chain with human approval accDescr: The Client app submits a return request. The Orchestrator publishes an event, a Worker classifies it and proposes a refund, and the Orchestrator asks the Approval service when the amount is over the limit. If a person decides in time, the Orchestrator posts the refund with an idempotency key derived from the event id. If not, the request expires and nothing is posted. autonumber participant C as Client app participant O as Orchestrator participant B as Event bus participant W as Worker participant A as Approval service participant T as Tool server C->>O: return request with request id r1 O-)B: event return.requested, key order-42, event id e1, correlation id r1 B-)W: deliver e1 Note over W: Agent step - classify the return and propose a refund W-)B: event refund.proposed, key order-42, event id e2, correlation id r1 B-)O: deliver e2 O->>A: approval request, amount over the limit alt A person decides before the deadline A-->>O: approved O->>T: post_refund with idempotency key e2 T-->>O: refund id O-)B: event refund.completed else No decision before the deadline Note over O: Decision - expire the request and do not act O-)B: event refund.expired end O-->>C: outcome at the status endpoint

    How to read this: time runs downward, open-headed arrows are events, and every event carries correlation id r1 and its own event id.

    Observability of async chains

    Carry a correlation id in every event (Figure 4 uses r1), log topic, partition, offset and event id at each hop, alert on consumer lag per partition and on dead-letter depth, and keep the request's state record as the place to ask "where is this job?". See LLM observability.

    Case files

    Three case files show the patterns under pressure. The first two are composite scenarios; the third is a public case, based only on what Anthropic published.

    Under the hood: Partitions, consumer groups and offsets

    Intuition

    Picture notebooks with numbered pages: writers only append, and each page number is an offset. One reader at a time owns a notebook and keeps a bookmark; if that reader leaves, another resumes from the saved bookmark.

    Mechanism

    Figure 5. One event through partitions to a consumer group

    sequenceDiagram accTitle: An event through partitions to a consumer group accDescr: The Orchestrator appends two events with the key claim-77 to Partition 1 and one event with the key claim-12 to Partition 0. Worker A owns Partition 0 and Worker B owns Partition 1, both in one consumer group. Worker B reads offsets 41 then 42 in write order, processes them, and commits offset 43. Order is guaranteed only inside a partition. autonumber participant O as Orchestrator participant P0 as Partition 0 participant P1 as Partition 1 participant K as Group offsets participant WA as Worker A participant WB as Worker B O->>P1: append event key claim-77, assigned offset 41 O->>P0: append event key claim-12, assigned offset 90 O->>P1: append event key claim-77, assigned offset 42 Note over P0,P1: Each partition is its own ordered log, with no order across partitions Note over WA,WB: One consumer group - Partition 0 is assigned to A and Partition 1 to B WB->>K: where is my committed offset for Partition 1 K-->>WB: 41 WB->>P1: poll from offset 41 P1-->>WB: records 41 then 42, in write order Note over WB: Process 41, then 42, and apply their effects WB->>K: commit offset 43 for Partition 1 WA->>P0: poll from its committed offset P0-->>WA: record 90

    How to read this: each partition is its own lifeline with its own offsets, and "Group offsets" is the stored position that survives a restart.

    The Kafka documentation states the pieces precisely:

    1. A topic is spread over "buckets" called partitions; events with the same key "are written to the same partition".
    2. "any consumer of a given topic-partition will always read that partition's events in exactly the same order as they were written".
    3. Consumers sharing a group.id form a group; each partition is "consumed by exactly one consumer within each subscribing consumer group at any given time".
    4. A position is "a single integer, the offset of the next message to consume"; a restarted consumer resumes from the committed one.

    The range assignor gives "the first few consumers" one extra partition when the division is uneven. For 6 partitions and 4 Workers, 6 = 4 x 1 + 2, so Workers 0 and 1 own two each and Workers 2 and 3 own one. With 8 Workers, Workers 6 and 7 own none.

    Lag is log end minus committed offset (this page's reading of the LAG column, which the operations documentation describes as "how far behind the end of the log" a group is).

    Partition Log-end offset Committed offset Lag
    0 1200 1150 50
    1 1180 1180 0
    2 1260 1100 160
    Total 210

    At 30 events per second in and 45 per second consumed, the backlog drains at 15 per second: 210 / 15 = 14 seconds.

    Check yourself: which partition do you look at first, and why does the total hide it?

    Partition 2, with 160 of the 210. A small total can hide one partition far behind, so alert per partition.

    What this means for architects

    What changes What you do
    Parallelism is capped by the partition count Extra Workers sit idle: plan partitions as concurrency, not storage, because model calls are slow
    The key is the ordering promise Use the smallest entity that must stay in order (an order id, not a customer id); a skewed key overloads one partition
    Slowness shows as lag, not errors; auto.offset.reset defaults to latest when the stored offset is gone Alert on lag per partition; prefer none (it throws) for work you cannot lose, or a long outage silently skips to the end
    A Worker that does not call poll within max.poll.interval.ms (default 300000 ms, Kafka 4.3 documentation as of 2026-10-21) is treated as failed Keep a batch of LLM calls well inside it

    Under the hood: At-least-once and effectively-once processing

    Intuition

    Delivery guarantees are statements about a crash at the worst moment (effectively-once processing is the goal). Save your place first and a crash loses work; do the work first and a crash repeats it. "Once" needs the work and the saved place to change together, or the repeat to be harmless.

    Mechanism

    Figure 6. A Worker restart under each offset-commit order

    sequenceDiagram accTitle: Worker restart under two offset-commit orders accDescr: A Worker polls records 100 to 104 and processes 100 to 102 before crashing. If it commits after processing, the committed offset is still 100, so the restarted Worker re-reads 100 to 104 and a dedupe check skips 100 to 102. If it committed before processing, the committed offset is 105 and records 103 and 104 are never processed. autonumber participant W as Worker participant B as Event bus participant T as Tool server participant W2 as Restarted Worker W->>B: poll, receives records 100 to 104 alt Offset committed after processing W->>T: apply effects for 100, 101, 102 Note over W: Crash before the batch is committed Note over B: Committed offset is still 100 W2->>B: where do I resume B-->>W2: offset 100 W2->>T: records 100 to 102 repeat, the dedupe check skips them W2->>T: apply effects for 103, 104 W2->>B: commit offset 105 else Offset committed before processing W->>B: commit offset 105 W->>T: apply effects for 100, 101, 102 Note over W: Crash while working on 103 W2->>B: where do I resume B-->>W2: offset 105 Note over W2: Records 103 and 104 are never processed end

    How to read this: the same crash twice; the top branch repeats work that dedupe absorbs, the bottom loses work nothing can recover.

    Step through the same 5-record batch and crash under each commit order.

    The same crash, two commit orders (records 100 to 104) (interactive when JavaScript is on)

    Commit after processing

    1. Process, then crash. The Worker polls 100 to 104, applies 100 to 102 and crashes. The committed offset is still 100.
    2. Resume. The replacement re-reads all five records.
    3. Dedupe. 3 repeats are skipped, 2 effects applied, offset 105 committed. Nothing is lost.

    Commit before processing

    1. Commit first. The Worker polls 100 to 104 and commits 105 before working.
    2. Process, then crash. It applies 100 to 102 and crashes on 103.
    3. Loss. The replacement resumes at 105: 105 - 103 = 2 records are lost, silently.

    Duplicates after a crash are bounded by the records handled since the last commit: at most one batch of max.poll.records if you commit after every batch. The Kafka documentation describes each layer and where it stops.

    Setting or order What the documentation says Covers
    Read, save position, process "At-most-once": after a failure messages "may not be processed" Loss
    Read, process, save position At-least-once; Kafka "guarantees at-least-once delivery by default"; idempotent updates (overwriting by primary key) make duplicates harmless Duplicates
    Idempotent producer Retries add no duplicates to the log, but only within "a single session"; enable.idempotence defaults to true from Kafka 3.0 The producer's own retries
    An external system Exactly-once is supported inside Kafka Streams and via transactions with read-committed consumers; an external system "generally requires cooperation" A refund over HTTP is external: the key is on you

    "Effectively-once" means at-least-once delivery plus an idempotent effect: store the consumer's position in the same transaction as the output, or make the write idempotent (both discussed in the design documentation).

    What this means for architects

    What changes What you do
    Losing a refund is worse than repeating one Commit after processing and dedupe with a unique key, before the model call, reusing the stored result (a repeat can return different text); price repeats with the cost estimator
    "Exactly-once" has a scope Real for Kafka-to-Kafka; for the payments call it is your idempotency design
    enable.auto.commit defaults to true (5000 ms) and the committed offset can run ahead of the work Turn it off for agent Workers

    Under the hood: Idempotency keys

    Intuition

    An idempotency key is a receipt number the caller attaches to a request. Show the same receipt twice and the server returns the first outcome instead of acting again. That makes the retry a timeout forces on you safe, because a timeout does not say whether the first attempt happened.

    Mechanism

    Figure 7. Life of one idempotency key record

    stateDiagram-v2 accTitle: Life of one idempotency key record accDescr: A key starts with no record. The first request stores the key with a fingerprint of the payload and the record is in progress. When the operation finishes the response is saved and the record is completed. The same key during processing returns a conflict, the same key with a different payload is rejected, and the same key with the same payload returns the saved response. After the retention period the record disappears. [*] --> NoRecord NoRecord --> InProgress: first request, key and payload fingerprint stored InProgress --> Completed: operation finishes and response saved InProgress --> InProgress: same key while running returns 409 InProgress --> NoRecord: failure before any effect, reservation released Completed --> Completed: same key and same fingerprint returns the saved response Completed --> Completed: same key and different fingerprint returns 422 Completed --> NoRecord: retention period over

    How to read this: each box is the stored state of one key and each arrow what a request or the clock does to it.

    Figure 8. A retried tool call with the same key

    sequenceDiagram accTitle: Retried tool call with the same idempotency key accDescr: The Orchestrator calls the Tool server with key e2. The Tool server reserves the key in an idempotency store, creates the refund at the payments system passing the key along, and saves the response. The reply is lost, the Orchestrator retries with the same key, and the Tool server returns the saved refund instead of creating another. autonumber participant O as Orchestrator participant T as Tool server participant S as Idempotency store participant P as Payments system O->>T: post_refund order-42, key e2 T->>S: reserve key e2 with payload fingerprint S-->>T: reserved, no earlier record T->>P: create refund and pass key e2 along P-->>T: refund r-77 created T->>S: save response for key e2 Note over O,T: The reply to the Orchestrator is lost, so it times out and retries O->>T: post_refund order-42, key e2, same payload T->>S: look up key e2 S-->>T: completed, saved response refund r-77 T-->>O: refund r-77, nothing is created again Note over T,P: If the Tool server crashed before step 6, the store would show in progress, and only the key passed to the payments system prevents a second refund

    How to read this: steps 1 to 6 are the first attempt, 7 to 10 the retry, and the last note is the crash window a key store alone cannot close.

    Stripe documents one concrete design for its v1 API.

    Design point What Stripe documents
    The key Client-generated (V4 UUIDs suggested, up to 255 characters), sent in the Idempotency-Key header
    What is saved "the status code and body of the first request made with a given idempotency key after endpoint execution begins"; retries return it, "including 500 errors"; changed parameters are an error
    Expiry Keys may be removed once at least 24 hours old; a reused key then starts a new request

    The IETF effort is not a standard: the datatracker shows draft-ietf-httpapi-idempotency-key-header as an Expired Internet-Draft (revision 07, 2025-10-15), "Expired & archived". Its design is still useful: HTTP 400 for a missing required key, 422 for the same key with a different payload and 409 while the original request is still being processed.

    Worked numbers. Keys are kept 24 hours and the topic keeps events 7 days. A Worker paused for 2 days (48 hours) and then replaying reaches events whose keys expired (24 < 48), so an effect can run again. Retention must cover the longest period one event can be redelivered or replayed; otherwise extend it or store the key with the business record.

    Check yourself: a Worker is paused for 3 days with 7-day topic retention and 24-hour keys. Is a duplicate refund possible?

    Yes, if the event is redelivered. 24 hours is far shorter than 3 days, so the key is gone, and 7-day retention keeps the event available to replay.

    What this means for architects

    What changes What you do
    A key made fresh on each retry defeats the purpose Derive it from the event (the event id or a hash of the business identity)
    The key only works where it is checked Reserve it atomically in the same transaction as the effect, or pass it to the system that performs the effect (Figure 8's last note)
    LLM answers are not deterministic Return the saved response, so a second delivery does not ask the model again
    A key expires Publish the retention and treat 409 and 422 as expected

    Under the hood: The outbox pattern

    Intuition

    A service that changes its database and then publishes an event makes two writes to two systems, and a crash can fall between them. Publish first and the event can announce something that never committed; commit first and the event can be lost. The transactional outbox makes the second write part of the first.

    Mechanism

    The microservices.io pattern asks "How to atomically update the database and send messages to a message broker?" The service stores each message in an outbox table in the same local transaction as its business update, and a separate relay (a polling publisher or transaction log tailing) publishes it, so messages are sent "if and only if the database transaction commits". The price: the relay may publish twice, so consumers must be idempotent.

    Figure 9. Outbox with a polling relay and a duplicate publish

    sequenceDiagram accTitle: Outbox with a polling relay accDescr: The Orchestrator updates the refund case and inserts an outbox row in one database transaction. A relay polls the outbox, publishes the event to the Event bus, and marks the row sent. If the relay crashes after publishing and before marking the row, it publishes the same event again after restart and the Worker's dedupe check absorbs the duplicate. autonumber participant O as Orchestrator participant D as Service database participant R as Outbox relay participant B as Event bus participant W as Worker O->>D: one transaction - update refund case and insert outbox row e9 D-->>O: committed R->>D: poll for unsent rows D-->>R: row e9 R-)B: publish event e9 Note over R: Crash before the row is marked sent R->>D: after restart, poll for unsent rows D-->>R: row e9 again R-)B: publish event e9 again R->>D: mark e9 sent B-)W: deliver e9 twice Note over W: The dedupe check on event id e9 applies the effect once

    How to read this: steps 1 and 2 are the single transaction, 3 to 5 the first publish, 6 to 9 the retry after the crash.

    Compare a crash with and without the outbox.

    A crash between the database write and the event (interactive when JavaScript is on)

    Publish after commit (no outbox)

    1. Commit. The Orchestrator commits the refund-case update.
    2. Crash. The process dies before it publishes refund.proposed.
    3. Event lost. The database says one thing, the bus says nothing, and no Worker hears about the case.

    Outbox

    1. One transaction. The case update and the outbox row are committed together, or neither is.
    2. Crash. The process dies before publishing, but the outbox row is stored.
    3. Relay. The relay finds the unsent row and publishes it. If the relay itself crashes after publishing, the event goes out twice and the Worker's dedupe absorbs it.

    A polling relay adds delay between commit and publish: for commits spread evenly, the mean is T / 2 and the worst case is T plus query and publish time. At T = 500 ms the mean is 250 ms: fine beside a model call of seconds, not within a budget of a few hundred milliseconds, where log tailing fits better.

    What this means for architects

    What changes What you do
    A refund case and its refund.proposed event must not disagree Use an outbox when state and event must agree; skip it if losing an event is acceptable (a metrics ping)
    The event needs a stable identity Make the outbox row id the event id: the dedupe key and the tool call's idempotency key
    The relay can stall silently Alert on the age of the oldest unsent row; key events by aggregate id to keep their order

    Under the hood: Sagas and compensating actions

    Intuition

    A refund that touches payments, inventory and a carrier cannot be one database transaction, because different services own them. A saga replaces the single rollback with a sequence of local transactions and, for each, a compensating action that undoes it. If step 3 fails, undo step 2, then step 1.

    Mechanism

    The idea is from Hector Garcia-Molina and Kenneth Salem, "Sagas" (SIGMOD 1987; also Princeton technical report TR-070-87, January 1987). This page relies on the report's abstract: a long-lived transaction is a saga if it can be written as a sequence of transactions that can be interleaved with other transactions, and the database system guarantees either all of them complete or compensating transactions undo the partial work.

    Figure 10. Saga failure at step 3 and its compensations

    sequenceDiagram accTitle: Saga failure at step 3 with compensations accDescr: The Orchestrator holds funds at the Payments tool and reserves stock at the Inventory tool. Creating the shipment at the Carrier tool fails after retries, so the Orchestrator releases the stock and then the funds, each with an idempotency key, and publishes a saga aborted event. A failed compensation is retried until it succeeds and then escalated to a person. autonumber participant O as Orchestrator participant PAY as Payments tool participant INV as Inventory tool participant CAR as Carrier tool participant B as Event bus O->>PAY: T1 hold funds for order-42, key s1-t1 PAY-->>O: hold h1 placed O->>INV: T2 reserve stock, key s1-t2 INV-->>O: reservation v4 made O->>CAR: T3 create shipment, key s1-t3 CAR-->>O: error, retries exhausted Note over O: Decision - T3 failed, run compensations in reverse order O->>INV: C2 release reservation v4, key s1-c2 INV-->>O: released O->>PAY: C1 release hold h1, key s1-c1 PAY-->>O: released O-)B: event saga.aborted Note over O: A failed compensation is retried until it succeeds, then escalated to a person

    How to read this: steps 1 to 6 go forward, the note is the decision, and steps 7 to 10 undo in reverse order, each with its own key.

    Step through the same failure with and without compensations.

    Step 3 fails: with and without compensations (interactive when JavaScript is on)

    With compensations

    1. T1 and T2. Payments places hold h1 (key s1-t1); Inventory makes reservation v4 (key s1-t2).
    2. T3 fails. The Carrier tool errors and retries are exhausted. The Orchestrator decides to compensate.
    3. C2 then C1. Reservation v4 is released (key s1-c2), then hold h1 (key s1-c1), and saga.aborted is published.

    Without compensations

    1. T1 and T2. Payments places hold h1; Inventory makes reservation v4.
    2. T3 fails. The Carrier tool errors and retries are exhausted. There is no automatic rollback.
    3. Half-finished state. Unless something else releases them, funds stay held and stock stays reserved, with no shipment to justify them.

    The microservices.io saga page calls it "a reliably coordinated sequence of local transactions", run by choreography (services publish events that trigger the next) or orchestration (a coordinator tells participants what to execute). A developer "must design compensating transactions that explicitly undo changes".

    Worked numbers. Three steps, each succeeding independently with p = 0.98; the probability of first failing at step k is p^(k-1) x (1 - p).

    First failure at step k Probability Compensations run (k - 1)
    1 0.02 0
    2 0.0196 1
    3 0.019208 2
    Completes 0.98^3 = 0.941192 none

    Expected compensations per saga: 0 x 0.02 + 1 x 0.0196 + 2 x 0.019208 = 0.058016. About 6 in 100 sagas fail somewhere (1 - 0.941192 = 0.058808), and 0.0196 + 0.019208 = 0.038808, about 4 in 100, need at least one compensation: at volume the path runs every day.

    Check yourself: using the table, what share of sagas fail at step 3 and so need two compensations?

    0.019208, about 1.9%, or roughly 2 in 100. Each runs C2 and then C1.

    What this means for architects

    What changes What you do
    Some steps cannot be undone Order steps by reversibility, irreversible ones last (a design rule, not something the sources prescribe)
    There is no further rollback if an undo fails Make compensations idempotent, retry them to completion and escalate to a person
    With no isolation, another request can see a held amount Mark such records pending
    Choreography spreads the logic Prefer orchestration for agent flows: one Orchestrator keeps the saga state and holds the human decision as a state

    Under the hood: Dead-letter queues and ordering

    Intuition

    A poison message fails every time. Retry it forever and the line behind it stops; skip it and the work is lost, or later messages for the same entity are applied before it. A dead-letter queue is where the message goes so the line moves, with a person or tool responsible for what lands there.

    Mechanism

    Figure 11. Life of one message with retries and a dead-letter queue

    stateDiagram-v2 accTitle: Life of one message with retries and a dead-letter queue accDescr: A received message is processed. Success commits the offset. A transient failure waits with backoff and retries while attempts remain. A non-retryable failure, or exhausted attempts, sends the message to the dead-letter queue and then the offset moves on. [*] --> Received Received --> Processing Processing --> Committed: success, offset committed after Processing --> RetryWait: transient failure and attempts left RetryWait --> Processing: backoff elapsed Processing --> DeadLettered: non-retryable failure or attempts exhausted DeadLettered --> Committed: parked with error context, offset moves on Committed --> [*]

    How to read this: every path ends in Committed, so the line always moves.

    Figure 12. A poison message on one partition, with per-key quarantine

    sequenceDiagram accTitle: Poison message with per-key quarantine accDescr: A Worker receives offsets 7 and 8 with key claim-5 and offset 9 with key claim-9. Offset 7 fails and then fails again on five retries with growing waits, then is parked in the dead-letter queue. Offset 8 has the same key, so it is parked too, which keeps the order for claim-5. Offset 9 is processed normally and the Worker commits offset 10. autonumber participant B as Event bus participant W as Worker participant T as Tool server participant D as Dead-letter queue B-->>W: offsets 7 and 8 key claim-5, offset 9 key claim-9 loop Five retries, waiting 1, 2, 4, 8 and 16 seconds W->>T: process offset 7 T-->>W: error end Note over W: Decision - 31 seconds of waiting spent, park offset 7 and quarantine key claim-5 W->>D: park offset 7 with key and error context W->>D: park offset 8, same key, to keep claim-5 in order W->>T: process offset 9, key claim-9 T-->>W: ok W->>B: commit offset 10

    How to read this: the loop is the retry policy, the note is the decision, and the two parked records keep the order for claim-5.

    Dead-letter handling differs by system.

    System Ordering Dead-letter handling
    Amazon SQS standard None promised A redrive policy sets maxReceiveCount, the receives before a message moves to the dead-letter queue; keep dead-letter retention longer than the source queue's, because the enqueue timestamp is unchanged on the move
    Amazon SQS FIFO Within a message group ID One failing message blocks its group. AWS: "Don't use a dead-letter queue with a FIFO queue if you don't want to break the exact order of messages or operations"
    Kafka consumer Per partition The consumer documentation read for this page describes no dead-letter feature; the usual design is to publish the failing record, with key and error context, to a dead-letter topic, then commit
    Kafka Connect Per partition Fails fast by default (errors.tolerance=none); routes failed records to a topic when errors.deadletterqueue.topic.name is set

    Worked numbers. Retries waiting 1, 2, 4, 8 and 16 seconds stall a partition for at least 31 seconds. At 20 events per second over 48 partitions a partition receives 20 / 48 = 0.4167 per second, so about 31 x 0.4167 = 13 events queue behind the poison message. Events sharing key claim-5 would be applied ahead of a parked record unless you quarantine the key, as Figure 12 does.

    What this means for architects

    What changes What you do
    A rate limit or timeout is transient; a schema failure never succeeds Retry transient failures with backoff; park permanent ones at once
    Parking breaks order for the parked key Block or quarantine by key for a saga or ledger; park and move on for independent items
    A queue nobody watches is a store of lost work, and holds prompts and customer text Give it an owner, an alarm on depth and age, a replay tool (safe only because consumers are idempotent) and its source system's access control

    Decision framework

    Figure 13. Which mechanism does this failure need?

    flowchart TD accTitle: Choosing the mechanism for a multi-agent event flow accDescr: If the task cannot be split into independent parallel subtasks, use one agent or a fixed workflow. If the user must wait inline, use a synchronous call, otherwise put an Event bus between Orchestrator and Workers. Then commit offsets after processing with an idempotent effect, use an outbox when state and event must agree, a saga when an action spans services, and a dead-letter queue with a per-key rule when one message can block a partition. Q1{"Independent parallel subtasks?"} A1["One agent or a fixed workflow"] Q2{"Can the work wait seconds?"} A2["Synchronous call"] A3["Event bus between Orchestrator and Workers"] A4["Commit after processing, idempotent effect keyed by event id"] Q3{"State change and event must agree?"} A5["Outbox"] Q4{"Action spans services, some steps irreversible?"} A6["Saga with idempotent compensations"] Q5{"One message can block a partition?"} A7["Retry limit, dead-letter queue, per-key rule"] Q1 -->|"no"| A1 Q1 -->|"yes"| Q2 Q2 -->|"no"| A2 Q2 -->|"yes"| A3 A3 --> A4 A4 --> Q3 Q3 -->|"yes"| A5 A5 --> Q4 Q3 -->|"no"| Q4 Q4 -->|"yes"| A6 A6 --> Q5 Q4 -->|"no"| Q5 Q5 -->|"yes"| A7

    How to read this: the first two questions decide whether events are worth using, and the rest add one mechanism per remaining risk.

    If Then Because Revisit when
    The task cannot be split into independent parallel subtasks, or its parts share context One agent or a fixed workflow Shared context is a poor fit, and several agents cost about 15 times a chat's tokens The extra cost measurably buys value
    Work can wait seconds and arrives in bursts An Event bus between Orchestrator and Workers It absorbs bursts and lets each side fail independently The user must wait inline
    Delivery can repeat Commit after processing; idempotent effect keyed by event id A lost refund is worse than a repeated one A Kafka-to-Kafka stage uses transactions
    State change and event must agree One local transaction through an outbox A separate publish can lose or invent events Broker and database support an atomic write
    An action spans services with irreversible steps A saga with idempotent compensations There is no distributed rollback A step needs a human decision first
    One message can block a partition Retry limit, dead-letter queue, per-key rule Unbounded retry stalls every key Dead-letter depth stays above zero

    Comparison of the main options

    Option Ordering Replay Failure handling Main cost
    Direct synchronous calls Call order in one request None Caller's timeout and retry Failures cascade up the chain
    Queue, order not needed None promised Limited to retention Visibility timeout, retries, dead-letter queue Duplicates and out-of-order handling
    FIFO queue with message groups (SQS FIFO) Strict within a group Limited A failing message blocks its group Head-of-line blocking; a dead-letter queue can break order
    Partitioned log (Kafka) Per partition, by key Yes, within retention Consumer decides commit and parking Operations, partition planning, dead-letter code you write
    Orchestrator with a durable state record What the Orchestrator enforces From the record Saga steps and compensations You build and own the state machine

    Failure scenarios to design for

    Failure What the system does Why
    A Worker crashes mid-batch Offset committed after the batch; dedupe skips applied events; a recorded result is reused Repeats are bounded by one batch
    Slow processing triggers a rebalance A batch of 50 at 2 s each takes 100 s, inside the 300 s default max.poll.interval.ms; at 7 s each it takes 350 s and the consumer is treated as failed. Keep batch size x worst-case time well inside the interval A Worker that does not call poll in time is failed
    A poison message blocks a partition Retry limit with backoff, dead-letter queue with error context, per-key quarantine, alarm on depth Unbounded retry stalls every key
    A saga compensation fails Idempotent retries, then a human queue with the full state There is no further rollback
    A consumer returns after its offset expired Use none or earliest (not latest) for work you cannot lose; dedupe the replay The default silently skips to the end
    An orchestrator fans out too far Effort rules by task type, a cap on subagents, a token budget per job The research post reports early agents spawning 50 subagents for simple queries

    Worked example

    Size the Worker pool for the returns pipeline and see what a restart costs.

    Assumptions: illustrative figures.

    • Peak load is 20 events per second; one agent step (model call plus tool call) takes 2.0 s; each partition handles one event at a time to keep per-key order.
    • The topic has 48 partitions on 4 Worker instances (12 each); max.poll.records is 50 and the offset is committed after each batch.
    • Events spread evenly, and all Workers are down for 180 s.
    Step Calculation Result
    1. Concurrency (Little's law: in-flight work = arrival rate x time in the system) 20 x 2.0 40 in flight, so at least 40 partitions must be busy
    2. Capacity 48 / 2.0; utilisation 20 / 24 24 events per second; 83%
    3. Backlog after the outage 20 x 180; 3,600 / 48 3,600 events, 75 per partition
    4. Drain time 3,600 / (24 - 20) 900 s, 15 minutes
    5. With 40 partitions instead 40 / 2.0 20 per second, equal to arrivals: the backlog never drains
    6. Restart duplicates 4 instances x 50 At most 200 events redelivered: without dedupe 200 x 2.0 = 400 worker-seconds (400 / 48 = 8.3 s of fleet time) and 200 extra model calls; with dedupe first, lookups

    The design rule: capacity is partitions divided by step time, and 4 events per second of headroom turns a 3-minute outage into a 15-minute recovery.

    Code sample: an idempotent consumer that commits after processing

    This Java sketch uses the Kafka consumer API and a SQL database that supports ON CONFLICT DO NOTHING (PostgreSQL and SQLite do). It compiles against kafka-clients 3.9.0; the consumer is configured with enable.auto.commit=false.

    import java.nio.charset.StandardCharsets;
    import java.sql.*;
    import java.time.Duration;
    import java.util.List;
    import org.apache.kafka.clients.consumer.*;
    
    public class ClaimWorker {
        // consumer config: group.id=claim-workers, enable.auto.commit=false, String deserializers
        static void run(KafkaConsumer<String, String> consumer, Connection db) throws Exception {
            db.setAutoCommit(false);
            consumer.subscribe(List.of("claim-events"));
            while (true) {
                ConsumerRecords<String, String> batch = consumer.poll(Duration.ofSeconds(1));
                for (ConsumerRecord<String, String> r : batch) {
                    String eventId = new String(
                            r.headers().lastHeader("event-id").value(), StandardCharsets.UTF_8);
                    try (PreparedStatement seen = db.prepareStatement(
                            "INSERT INTO processed_events(event_id) VALUES (?) ON CONFLICT DO NOTHING")) {
                        seen.setString(1, eventId);
                        if (seen.executeUpdate() == 1) {   // first time this event id is seen
                            applyEffect(db, r);            // same transaction as the dedupe row
                        }
                        db.commit();                       // effect and dedupe row become durable together
                    } catch (Exception e) {
                        db.rollback();
                        throw e;                           // offset not committed: a restarted consumer gets the batch again
                    }
                }
                if (!batch.isEmpty()) consumer.commitSync(); // offsets move only after the whole batch
            }
        }
    
        static void applyEffect(Connection db, ConsumerRecord<String, String> r) throws SQLException {
            // write the triage result for r.key() using db
        }
    }

    Why it is correct: event_id must be a primary key or unique, or ON CONFLICT has nothing to conflict with. The dedupe row and the business write share one transaction, so a crash before db.commit() leaves neither (the event is applied on redelivery) and a crash after it but before commitSync() leaves both (executeUpdate() returns 0, so the effect is skipped).

    It assumes each record has an event-id header and that applyEffect calls no external system inside the transaction. It omits retry limits, the dead-letter step and rebalance handling, and must finish each batch within max.poll.interval.ms.

    Common mistakes

    • Treating "exactly-once" as a property of the whole system. Make the external effect idempotent yourself.
    • Committing the offset before the work. It loses events silently; commit after, and dedupe.
    • A new idempotency key on every retry. Derive the key from the event.
    • Publishing after the database commit as a separate step. A crash between them loses the event; use an outbox.
    • Compensations that are not idempotent. The path runs about 4 times in 100 in the worked example.
    • A dead-letter queue nobody watches. It becomes a silent store of lost work and customer data.

    Try it

    Time: 30 to 40 minutes. Pick an asynchronous flow you know or invent a small one (a ticket-routing agent that posts to a chat tool).

    1. Draw its sequence diagram with an Event bus, one Worker restart and one human approval, using Figure 4 as the template.
    2. Write down the partition key, the ordering it promises and your commit order; compute the duplicates one crash can cause for a batch size you choose.
    3. Define the event id and how long the dedupe record is kept compared with the topic's retention.
    4. Write compensations, in reverse order with idempotency keys, for two steps that can fail halfway, and say what happens to a message that fails five times.

    Done when every diagram has a figure title, an accessible title and description and a "how to read this" line, and you can point to the crash case, the duplicate case and the poison-message case in your design and name the defined behaviour for each.

    Key takeaways

    • More than one agent pays off only for valuable, parallelisable tasks; shared-context and dependent tasks are a poor fit.
    • Kafka orders events per partition: the key is your ordering promise, the partition count your parallelism ceiling.
    • Delivery is at-least-once: commit after processing and make the effect idempotent. Exactly-once stops at Kafka's edge.
    • An idempotency key comes from the event, is honoured where the effect happens and outlives the longest replay.
    • The outbox makes a state change and its event atomic; a saga replaces rollback with idempotent compensations in reverse order.
    • A dead-letter queue works only if someone owns it, and parking breaks per-key order unless the key is quarantined.

    Self-check

    1. A teammate proposes splitting a coding task across five parallel agents that all edit the same repository. What do the published criteria say?

    Shared context and many dependencies are a poor fit, and coding has fewer parallelisable tasks than research. With about 15 times a chat's tokens, value must justify the cost, so start with one agent.

    2. A Worker processes records 100 to 102 of a 5-record batch and crashes. What happens under commit-before-processing and commit-after-processing?

    Commit-before: the offset is 105, so 103 and 104 are never processed (2 lost). Commit-after: the offset is still 100, so all five are re-read; dedupe skips 100 to 102 and 103 and 104 are processed.

    3. Does Kafka's idempotent producer make a refund post exactly once?

    No. It covers the producer's own retries within a session. A consumer reprocessing after a restart, or an HTTP call to a payments system, needs an idempotency key honoured there.

    4. Why use an outbox, and what does it not give you?

    The message is stored in the same transaction as the change, so it is sent if and only if the transaction commits. It is not exactly-once: a relay that crashes between publishing and marking the row publishes again, so consumers must be idempotent.

    5. A four-step saga fails at step 3. Which compensations run, in what order, and what if one fails?

    Step 2's compensation, then step 1's, in reverse order. Each is idempotent; a failed one is retried until it succeeds, then escalated to a person with the saga's state.

    Further reading

    Last verified: 2026-10-22

    Next

    Continue to Evaluating AI systems: metrics, judges and gates, which shows how to test the agents and pipelines built here.

    Enroll to keep reading

    Lesson 7 of 8 · AI Architect (Intermediate): Design the System

    When several agents beat one, and how to run them over events safely: partitions, offsets, idempotency keys, outbox, sagas and dead-letter queues.

    In the rest of this lesson

    • Under the hood: At-least-once and effectively-once processing
    • Under the hood: Idempotency keys
    • Under the hood: The outbox pattern
    • Under the hood: Sagas and compensating actions
    • Under the hood: Dead-letter queues and ordering
    • Decision framework

    Enrolling is free. It unlocks every lesson in AI Architect (Intermediate): Design the System, tracks your progress across devices and keeps your quiz scores. The newsletter is optional.

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments