Sub topic 6
Writing idempotent consumers
This chapter assumes you know what producers, brokers, queues, and consumers are. It also assumes you know how acknowledgements work and why at-least-once delivery can deliver a message more than once. You should be comfortable reading Python and basic SQL.
Why duplicates happen
With at-least-once delivery, the broker redelivers a message whenever it is not sure the consumer finished it. A consumer can do all its work and still be unable to tell the broker. The usual causes are:
- The consumer crashes after the side effect but before the acknowledgement.
- The network drops the acknowledgement on its way to the broker.
- The acknowledgement timeout expires because processing ran long, so the broker hands the message to another consumer.
- The producer retried a publish whose confirmation was lost, so the broker holds two copies.
You cannot remove these windows by being careful. Between "the work is done" and "the broker knows it is done" there is always a gap. The practical answer is to make the work safe to repeat.
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 10 to a balance is not. A consumer is idempotent when handling the same message twice leaves the system in the same state as handling it once.
Naturally idempotent operations
Before adding machinery, check whether the operation can be made idempotent by its shape.
| Operation | Idempotent? | Safer form |
|---|---|---|
| `UPDATE orders SET status = 'shipped' WHERE id = 7` | Yes | Keep as is |
| `UPDATE accounts SET balance = balance + 10` | No | Store the transfer as a row with a unique ID and compute the balance from rows |
| `INSERT INTO payments (...)` | No | Add a unique key and use an upsert |
| Send an email | No | Record "sent for message X" before or with sending, and accept some risk (see below) |
| Delete a file by name | Yes | A second delete should treat "not found" as success |
Messages that carry the new state ("order 7 is now shipped") are easier to handle than messages that carry a change ("add 10"). When you design the message format, prefer state or include enough information to detect a repeat.
The deduplication key
When the operation is not naturally idempotent, the consumer needs a way to recognize a message it has already handled. That requires a stable identifier.
- Use an ID the producer assigns, such as a UUID generated when the event is created. The ID must be the same on every redelivery and on every producer retry.
- A broker-assigned delivery tag is not suitable. In RabbitMQ it is scoped to a channel and changes between deliveries, so it identifies the delivery, not the message.
- A business key can work when it is naturally unique, such as
order_idplusevent_type.
If the producer generates a new random ID each time it retries a publish, producer-side duplicates will look like different messages. Generate the ID once, before the first publish attempt, and store or derive it deterministically.
Record the ID in the same transaction as the side effect
The standard technique is a table of processed message IDs. The check and the effect must commit together. If they are separate, a crash between them reopens the gap you were trying to close.
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 and commits at the end, or rolls back if an exception escapes. The insert into processed and the apply call are therefore atomic. The primary key makes the insert a claim: only one transaction can insert a given ID. The first call prints True and the second prints False.
Two details matter:
- If
applyraises, the transaction rolls back, including theprocessedrow. A later redelivery will try again, which is what you want. - If two consumers receive the same message at the same time, the database serializes the inserts on the primary key. One succeeds and the other either sees
rowcount == 0or waits for the first to commit. This depends on a real database with unique constraints, not a cache check done in application code.
The return value tells the caller what to do. In both cases the consumer should acknowledge the message. A duplicate is not a failure.
def handle(ch, method, properties, body):
message_id = properties.message_id
handle_once(db, message_id, lambda d: apply_order(d, body))
ch.basic_ack(delivery_tag=method.delivery_tag)Here properties.message_id is a standard AMQP property the producer must set when publishing. Reading it from the message, not from the broker's delivery metadata, keeps it stable across redeliveries.
When the side effect is outside your database
The transaction trick only works when the effect and the ID record live in the same transactional store. Calls to an email service, a payment gateway, or another HTTP API cannot join your database transaction. You have three options, in order of preference.
- Pass the key downstream. Many APIs accept an idempotency key and return the earlier result for a repeated key. Use the message ID as that key. The external service then does the deduplication.
- Make the call safe to repeat. For example, "set the user's email preference to X" is idempotent even without a key.
- Choose which failure you accept. If neither option exists, you decide between a possible duplicate and a possible loss. Record the ID first and then call out, and a crash in between loses the effect (at most once). Call out first and then record the ID, and a crash in between repeats the effect (at least once). Pick based on which error is cheaper. A duplicate reminder email is usually tolerable. A duplicate charge is not.
Common errors
Checking, then acting, in two steps. Code that runs SELECT to see if the ID exists and then does the work has a race. Two consumers can both see "not found". Use a unique constraint and let the database decide.
Acknowledging before committing. If you acknowledge first and the commit fails, the message is gone and the work never happened. Acknowledge after the commit. The processed-ID table then protects you from the duplicate that this ordering can create.
Unbounded growth of the table. Every message adds a row. Add a timestamp column and delete rows older than the longest period in which a duplicate can plausibly arrive. That period is at least the broker's retention or the dead-letter replay window, whichever is longer. Deleting too early lets an old duplicate through, so keep a generous margin.
Treating a duplicate as an error. Raising or rejecting on a duplicate sends the message into the retry and dead-letter path for no reason. Return success and acknowledge.
Reusing one ID for different content. If a producer reuses an ID for a changed message, the consumer silently drops the update. Generate a new ID for each distinct event. If the same logical entity changes often, include a version number and ignore only versions at or below the one you have already applied.
Dedup state in memory. A Python set of seen IDs vanishes on restart and is not shared between consumer instances. It reduces duplicates but does not give you a guarantee.
Idempotency and ordering
Idempotency does not fix out-of-order delivery. Suppose status=shipped arrives, then a redelivered older status=packed arrives. The consumer has not seen the packed ID before, so it applies it and moves the order backwards. A version or sequence number stored with the entity, and a check such as UPDATE ... WHERE version < ?, handles this case. Deduplication answers "have I seen this message?" Versioning answers "is this message still relevant?" Many systems need both.
What idempotency does not give you
An idempotent consumer on at-least-once delivery produces an effect that behaves as if it happened exactly once. The message is still delivered more than once, and the consumer still does some wasted work on each duplicate. This is why the pattern is often described as effectively-once processing. It costs one extra write and one lookup per message, and it needs the ID retention described above.
Exercise
A consumer reads an order message, calls a payment gateway that does not support idempotency keys, and then inserts the payment ID into its own database. The consumer crashes after the gateway call but before the insert. What happens on redelivery, and how would you change the design so a repeat cannot charge the customer twice?
Show answer
On redelivery the consumer calls the gateway again and the customer is charged twice, because nothing records that the first call happened. The fix is to store the order's message ID, or a payment attempt row keyed by it, before calling the gateway, with a status such as "pending". On redelivery the consumer sees the pending attempt and queries the gateway for the outcome, or asks for manual review, instead of charging again. If the gateway can be given a client-supplied reference, send the message ID as that reference so the gateway rejects the repeat.
Exercise
Why is SELECT followed by INSERT a weaker deduplication check than a single INSERT with a primary key on the message ID?
Show answer
Two consumers can run the SELECT at the same time, both find nothing, and both proceed to apply the effect. A primary key constraint makes the database allow only one insert for a given ID, so exactly one consumer wins even when they run concurrently.