Sub topic 7
Writing idempotent consumers
This chapter assumes you know what a broker, a topic and a consumer are, and that you have read the previous chapter on delivery guarantees. You should be comfortable with basic SQL and database transactions.
Why consumers must tolerate duplicates
Most brokers deliver messages at least once. If a consumer processes an event but crashes before it acknowledges the message, the broker sends the event again. Network timeouts, consumer group rebalances and producer retries cause the same effect.
You cannot remove duplicates at the broker in the general case. The practical answer is to make the consumer idempotent: processing the same event twice leaves the system in the same state as processing it once. Combined with at-least-once delivery, this gives you effectively-once processing.
Naturally idempotent and non-idempotent operations
Some operations are safe to repeat. Others are not.
| Operation | Idempotent? | Why |
|---|---|---|
| Set `status = 'shipped'` for order o-1 | Yes | Repeating gives the same final value |
| Upsert a customer row by primary key | Yes | A second write replaces the first with identical data |
| Delete a row by ID | Yes | The row is already gone on the second run |
| Add 25 to a balance | No | Each run changes the balance again |
| Append a line to an audit log | No | Each run adds another line |
| Send a receipt email | No | The customer gets two emails |
Where you can, redesign the operation as a state assignment. If an event carries the new total instead of a delta, applying it twice is harmless. This is one reason event-carried state transfer, covered earlier, simplifies consumers. Many operations cannot be redesigned this way, so you need explicit deduplication.
Deduplication by event ID
Every event should carry a unique ID, as in the envelope from the schema chapter. The consumer records the IDs it has handled and skips any ID it has seen.
balances = {"acct-1": 100}
processed_ids = set()
def handle_deposit(event):
if event["event_id"] in processed_ids:
return # duplicate delivery: do nothing
balances[event["account"]] += event["amount"]
processed_ids.add(event["event_id"])
event = {"event_id": "e-42", "account": "acct-1", "amount": 25}
handle_deposit(event)
handle_deposit(event) # redelivered by the broker
print(balances["acct-1"]) # 125, not 150This works in a single process, but it has a flaw that matters in production. The balance update and the ID record are two separate steps. If the process crashes between them, one of two bad things happens, depending on the order:
- Update first, then record the ID: a crash in between leaves the deposit applied but unrecorded. The redelivery applies it again.
- Record the ID first, then update: a crash in between leaves the ID recorded but the deposit lost. The redelivery is skipped.
The fix is to store the ID and the state change in one database transaction, so both happen or neither does.
Deduplicating with a database transaction
The most reliable approach uses a unique constraint on a table of processed IDs. The insert doubles as the duplicate check, so there is no race between checking and writing.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.executescript(
"""
CREATE TABLE accounts (id TEXT PRIMARY KEY, balance INTEGER NOT NULL);
CREATE TABLE processed_events (event_id TEXT PRIMARY KEY);
INSERT INTO accounts VALUES ('acct-1', 100);
"""
)
def handle_deposit(event):
try:
with conn: # one transaction: commits on success, rolls back on error
conn.execute(
"INSERT INTO processed_events (event_id) VALUES (?)",
(event["event_id"],),
)
conn.execute(
"UPDATE accounts SET balance = balance + ? WHERE id = ?",
(event["amount"], event["account"]),
)
except sqlite3.IntegrityError:
# The event ID is already recorded: this is a duplicate.
print("duplicate, skipped:", event["event_id"])
event = {"event_id": "e-42", "account": "acct-1", "amount": 25}
handle_deposit(event)
handle_deposit(event)
row = conn.execute("SELECT balance FROM accounts WHERE id = 'acct-1'").fetchone()
print(row[0]) # 125On the second call, the INSERT violates the primary key, the transaction rolls back, and the balance is untouched. Two concurrent consumers handling the same event cannot both succeed, because the database enforces the constraint.
One caveat: IntegrityError can also come from the UPDATE, for example from a constraint on the accounts table. In production code, check for the specific constraint, or use an INSERT ... ON CONFLICT DO NOTHING and test the affected row count instead.
What the transaction cannot cover
The transaction guarantees atomicity only for changes inside that one database. Side effects outside it are not protected:
- Sending an email or calling a payment API cannot be rolled back.
- If you send the email and then crash before committing, the redelivery sends it again.
There are three common ways to handle external side effects:
- Pass an idempotency key to the other service. Many payment APIs accept a key, and they return the original result when they see it a second time. Use the event ID, or a value derived from it, as the key.
- Record the intent in your database, then perform it separately. The consumer writes a "send receipt" row in the same transaction as the state change. A separate worker sends the email and marks the row done. This is the outbox idea from a later chapter, applied on the consuming side.
- Accept the rare duplicate when the cost is low, such as a duplicate notification.
Choosing the deduplication key
The ID you deduplicate on determines what counts as "the same event".
- Broker-assigned message ID or offset. This is easy, but a producer that retries a publish may create two broker messages for one logical event, and these have different IDs.
- Producer-assigned event ID. The producer generates the ID once, when it creates the event, and keeps it across retries. This catches duplicates caused by producer retries as well as by redelivery. It is the usual choice.
- Business key. For example,
(order_id, "payment_captured"). This is useful when different events could represent the same business fact, but it requires care. Two legitimate events with the same business key would be wrongly dropped.
Handling the ID table over time
The processed_events table grows forever unless you manage it. Options:
- Expire old rows. Delete IDs older than the longest period in which a duplicate can plausibly arrive. This window must exceed the broker retention period, any retry delays, and any replay you might perform. If a duplicate arrives after its ID is deleted, it is processed again.
- Keep IDs forever if volume is low and correctness matters more than storage.
- Use sequence numbers. If events for one entity carry an increasing version, store only the highest version applied per entity and ignore anything lower or equal. This needs ordering within the entity, covered in the next chapter, and it also rejects stale events that arrive out of order.
Common errors
- Checking and writing in separate steps. A read like "is this ID known?" followed by a write has a race window when two consumers run at once. Use a unique constraint.
- Acknowledging before processing. If you acknowledge first and crash, the event is lost. This is at-most-once behavior, not a deduplication problem. Acknowledge after the transaction commits.
- Using a timestamp as the ID. Two events can share a timestamp, and a redelivered event keeps its original one. A timestamp does not identify an event.
- Generating a new ID on each retry. If the producer builds a fresh UUID every time it retries, consumers see distinct events. Generate the ID once per logical event.
- Treating a duplicate as an error. A duplicate is expected. Log it at a low level and acknowledge the message. If you raise an exception, the broker redelivers it again and again, and the message may end up in a dead-letter queue.
- Testing only the happy path. Always write a test that delivers the same event twice, and one that simulates a crash between the side effect and the acknowledgment.
A view of the flow
Exercise
A consumer handles "order.placed" events by running INSERT INTO shipments (order_id) VALUES (...) and then calls a courier API to book a pickup. The shipments table has no unique constraint on order_id, and the courier call is made before the database insert commits. Describe two ways a redelivery could cause harm, and propose a fix for each.
Show answer
First, with no unique constraint, a redelivery inserts a second shipment row for the same order. Fix: add a unique constraint on order_id, or record the event ID in the same transaction as the insert, and treat a violation as a duplicate. Second, the courier call happens before the commit. If the consumer crashes after the call but before the commit, the redelivery books a second pickup. Fix: pass the event ID (or order ID) to the courier API as an idempotency key, or write a "book pickup" intent row in the same transaction as the shipment and let a separate worker call the courier and mark the row done.
Exercise
Your processed_events table holds IDs for 7 days, but the broker retains messages for 14 days and you sometimes replay a topic from the beginning. What can go wrong, and what would you change?
Show answer
Events older than 7 days that are redelivered or replayed have had their IDs deleted, so they are processed again and may apply their changes twice. Either keep IDs at least as long as the longest retention or replay window, or switch to per-entity version numbers so that old events are rejected by comparison with the stored version, regardless of how long ago they were first seen.