AI Hints
Home›System Design Tutorial›Logs and Guarantees
System Design · Lesson 69 of 120

Idempotent Consumers

Handling duplicates.

⏱ 2 min read▶ Video at 1:22:40🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

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.

Idempotent Consumers
From the video: Idempotent Consumers
  • 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.

dedupe.pypython
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)
Output
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.

keyvalue
Track IDsskip seen messages
Set, don't addstatus = shipped
Unique constraintsecond insert fails
Same transactionID 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
Next up: Dead-Letter Queues — where bad messages go