Idempotent Consumers
Handling duplicates.
With at least once delivery, the same message can arrive twice. If the consumer charges a card or adds loyalty points each time, the customer gets a nasty surprise. The consumer must be idempotent.

- Messages can repeat
- Double charges?
- Make consumers idempotent
Remembering message IDs
Every message gets a unique ID. The consumer records the IDs it has processed, and skips any it has seen before. Here, message two is delivered twice. Run it. The duplicate is noticed and skipped, so the points are only added once.
messages = [
{"id": "m1", "user": "sam", "points": 10},
{"id": "m2", "user": "sam", "points": 5},
{"id": "m2", "user": "sam", "points": 5}, # delivered again
]
seen, points = set(), {"sam": 0}
for msg in messages:
if msg["id"] in seen:
print("skip duplicate", msg["id"])
continue
points[msg["user"]] += msg["points"]
seen.add(msg["id"])
print("points:", points)skip duplicate m2
points: {'sam': 15}Other ways to be idempotent
There are other ways too. Use set operations instead of adds. Setting status to shipped twice is harmless. Use a database unique constraint, so a second insert of the same order fails. And save the seen ID in the same transaction as the work, so a crash can't leave them out of step.
| key | value |
|---|---|
| Track IDs | skip seen messages |
| Set, don't add | status = shipped |
| Unique constraint | second insert fails |
| Same transaction | ID and work together |
Summary
Idempotent consumers make duplicate messages harmless, usually by tracking message IDs. With at least once delivery, that's essential. Next, what to do with messages that keep failing.
Key takeaways- Unique message IDs
- Skip what you've seen
- Set instead of add