Course contents

11. Microservices Lesson 9 of 10

Inbox and Idempotent Consumers

Watch an at-least-once broker deliver duplicates, then make them harmless with an inbox table, a unique key and idempotency keys downstream.

15 minAdvanced9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • At-least-once brokers redeliver unacknowledged messages, so slow or crashed consumers see the same message again.
  • An inbox table keyed by message id, written in the same transaction as the work, makes the second delivery a no-op.
  • Separate transactions either lose messages or duplicate work; a unique key, not check-then-insert, settles races.
  • External calls need idempotency keys derived from the message id; prefer naturally idempotent writes.
  • Deduplicate on producer-assigned ids, keep inbox rows longer than any redelivery window, and watch the duplicate rate.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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

  1. 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.
  2. One transaction per message: BEGIN · INSERT INTO inbox (message_id, processed_at) VALUES (…) · do the work (insert the invoice, update the order) · COMMIT.
  3. Duplicate? The insert violates the primary key. Roll back, skip the handler, and acknowledge the message anyway, or the broker keeps redelivering it.
  4. 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.
  5. 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 SELECT check followed by an insert would let both through.
  6. 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 NX with 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.

The lesson as textEvery step of the simulation, written out.
  1. 1. At-least-once means some messages twice

    The Orders relay publishes 40 OrderPlaced events per second; Billing turns each into an invoice. The broker delivers a message, then waits up to 1 second for Billing’s acknowledgement. Most invoices take a couple of hundred milliseconds, but a few take longer than a second (a slow PDF render, a lock wait).

    For those, the broker assumes Billing died and delivers the message again while the first attempt is still running. Both attempts finish: the same order is invoiced twice. The simulation counts every such duplicate; with at-least-once delivery they are normal, not a bug.

    Scene: The relay publishes events to the broker and Billing consumes them. A few take longer than the one-second visibility timeout; the broker redelivers them and Billing processes those orders twice.

    Key idea: At-least-once delivery trades loss for duplicates: a slow consumer looks exactly like a dead one.

  2. 2. A crash before the ack

    Billing is fast and steady again. One second in, it crashes and restarts half a second later. Every message it was working on was never acknowledged, so after the visibility timeout the broker redelivers all of them.

    If Billing had already written the invoice (or charged a card) and crashed just before acknowledging, the redelivery does that work a second time. A longer timeout would not help here, it would only delay the redelivery. The consumer has to recognise work it has already done.

    Scene: Billing crashes for half a second. The messages it had in progress were never acknowledged, and the broker redelivers them once their visibility timeout expires.

    Key idea: Crash after the side effect, before the ack: the message comes back and the work runs again.

  3. 3. Record the message id with the work

    Every event carries a unique message id set by the producer (here the outbox row id), not by the broker. Billing keeps an inbox table, inbox(message_id PRIMARY KEY, processed_at), in its own database.

    For message #7 it runs one transaction: BEGIN · INSERT INTO inbox VALUES (7, now()) · INSERT the invoice · COMMIT, and only then acknowledges to the broker. The inbox row and the invoice exist together or not at all. *Scripted illustration.*

    Scene: Message 7 arrives at Billing, which inserts its id into the inbox table and creates the invoice in one transaction, then acknowledges the message to the broker.

    Key idea: Insert the message id into an inbox table in the same transaction as the side effect, then ack.

  4. 4. The duplicate is skipped, and acked

    Message #7 arrives again. Billing starts the same transaction, but INSERT INTO inbox hits the primary key: #7 is already there. Billing rolls back, skips the handler, and still acknowledges the message.

    The ack matters: a consumer that refuses to ack a duplicate gets it redelivered forever. With the inbox, at-least-once delivery becomes effectively-once processing: the message may arrive many times, its effect happens once. *Scripted illustration.*

    Scene: Message 7 is delivered again. Billing’s inbox insert fails on the existing id, so it rolls back, skips the work and acknowledges the message.

    Key idea: A duplicate fails the inbox insert, the work is skipped, and the message is acknowledged anyway.

  5. 5. Why it has to be the same transaction

    A tempting shortcut: mark the message as seen first, in its own transaction, then do the work. Here Billing commits inbox #8, then crashes before writing the invoice. The broker redelivers #8; the inbox says “already processed”, so Billing skips it. The invoice is never created: the shortcut turned a duplicate into a lost message.

    The reverse order (work first, inbox second) fails the other way: a crash between the two runs the work twice. Only one transaction covering both closes the gap. *Scripted illustration.*

    Scene: Billing commits the inbox entry for message 8 on its own and crashes before creating the invoice. The redelivered message 8 is found in the inbox and skipped, so the invoice is never created.

    Key idea: Inbox row and side effect must commit together; any gap either loses messages or duplicates them.

  6. 6. Two consumers, one message

    Billing now runs two instances. Message #9 is slow on Billing 1, the visibility timeout expires, and the broker hands #9 to Billing 2 while Billing 1 is still working. Both are inside their transactions at the same time.

    A check-then-act (SELECT … WHERE id = 9, then insert) would let both see “not processed”. The unique key does not: Billing 2’s insert waits on Billing 1’s uncommitted row, and once Billing 1 commits it fails with a unique violation and rolls back. Exactly one invoice, without any distributed lock. *Scripted illustration.*

    Scene: Message 9 is delivered to Billing 1 and, after the timeout, to Billing 2 as well. Both start a transaction; Billing 1 commits first, Billing 2’s inbox insert then fails on the unique key and it rolls back. Both acknowledge.

    Key idea: Let the database’s unique constraint arbitrate concurrent duplicates; never check-then-insert.

  7. 7. Side effects outside your database

    The inbox only protects what is in the same database. Billing also charges a card at a payment provider, which no local transaction can cover. So Billing passes the message id along as an idempotency key (Idempotency-Key: order-10). The first call times out: Billing cannot know whether the charge happened. It retries with the same key, and the provider returns the original result instead of charging again.

    Where you can, prefer naturally idempotent operations: SET status = "paid" can run twice, balance = balance + 10 cannot. *Scripted illustration.*

    Scene: Billing charges the payment provider with an idempotency key; the first call times out, so it retries with the same key and the provider returns the original result. Billing then records the inbox entry and invoice and acknowledges.

    Key idea: Carry the message id downstream as an idempotency key; prefer operations that are idempotent by nature.

  8. 8. Duplicates keep coming; the inbox absorbs them

    Back to full traffic, with two Billing instances and the long-tailed invoices of the first step. The broker still delivers duplicates: the inbox does not change delivery, it changes what a duplicate does. Each one now costs a failed insert and an ack instead of a second invoice.

    Keep watching the duplicate rate anyway. A rising rate means handlers are too slow for the visibility timeout or consumers are crashing, and every duplicate is wasted work. (The simulation counts duplicate deliveries; the inbox itself is not modelled.)

    Scene: The relay publishes 40 events per second to two Billing instances. Some deliveries still outlive the timeout and arrive twice; the inbox turns each duplicate into a skipped, acknowledged message.

    Key idea: Idempotency does not reduce duplicates; it makes them harmless. Monitor them as a health signal.

  9. 9. Running an inbox

    Deduplicate on a producer-assigned message id (the outbox id or an event id), never on the broker’s delivery id, which changes on redelivery. Keep inbox rows longer than the longest redelivery window (broker retention, replays, relay restarts), then delete them in batches. Put the inbox in the same database as the side effects, and pass ids downstream as idempotency keys for everything else.

    Outbox on the producer, inbox on the consumer: together they give reliable, effectively-once processing over an at-least-once broker.

    Scene: The relay publishes events to the broker; two Billing instances consume them, record each message id in the inbox table with the invoice, and call the payment provider with idempotency keys.

    Key idea: Producer-assigned ids, same-transaction inbox, retention beyond the redelivery window, idempotency keys downstream.