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).
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
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.
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.
"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
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.
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
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 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
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.
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).
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
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.
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
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.
Comparison of the main options
Failure scenarios to design for
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.
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 {
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) {
applyEffect(db, r);
}
db.commit();
} catch (Exception e) {
db.rollback();
throw e;
}
}
if (!batch.isEmpty()) consumer.commitSync();
}
}
static void applyEffect(Connection db, ConsumerRecord<String, String> r) throws SQLException {
}
}
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).
- Draw its sequence diagram with an Event bus, one Worker restart and one human approval, using Figure 4 as the template.
- 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.
- Define the event id and how long the dedupe record is kept compared with the topic's retention.
- 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.