How-To Guide

How to Design Idempotent Consumers

Make a message consumer idempotent: dedupe on the event id, apply the effect and the id in one transaction, and handle the out-of-order delivery.

On this page

  1. Introduction
  2. Dedupe on a unique event id
  3. Apply the effect and the id in one transaction
  4. Handle the out-of-order delivery
  5. Make the side effects idempotent too
  6. Test the redelivery, the reorder, and the crash
  7. Common pitfalls
  8. Conclusion

Introduction

A message broker delivers at least once: a consumer that processes a message and crashes before acknowledging it receives the message again. If the consumer applies the effect twice, the data is wrong: a double charge, a double increment, a duplicate record. An idempotent consumer makes a redelivery a no-op, so the at-least-once delivery becomes effectively once for the data, which is the reliability a distributed system can actually provide.

This tutorial designs an idempotent consumer: dedupe on the event id, apply the effect and the id in one transaction, handle the out-of-order delivery, and test the redelivery and the reorder. The examples use a relational store for the dedupe, and the design applies to any consumer.

Dedupe on a unique event id

Each event carries a unique id assigned by the producer. The consumer records the ids it has processed and skips a message whose id it has seen. This is the core of idempotency: the second delivery of the same event is recognized and ignored, so the effect is applied once even though the message was delivered twice.

The id must be unique per event and stable across redeliveries, which the producer guarantees by generating it once. A consumer that derives the id from the content instead of reading it can collide two different events with the same content, or fail to match a redelivery whose metadata changed. Read the id the producer assigned, and do not recompute it.

async function consume(event) {
  const seen = await store.get('processed:' + event.id);
  if (seen) return;                       // a redelivery: skip it
  await applyEffect(event);               // apply the effect
  await store.set('processed:' + event.id, '1');   // record the id
}
// but the effect and the record are two writes: a crash between them is unsafe

Apply the effect and the id in one transaction

The dedupe record and the effect must commit together, or a crash between them leaves a wrong state: the effect applied but the id not recorded, so a redelivery double-applies; or the id recorded but the effect not applied, so the effect is lost. Both go in one transaction, so either both are in the store or neither, and a crash leaves a consistent state the redelivery handles correctly.

Write the processed id with an insert that fails on a duplicate, so a concurrent redelivery of the same event cannot both pass the check. The insert’s unique constraint is the guard: the first event inserts the id and applies the effect, and the second event’s insert fails and it skips. This makes the dedupe safe even under concurrency, not only under a sequential redelivery.

BEGIN;
-- the unique constraint on event_id makes a concurrent duplicate fail here
INSERT INTO processed_events (event_id) VALUES ($1);
UPDATE accounts SET balance = balance + $2 WHERE id = $3;
COMMIT;
-- on a unique violation, roll back and skip: the event was already processed

Handle the out-of-order delivery

A broker may deliver the events for one entity out of order, especially across partitions. The consumer should compare the event’s version or timestamp to the one it has applied and ignore an older event, so a late old event does not overwrite a newer state. Store the last applied version per entity, and skip an event whose version is not greater.

Ordering is per entity, so the version is per entity, not global. The consumer stores the last applied version for each entity it touches, and an event older than that is a stale delivery to ignore. This pairs with the dedupe: the dedupe handles the exact duplicate, and the version check handles the older event, so both the redelivery and the reorder are safe.

BEGIN;
-- skip an event older than the last applied version for this entity
UPDATE entity_state SET version = $2, data = $3
WHERE entity_id = $1 AND version < $2;   -- zero rows affected -> stale event, ignore
COMMIT;

Make the side effects idempotent too

The consumer’s effect may be a call to an external service, such as charging a payment or sending an email, which is not a database write and cannot be in the dedupe transaction. For those, pass an idempotency key to the external service, so it deduplicates the call itself, and record the result so a retry reuses it. The external service’s idempotency is the counterpart of the consumer’s dedupe.

For an email or a notification, an idempotency key or a check on whether the message was already sent prevents a duplicate. For a payment, the provider usually accepts an idempotency key and returns the same result for a repeat. Record the outcome with the event id, so a retry of the consumer reuses the recorded outcome rather than calling the external service again.

Test the redelivery, the reorder, and the crash

Test that the same event delivered twice applies the effect once, by delivering it twice and asserting one effect. Test that an older event delivered after a newer one is ignored, by delivering a newer then an older and asserting the state is the newer. Test that a crash between the effect and the id record does not double-apply, by simulating the crash and redelivering. Test the concurrent duplicate, by delivering two at once and asserting one effect.

# deliver the same event twice: one effect
node scripts/deliver.mjs order-placed evt-1
node scripts/deliver.mjs order-placed evt-1
node scripts/assert-balance.mjs --expected 1-effect
# deliver an older event after a newer: assert it is ignored

Common pitfalls

No dedupe so a redelivery double-applies, the dedupe record and the effect in separate transactions so a crash leaves a wrong state, deriving the id from the content instead of reading it, no version check so an out-of-order old event overwrites a newer state, and a non-idempotent external call without an idempotency key are the recurring mistakes. An event id from the producer, one transaction for the id and the effect, a unique-constraint insert, a version check per entity, and idempotency keys for the externals address them.

Conclusion

An idempotent consumer makes at-least-once delivery safe. Dedupe on the producer-assigned event id, apply the effect and the id in one transaction with a unique constraint, ignore an older event with a version check, and use idempotency keys for the external side effects. Self-check by delivering an event twice and asserting one effect, and by delivering an older event after a newer and asserting it is ignored. Then a redelivery or a reorder does not corrupt the data.

Sources: Chris Richardson: Idempotent consumer, Kafka: Delivery semantics, AWS: Exactly-once processing.

FAQ

Why not exactly-once delivery?
Exactly-once delivery is not achievable in a distributed system without a transaction that spans the broker and the consumer, which the broker does not offer. At-least-once delivery with an idempotent consumer gives the same result for the data and is achievable.
Where do I store the processed ids?
In the same store as the effect, so the effect and the id commit together. A separate store means two transactions, and a crash between them either loses the effect or leaves it deduped without the effect.

Related Examples