SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Service Discovery
  • API Gateway Pattern
  • Backend for Frontend (BFF)
  • Sidecar Pattern
  • Circuit Breaker
  • Bulkhead
  • Strangler Fig
  • Service Mesh
  • Database per Service
  • Timeouts and Deadlines
  • API Composition
  • Anti-Corruption Layer
  • Ambassador Pattern
  • Idempotent Consumer and Inbox Pattern
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Microservices Patterns

Idempotent Consumer and Inbox Pattern

Handle the same message twice without doing the work twice, by remembering what you already processed.

⏱ 13 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

An idempotent consumer is a message receiver that can handle the same message twice and still do the work only once. The inbox pattern is the most reliable way to build one: the consumer saves the message ID and does the work in one database transaction.

  • Most brokers promise at-least-once delivery. That means a message can arrive more than once.
  • True "exactly-once" between two separate systems cannot come from the broker alone. In practice you use at-least-once delivery + an idempotent consumer, which gives effectively-once processing.
  • The inbox is the receiving-side partner of the outbox pattern. The outbox protects the sender. The inbox protects the receiver.

02Concept: What is it?

Imagine a consumer that reads a message saying "pay $10 for order 7". It pays, and then it must ack (confirm) to the broker. If the consumer crashes, or the ack gets lost, the broker thinks the message was never handled and delivers it again. A naive consumer then pays a second time.

Repeats happen for many ordinary reasons:

  • The consumer crashed before the ack, so the broker redelivers.
  • The ack was lost on the network.
  • The work took longer than the visibility timeout, so the broker gave the message to another worker.
  • A rebalance moved the partition to a different consumer.
  • The producer retried, or the outbox relay published the same event twice.

Because repeats are normal, the receiver must make them harmless. There are two ways:

  • Natural idempotency. Some actions are safe to repeat: "set the status to SHIPPED", "save this row by its ID (upsert)", "delete order 7". Doing them twice leaves the same result.
  • Remember what you handled. Other actions are not safe: "add $10", "send an email", "add one to a counter". For these, the consumer stores each message's unique ID and skips any ID it has already handled.
Without and with an inbox
No memory
πŸ“¨m3
πŸ“¨m3 again
↓both are processed
πŸ’ΈPaid twice$20 instead of $10
With an inbox
πŸ“¨m3
πŸ“¨m3 again
↓inbox: seen m3?
πŸ“₯Inbox tableunique message ID
↓first time only
πŸ’ΈPaid once$10
The inbox turns a repeated message into a quick skip.
🧠Effectively-once
You cannot stop a message from arriving twice. You can stop it from having an effect twice. That is what "effectively-once" means.

03Real-Life Example

🍡The Cheque Desk With a Ledger
A clerk at a bank desk cashes cheques. Sometimes a customer, unsure whether the first attempt went through, hands in the same cheque again. A careless clerk pays twice. A careful clerk writes the cheque number in a ledger and pays the money at the same moment, using one pen stroke on one page, so the number and the payment can never be separated. When the same cheque comes back, the clerk finds the number in the ledger and says, "Already done". A sloppy clerk who looks in the ledger, walks away to get the cash, and only later writes the number down can still be fooled if two customers hand in the same cheque at two windows at once.
Bank desk
Idempotent consumer
A cheque
A message
The cheque number
The unique message ID
The ledger
The inbox / processed-messages table
Paying the cash
The business action (for example, adding to a balance)
Writing the number and paying in one stroke
Saving the inbox row and the change in one transaction
Handing in the same cheque twice
A redelivered message
Checking, then walking off to pay, then writing
Check-then-act without a transaction (unsafe)
One message, handled safely
πŸ“¨Receivemessage with an ID
→↓
πŸ”’BEGINstart a transaction
→↓
πŸ“₯Insert IDunique key
→↓
πŸ’ΈDo the worksame transaction
→↓
βœ…COMMIT, then ack

04Why Do We Need It?

πŸ’ΈNo double charges
A repeated message cannot pay, ship or email a second time.
πŸ”Retries become safe
You can retry and redeliver freely, because repeats do no harm.
πŸ’₯Survives crashes
The ID and the work are saved together, so a crash cannot leave only one of them.
🧩No special broker
It works with ordinary at-least-once queues and streams.
🧾Easy to audit
The inbox shows which messages were handled and when.
🀝Pairs with the outbox
The outbox may publish twice. The inbox makes the second copy harmless.
Brokers may deliver twice. Make your consumer safe to run twice, and remember the IDs you have handled in the same transaction as the work.

05Where Do We Use It?

πŸ’³Payments and balances
Adding or taking money must happen once per payment message.
πŸ”—Saga steps
Every saga step can be retried, so each step must accept repeats.
πŸ“¦Order and stock updates
Reserve stock once per order event, even if the event arrives twice.
πŸ“§Notifications
Send the welcome email once, not twice.
πŸ“ŠCounters and analytics
A page-view or like event must be counted once.
πŸ”„Data sync and CDC
Apply each change from another system once, in a read model or a search index.

06Types / Parts / How It Works

Ways to make a consumer idempotent

TechniqueHow it worksGood forWatch out
Natural idempotencyDesign the action so repeating it changes nothing: set a value, upsert by ID, delete by IDUpdates that overwrite stateNot possible for 'add 10' or 'send email'
Processed-ID checkLook up the message ID in a table, act, then record the IDSimple cases with one workerRaces and crashes between the steps (see below)
Unique constraintInsert the ID with a primary key. A duplicate insert fails or does nothingAny database with unique keysMust be in the same transaction as the work
Inbox patternInsert the ID and do the work in one transaction, then ackAnything that changes your own databaseNeeds a table and clean-up
Version checkApply a change only if its version is newer than the stored one (optimistic check)State that has a version or sequence numberNeeds a version in each message
Idempotency key to another serviceSend the message ID along with the outside call, so that service ignores repeatsPayments, email and other outside APIsThe other service must support it

Safe and unsafe, side by side

Check-then-act and the inbox
Check, then act (unsafe)
1️⃣Is the ID in the table?no
↓
2️⃣Do the work
↓crash or second copy here
3️⃣Write the ID
Inbox in one transaction (safe)
1️⃣BEGIN
↓
2️⃣Insert ID + do the workunique key stops a copy
↓
3️⃣COMMIT, then ack
Can pay twice Pays once
The only difference is whether the ID and the work are saved together.

A small inbox (illustrative SQL)

Illustrative only: exact syntax differs between databases
CREATE TABLE inbox (
  message_id   TEXT PRIMARY KEY,   -- from the producer
  processed_at TIMESTAMP NOT NULL
);

BEGIN;
  -- Fails (or inserts 0 rows) if this message was already handled
  INSERT INTO inbox (message_id, processed_at)
  VALUES ('evt-8841', now())
  ON CONFLICT (message_id) DO NOTHING;

  -- Only do the work if the insert really inserted a row
  UPDATE accounts SET balance = balance - 10 WHERE id = 7;
COMMIT;
-- then ack the broker
VisualizerSix messages, one repeat, a crash and a raceRun the naive consumer and watch m3 get paid twice. Switch to check-then-act and turn on the crash and the race. Then try the inbox with all of them on.
What kind of consumer is it?

Does the work for every delivery, then acks. It keeps no record, so it cannot tell a repeat from a new message.

What goes wrong?
Messages from the broker (↻ = delivered again). Cyan is being handled now.
m1m2m3↻ m3m4m5m6
Processed-ids table
No table: this consumer remembers nothing.
Payments made (red = a second payment for the same message)
m1 $10m2 $10m3 $10m3 $10m4 $10m5 $10m6 $10
Step log (last 10 steps)
12. Ack m3.
13. The broker delivers m4.
14. Pay $10 for m4.
15. Ack m4.
16. The broker delivers m5.
17. Pay $10 for m5.
18. Ack m5.
19. The broker delivers m6.
20. Pay $10 for m6.
21. Ack m6.
Balance
$30
right answer: $40 at the end
Duplicate payments
1
same message paid again
Payments made
7
of 6 wanted
Table rows
none
ids remembered
1 message was paid twice (m3): $10 too much, so the balance is $30 instead of $40. This consumer remembers nothing, so every repeat delivery pays again.

A simplified teaching model with no random numbers, so the same settings replay the same story. Messages m1 to m6 each pay $10 from an account that starts at $100 (made-up numbers), so the right final balance is $40. Message m3 is always delivered twice (its first ack is lost). A crash always hits m5, and the broker then delivers m5 again. The naive consumer keeps no record, so both crash choices behave the same for it.

07How to Use It / Steps / Implementation

Building an idempotent consumer

  1. 1
    Give every message a unique ID
    The producer should create it once (for example an event ID), and keep it the same on every retry. If the outbox sent the message, use the outbox row ID.
  2. 2
    Prefer natural idempotency
    If you can write the action as 'set to X' or 'upsert by ID', do that. It needs no table at all.
  3. 3
    Create an inbox table
    A column for the message ID with a primary key or unique index, and a time. The database is what enforces 'only once'.
  4. 4
    Use one transaction
    BEGIN, insert the message ID, do the database work, COMMIT. If the insert hits the unique key, skip the work. Only then ack the broker.
  5. 5
    Ack after the commit
    If you crash after the commit but before the ack, the broker redelivers, and the inbox makes the repeat a harmless skip.
  6. 6
    Handle outside calls
    An email or payment API is not part of your transaction. Send the message ID as an idempotency key to the other service, or write the next step to an outbox.
  7. 7
    Clean up the table
    Keep IDs longer than the longest time a repeat could still arrive (retries, redelivery, replays). Then delete or archive older rows.
  8. 8
    Send poison messages away
    A message that always fails should move to a dead letter queue after a few tries, not block the line.
πŸ’‘Return the same answer
For a request that expects a reply, store the result with the ID. When the repeat comes, return the saved result instead of just skipping.
⚠️Do not check, walk away, then act
Reading the table and writing the ID as two unconnected steps leaves a gap. A second copy can slip through the gap, and a crash in the gap loses the record. Put the unique insert and the work in the same transaction.

08Key Terms to Know

TermMeaning in easy words
IdempotentDoing it more than once has the same effect as doing it once
Idempotent consumerA receiver that can safely handle the same message more than once
Inbox patternSave the message ID and do the work in one transaction, to ignore repeats
Inbox tableA table of message IDs already handled, with a unique key
At-least-once deliveryEvery message arrives, but some may arrive more than once
Effectively-onceAt-least-once delivery plus idempotent handling, so the effect happens once
AckA confirmation to the broker that the message was handled
RedeliveryThe broker sending a message again because it never got an ack
Unique constraintA database rule that refuses a second row with the same key
Idempotency keyAn ID sent with a request so the receiver can spot repeats
Dedupe windowHow long you keep message IDs, so repeats within that time are caught

09Pros, Cons and Trade-offs

βœ… Pros
  • Repeated messages do no harm
  • Works with ordinary at-least-once brokers
  • The ID and the work cannot be split by a crash
  • Retries and redeliveries become safe
  • Simple tools: a table and a unique key
⚠️ Cons
  • An extra table and write on every message
  • The table needs retention and clean-up
  • Only covers changes inside your own database
  • Outside calls need their own idempotency keys
  • Messages need reliable unique IDs

Trade-offs

ChoiceWe gainWe lose
Inbox tableStrong protection against repeatsOne more write and some storage per message
Natural idempotency insteadNo table, no clean-upOnly works for overwrite-style actions
Long retention of IDsCatches very late repeatsA bigger table and slower clean-up
Short retentionA small, fast tableA very late repeat may slip through
Same database for inbox and workOne atomic transactionCouples the inbox to that database
Check-then-act without a transactionEasy to writeRaces and crash gaps can still cause duplicates

10Common Problems and Mistakes

Common mistakes

  1. Check, then act, then record. Two copies running together can both pass the check. A crash after the work loses the record.
  2. Recording the ID in a different database or transaction from the work. The two can disagree after a crash.
  3. Acking before the commit. If you crash after the ack but before the commit, the message is gone and the work was never done.
  4. IDs that change on retry. If the producer makes a new ID each time, the inbox sees every repeat as a new message.
  5. Forgetting outside side effects. A rolled-back database cannot take back an email already sent.
  6. Keeping IDs for too short a time. A repeat that arrives after the cleaning job slips through.
  7. Never cleaning the table. It grows until it slows everything down.

Things to watch

πŸ”€Order and repeats
A repeat can arrive after newer messages. Use sequence or version numbers when order matters.
☠️Poison messages
A message that always fails should go to a dead letter queue, with an alert.
πŸ“ˆInbox growth
Watch the table size and the age of the oldest row.
πŸ”‘Lock waits
Two copies of one message wait for each other on the unique key. That is correct, but watch for slow waits.

11Real-World Examples

πŸ’³Payment services
Payment APIs accept an idempotency key so a retried request does not charge twice.
🧰Framework support
Messaging libraries such as MassTransit, NServiceBus and Axon offer inbox or deduplication features.
🐘Outbox + inbox
A common design: the sender uses an outbox, the receiver uses an inbox, and together they give effectively-once.
☁️Cloud queues
Queue services often deliver at least once, so consumers keep their own record of handled IDs.
πŸ›’Order systems
Reserving stock and taking payment are guarded so a repeated event changes nothing.
πŸ“§Email and SMS
Services that send messages dedupe by a message ID to avoid sending twice.
πŸ“Note
Product features and defaults change between versions. Check the documentation of your broker and database before relying on a built-in deduplication feature.
Mini case: the crash between commit and ack
πŸ“¨Message m5
→↓handled
βœ…Committedpayment + inbox row
→↓crash before ack
πŸ“¨Broker resends m5
→↓inbox says seen
⏭️Skip and ack

12Related Topics to Read Next

Outbox Pattern→

The sending-side partner. It may publish twice, and the inbox absorbs that.

Idempotency→

The general idea, and idempotency keys for outside calls.

Delivery Semantics→

Why at-least-once is the usual promise, and what exactly-once really means.

Dead Letter Queues→

Where messages that keep failing should go.

Message Ordering→

How repeats and late messages interact with order.

SAGA Pattern→

Every saga step must tolerate repeats.

ACID Transactions→

The local transaction that makes the inbox row and the work atomic.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”Problem: brokers deliver at least once, so repeats happen.
  • βœ”Goal: effectively-once = at-least-once + idempotent consumer.
  • βœ”Easy case: make the action naturally idempotent (set, upsert, delete by ID).
  • βœ”Inbox: BEGIN, insert message ID (unique), do the work, COMMIT, then ack.
  • βœ”Trap: check, then act, then record, in separate steps. Races and crash gaps.
  • βœ”Outside calls: pass the message ID as an idempotency key, or use an outbox.
  • βœ”Clean-up: keep IDs longer than the longest possible repeat, then delete.
  • βœ”One line: β€œRemember every message you handled, in the same transaction as the work.”
← Previous
Ambassador Pattern
Next β†’
Challenges of Distribution