What it is
An idempotent consumer is a message handler that produces the same result whether a message is processed once or many times. The inbox pattern is the most common way to build one: the consumer records each message's id in an inbox table in its own database, in the same transaction as the work the message causes. A message whose id is already there is skipped and acknowledged.
Why it exists
Reliable brokers deliver at least once. They keep a message until the consumer acknowledges it, and deliver it again if no ack arrives in time. That protects against loss but guarantees duplicates sooner or later:
- A handler runs longer than the visibility timeout (or ack deadline), so the broker redelivers it while the first attempt is still working. The lesson's long-tailed invoices show this happening continuously.
- A consumer crashes after the side effect and before the ack. The message comes back and the work runs again.
- The producer republishes: an outbox relay that crashed before marking a row, or a client that retried a publish whose ack was lost.
- Consumer group rebalances and offset commits that lag behind processing in log-based brokers replay recent messages.
Broker features named "exactly once" cover only part of this path (for example, Kafka transactions cover reads and writes within Kafka). Your database writes and external calls still need the consumer to deduplicate.
How it works
- The producer assigns a stable id to every message (an outbox row id, an event UUID). It must stay the same across retries and redeliveries.
- One transaction per message:
BEGIN·INSERT INTO inbox (message_id, processed_at) VALUES (…)· do the work (insert the invoice, update the order) ·COMMIT. - Duplicate? The insert violates the primary key. Roll back, skip the handler, and acknowledge the message anyway, or the broker keeps redelivering it.
- Then acknowledge. Ack only after the commit. A crash before the commit leaves nothing behind and the redelivery does the work; a crash after the commit leaves the inbox row, and the redelivery is skipped.
- Concurrent duplicates are settled by the same unique key. If two instances handle the same message at once, the second insert waits on the first's uncommitted row and fails once it commits. A
SELECTcheck followed by an insert would let both through. - External side effects cannot join the local transaction. Pass a key derived from the message id (
Idempotency-Key: order-10) so the downstream API deduplicates; many payment APIs accept such keys. Where possible use naturally idempotent operations: setting a status is safe to repeat, incrementing a balance is not.
Some teams store the whole message in the inbox and process it asynchronously from there; the deduplication principle is the same.
When to use it
- Any consumer of an at-least-once broker whose handler has non-idempotent effects: creating records, charging, sending emails, adjusting stock or balances.
- Saga participants, which receive commands and events that may be resent after an orchestrator crash.
- HTTP APIs that clients retry: the same idea as an idempotency key table for POST requests.
When not to
- When the handler is naturally idempotent already (upserting the latest state by id, setting a value, deleting by id), a separate inbox adds cost without benefit.
- When processing is a pure function into a store that overwrites by key (a read model rebuilt from events with version checks).
- When duplicates are harmless and cheap (cache invalidations, metrics pings).
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Inbox table | Effectively-once effects over an at-least-once broker | One extra insert per message, table growth, cleanup job |
| Same transaction as the work | No loss and no double effect | The work must live in the same database as the inbox |
| Unique key arbitration | Correct under concurrency without locks | Duplicates cost a blocked insert and a rollback |
| Idempotency keys downstream | Safe retries of external calls | Downstream must support them; keys must be stable and stored |
| Longer visibility timeout | Fewer duplicates from slow handlers | Slower recovery when a consumer really crashes |
Alternatives
- Natural idempotency: design writes as upserts or state transitions with version checks (
UPDATE … WHERE version = 4). - Deduplication at the broker (e.g. SQS FIFO deduplication ids, Kafka idempotent producers): useful against producer retries within a window, not against consumer crashes or your own side effects.
- Dedup cache (Redis
SET NXwith a TTL): fast, but not transactional with your database write, so it narrows rather than closes the gap. - Event sourcing with expected versions: appending with an expected stream version rejects the duplicate append.
Failure modes
- Separate transactions: inbox first then work loses messages on a crash; work first then inbox duplicates them.
- Check-then-insert without a unique constraint lets concurrent duplicates both pass.
- Wrong dedup key: broker delivery ids, receipt handles or offsets change between deliveries, so nothing is deduplicated.
- Retention too short: rows deleted before a late redelivery or a replay arrive turn old messages into new work.
- Not acking duplicates fills the dead letter queue with messages that were already processed.
- External call outside idempotency: the inbox protects the database write but the card is charged twice.
In production
Use a primary key on message_id (plus the consumer name if several handlers share a database). Delete inbox rows in batches after a retention period longer than the broker's retention or any replay you might run. Record the outcome in the same row if handlers need to return the previous result. Expose metrics for deliveries, duplicates skipped and handler duration against the visibility timeout; a rising duplicate rate is an early warning of slow handlers or crashing consumers. Document for every event stream that delivery is at-least-once.
Common misconceptions
- "Our broker is exactly-once, so we don't need this." Broker guarantees stop at the broker; your side effects and external calls are outside them.
- "Idempotency reduces duplicates." It makes them harmless; the broker delivers just as many.
- "Check if processed, then process." Without a unique constraint and one transaction, concurrent and crash cases slip through.
- "Skip the ack for duplicates." Unacked duplicates come back forever.
Interview angle
Whenever a design consumes messages, say "at-least-once, so consumers are idempotent" and explain how: inbox table with the message id as primary key, in the same transaction as the side effect, ack after commit. Mention the concurrent-duplicate case and why a unique key beats check-then-act, how external calls use idempotency keys, and that producer-assigned ids come from the outbox. Pairing outbox and inbox shows you understand end-to-end reliability.
Model assumptions
Parts of this lesson are simulated and parts are scripted. Simulated by the queueing engine: an outbox relay publishing 40 events per second at a steady rate to a broker queue with a 1-second visibility timeout; Billing with 16 concurrent handlers averaging 200 ms, with a long tail in the duplicate steps (lognormal, coefficient of variation 2) and steady otherwise (0.3); redelivery of unacknowledged messages after the timeout, and a counted duplicate whenever two deliveries of one message both finish. In the engine a crashed handler's work is simply lost, so the crash step shows redeliveries rather than double effects. Scripted (hand-placed packets): the inbox transaction, the skipped duplicate, the separate-transaction bug, two consumers racing on one message, and the idempotency key sent to the payment provider. The engine does not model transactions, unique keys or idempotency. Numbers show behaviour and orders of magnitude, not benchmarks.