Idempotent consumers and effectively-once processing
Where you acknowledge decides your guarantee; idempotency turns duplicates into no-ops.
15 min readWhere you acknowledge decides the guarantee
A consumer can acknowledge a message before or after processing it. Acknowledge first and crash mid-processing, and the message is gone: at-most-once. Acknowledge after, and a crash before the ack means redelivery: at-least-once. Duplicates also appear without crashes. In SQS a received message is hidden for a visibility timeout (30 seconds by default); if your handler takes 45 seconds, the message reappears and a second worker processes it while the first is still running. In Kafka, offsets committed after processing mean a rebalance can replay everything since the last commit. Assume every message will sometimes arrive twice.
Naturally idempotent operations
The cheapest fix is to design operations that are safe to repeat. Setting a value is idempotent; incrementing it is not. 'Set order 42 status to shipped' can run ten times with the same result; 'add 1 to the shipped count' cannot. Upserts keyed by a natural identifier, overwriting a thumbnail at a deterministic path, and conditional updates such as 'update only if version = 7' are all safe to repeat. Prefer messages that carry the resulting state or an absolute value over messages that carry deltas.
Deduplicate with an idempotency key
When the operation itself is not idempotent, make the consumer remember what it has done.
- The producer assigns a unique message ID when the event is created, not when it is sent, so retries of the send carry the same ID
- The consumer inserts the ID into a processed-messages table with a unique constraint in the same database transaction as its side effect; a duplicate fails the insert and is skipped
- Keep IDs longer than the longest possible redelivery window, typically days
- For external side effects, pass the key to the provider (for example Stripe's Idempotency-Key header) so it deduplicates for you
The gap you cannot fully close
If the side effect lives outside your database (sending an email through a provider with no idempotency support), there is always a window between performing it and recording that you did. A crash in that window causes a duplicate. Make the window as small as possible, record intent before acting, and decide whether a rare duplicate email is acceptable. 'Exactly once' features such as Kafka transactions cover reading from and writing to Kafka, not arbitrary side effects in other systems.
Key takeaways
- Ack after processing for at-least-once; every consumer must then tolerate duplicates
- Prefer operations that are naturally idempotent: set, upsert, conditional update
- Record processed message IDs in the same transaction as the side effect
- External side effects need the provider's idempotency support or an accepted risk
Sign in to track lessons and earn badges.