Sub topic 6
Writing idempotent consumers
This chapter assumes you know what a producer, broker, queue, and consumer are. It also assumes you know that a consumer acknowledges a message after processing it, and that at-least-once delivery means duplicates can happen.
Why duplicates happen
With at-least-once delivery, the broker redelivers a message if it does not receive an acknowledgement. A consumer can finish its work and then crash before sending the ack. The broker cannot tell this apart from a crash before the work. It sends the message again.
An operation is idempotent if running it several times has the same effect as running it once. An idempotent consumer makes redelivery harmless.
Two ways to get idempotency
The first is to make the operation naturally idempotent. Setting a value is safe to repeat, and incrementing it is not.
| Natural idempotent | Not idempotent |
|---|---|
| Set status to "shipped" | Add 1 to a counter |
| Upsert a row by key | Insert a row with a generated key |
| Delete a file by name | Send an email |
The second is to deduplicate. Each message carries a unique ID, and the consumer records the IDs it has handled. Before doing the work, it checks whether the ID is already recorded.
Deduplicating with a processed-IDs table
The check and the side effect must succeed or fail together. If you record the ID and then crash before applying the change, the message is lost. If you apply the change and then crash before recording the ID, a retry repeats the change. Putting both in one database transaction avoids both problems.
import sqlite3
def handle_once(db, message_id, apply):
with db:
cur = db.execute(
"INSERT OR IGNORE INTO processed (message_id) VALUES (?)",
(message_id,),
)
if cur.rowcount == 0:
return False
apply(db)
return True
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE processed (message_id TEXT PRIMARY KEY)")
print(handle_once(db, "m-1", lambda d: None))
print(handle_once(db, "m-1", lambda d: None))The with db: block opens a transaction. It commits if the block finishes and rolls back if apply raises an exception. INSERT OR IGNORE relies on the primary key: a second insert of the same ID changes no rows, so rowcount is 0. The program prints True, then False.
Common errors
- Checking and recording in separate steps. Two consumers can both see "not processed" and both do the work. Use the unique constraint as the check, as above.
- Dedupe store and side effect in different systems. A database transaction cannot cover an email send or an HTTP call. For those, pass the message ID as an idempotency key to the downstream service, if it supports one.
- Using an ID that changes on retry. The ID must be created by the producer once and kept across redeliveries. Do not use the broker's delivery tag, which is per delivery. A random ID generated inside the consumer fails for the same reason.
- Keeping IDs forever. The table grows without limit. Delete entries older than the longest time a duplicate could still arrive, including retry and dead-letter replay windows.
Exercise
A consumer reads an order-paid message, checks whether the ID is in a processed table, charges the customer's card, and then inserts the ID. The consumer crashes after the charge but before the insert. What happens on redelivery, and how would you reduce the risk?
Show answer
The ID is not in the table, so the consumer charges the card again. To reduce the risk, send the message ID to the payment provider as an idempotency key, so a repeated charge request is ignored. Where the side effect is in your own database, put the ID insert and the change in one transaction.
Exercise
Why does the code above use INSERT OR IGNORE and check rowcount, instead of running a SELECT first and then an INSERT?
Show answer
A SELECT followed by an INSERT leaves a gap where two consumers can both see no record and both proceed. The primary key makes the insert itself the atomic check, so only one consumer gets rowcount 1.