Sub topic 7
Writing idempotent consumers
This chapter assumes you know basic programming, HTTP request/response APIs, and database transactions. It also assumes you have read the chapter on delivery guarantees.
Why consumers must tolerate duplicates
Most brokers promise at-least-once delivery. If a consumer processes a message but crashes before acknowledging it, the broker sends the message again. The consumer cannot tell a first delivery from a redelivery without help.
An operation is idempotent if running it several times has the same effect as running it once. Setting a status to shipped is idempotent. Adding 25 to a balance is not. An idempotent consumer makes the second case safe, so at-least-once delivery behaves like effectively-once processing.
Technique 1: deduplicate by event ID
Every event carries a unique ID in its envelope. 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 150The second call changes nothing, so the balance is 125 and not 150.
Technique 2: make the operation naturally idempotent
Sometimes you can design the write so duplicates do no harm.
- Use an upsert keyed on a business identifier, such as "insert order
o-1or overwrite it". - Set absolute values instead of applying deltas. "Status is
shipped" survives replays. "Add 1 to the shipped count" does not. - Use a conditional update, such as "set status to
shippedonly if it is currentlypacked".
Natural idempotency needs no extra table. It works best when events carry full state, as in event-carried state transfer.
Technique 3: pass idempotency keys to downstream calls
If the consumer calls an external service, such as a payment provider, send a stable key derived from the event ID. Many APIs accept an idempotency key and return the original result for a repeated key. Without one, a retry after a timeout can charge a customer twice.
How the flow works
Acknowledge only after the commit. If the consumer crashes after the commit but before the acknowledgment, the broker redelivers, and the stored ID makes the retry harmless.
Common errors
- Check and write in separate steps. Two copies of the same event handled in parallel can both pass the check. Use a unique constraint on the event ID so the database rejects the second one.
- Using a new ID per retry. If a producer generates a fresh ID each time it resends, consumers cannot recognize duplicates. The ID must be created once, when the event is created.
- Storing IDs forever. The table grows without limit. Keep IDs for longer than the broker's maximum redelivery window, then expire them.
- Acknowledging before processing. This turns at-least-once into at-most-once, so a crash loses the event.
Exercise
A consumer reads "payment_captured" events and runs UPDATE accounts SET balance = balance + :amount. It stores processed event IDs in a separate database from the balance, in a separate step. Name two problems with this design and one fix.
Show answer
First, a crash between the balance update and the ID write causes the event to be applied again on redelivery. A crash in the opposite order loses the update. Second, two parallel copies of the event can both pass the "already seen?" check. The fix is to store the event ID and the balance change in the same database transaction, with a unique constraint on the event ID.