The inbox: idempotent consumers and exactly-once effects
Duplicates are normal
Section titled “Duplicates are normal”The outbox can publish an event twice, and so can a broker that loses an acknowledgement or a consumer that crashes after doing its work and before telling the broker. The messaging module showed the choice: acknowledge before the work and risk losing a message, or after the work and risk repeating it. For anything that matters the second choice is the usual one, and a repeat is then something the consumer must expect.
A repeat is harmless for some effects and harmful for others. “Set the order’s status to shipped” can run twice. “Reserve 2 units” and “debit 30” cannot: run twice, they reserve 4 and debit 60. The idempotency module taught the idea; the inbox is the standard way to make any consumer safe, whatever its effect.
What exactly-once means
Section titled “What exactly-once means”Three promises are in use, and the accurate statement about the third is the most useful thing in this lesson.
- At most once: a message may be lost and is never repeated.
- At least once: a message is never lost and may be repeated.
- Exactly once: each message is processed once and only once.
Exactly-once delivery over an unreliable network is not something a broker can give by itself. The sender cannot tell a lost message from a lost acknowledgement, so it can only resend, and a resend can duplicate. What can be built is one of two things.
- At-least-once delivery plus idempotent processing. The message may arrive several times, and processing it a second time changes nothing. The effect happens once, which is why it is called effectively once.
- Exactly-once processing inside a defined boundary. Kafka’s documentation describes it for consuming from a topic and producing to another: the consumer’s position is stored in the same transaction as the output, so both are updated or neither. The same page warns that many systems claim exactly-once delivery and that you should read the fine print, because some claims do not hold when producers or consumers fail. For other destinations it says exactly-once generally requires cooperation with the destination system.
The Kafka page also names the idea behind the inbox: instead of a two-phase commit between the consumer’s position and its output, let the consumer store its position in the same place as its output. The inbox does exactly this, with the message id in place of the position.
An inbox in the consumer’s database
Section titled “An inbox in the consumer’s database”The inbox is a table in the consumer’s own database that holds the id of every message it has processed. The consumer handles a message inside one local transaction:
BEGIN;INSERT INTO inbox (message_id) VALUES ('msg-7'); -- fails if the key already existsUPDATE stock SET reserved = reserved + 2 WHERE sku = 'A1';COMMIT;-- only now acknowledge the message to the brokermessage_id is the table’s primary key, or has a unique key. If the message has been processed before, the insert fails; the consumer rolls back the transaction, skips the effect, and still acknowledges the message so that the broker stops sending it. This is how Richardson describes the idempotent consumer: the handler inserts the message’s id into a processed-messages table, and since the insert fails if the message was already handled, it can roll back and ignore the message. His key is the pair subscriber id and message id, so that two different consumers of the same message each handle it once.
In PostgreSQL an error inside a transaction aborts it, so the same thing is often written with INSERT ... ON CONFLICT DO NOTHING, which skips the row instead of failing and lets the consumer count the rows inserted: zero means a duplicate. The unique key also settles the case of two copies arriving at the same moment on two workers: only one insert can win.
Two details carry all the weight.
- The id and the effect are one transaction. If the id were saved first, in its own transaction, and the effect then failed, the id would stay behind, and the retry would look like a duplicate and be skipped. The effect would be lost for ever. If the effect came first and the id after, a crash between them would apply the effect twice.
- The id comes from the producer and is stable. It is the outbox row’s id, the same on every publication of the message. An id that the consumer draws at receipt would be different each time and would match nothing.
Try it: a redelivery
Section titled “Try it: a redelivery”The flow has three runs of the same message, “reserve 2 units”. Press play on each and watch the stock.
The inbox: a duplicate message is processed once
The consumer stores the message id in its inbox table and applies the effect in the same local transaction, then acknowledges. Nothing has gone wrong yet; this is the cost of the inbox on the normal path.
- First delivery10 msBroker to Consumer: Deliver msg-7: reserve 2 units. Arrives at 10 ms.Deliver msg-7: reserve 2 units
- 12 msConsumer to Consumer database (inbox and stock): One local transaction: INSERT inbox(msg-7), then UPDATE stock (-2), COMMIT. Arrives at 12 ms.Processing: 10 msOne local transaction: INSERT inbox(msg-7), then UPDATE stock (-2), COMMIT
- 24 msConsumer database (inbox and stock) to Consumer: Committed: msg-7 is recorded and the stock is down by 2. Arrives at 24 ms.Committed: msg-7 is recorded and the stock is down by 2
- 34 msConsumer to Broker: Acknowledge msg-7. Arrives at 34 ms.Acknowledge msg-7
Time until the consumer has handled the message: 34 ms10 ms of processing
Model notes
Assumptions
- Each message takes half the round-trip time of the link it crosses. Messages are never lost, never queue and never overlap, and each leaves when the one before it has arrived, once its receiver has finished any processing.
- Every message carries a stable id that the producer chose, the same on every delivery, such as the outbox row id. An id the consumer draws itself would be different each time and deduplicate nothing.
Simplifications
- The consumer’s crash and the broker’s redelivery timeout are shown as the restart time of the consumer. A lost acknowledgement, with no crash, leads to the same redelivery.
- The inbox table is never cleaned in this flow. A real one keeps ids for as long as a duplicate can still arrive, then deletes them, which bounds its size.
Parameter values are illustrative. They are not benchmarks of any real product.
First delivery takes 34 ms and four messages. The consumer inserts the id and updates the stock in one local transaction, 10 ms by default for Time the database takes for the local transaction, and acknowledges. The 34 ms is 24 ms of messages plus those 10 ms. The inbox adds an insert to a transaction that was happening anyway, not a round trip.
A duplicate, no inbox is the harm. The consumer commits and crashes before it acknowledges, so after Time before the broker delivers again, 5,000 ms by default, the broker delivers msg-7 again. The consumer has no record of what it processed, runs the update a second time, and the stock goes down by 4 instead of 2. It takes 5,058 ms.
A duplicate, with an inbox has the same crash and the same redelivery. This time the insert finds msg-7 already there, the unique key refuses it, the transaction is rolled back, the effect is skipped and the message is acknowledged. It also takes 5,058 ms, and the stock stays down by 2. The model prices the inbox at no extra time on the redelivery: the second copy is recognised inside the transaction that would have run anyway.
Try it in code
Section titled “Try it in code”The C# example uses a fake bus that delivers some messages twice, and a stock consumer in three modes.
// The inbox: a consumer records the id of every message it has processed, in the same transaction as the// effect, so a message delivered twice has its effect once. Recorded in a separate transaction, it can lose the effect.using ShardCraft.Playground;
// 1. Duplicates: the bus delivers every third message twice, as if its acknowledgement had been lost.foreach (var (label, mode) in new[] { ("no inbox", InboxMode.None), ("inbox, one transaction", InboxMode.SameTransaction) }){ var bus = new MessageBus(duplicateEvery: 3); for (var order = 1; order <= 5; order++) bus.Publish($"reserve 1 unit for order {order}"); var consumer = new StockConsumer(mode); var deliveries = 0; while (bus.TryReceive(out var message)) { deliveries++; consumer.Handle(message, effectFails: false); } Console.WriteLine($"{label,-24} deliveries={deliveries} reserved={consumer.Reserved} skipped={consumer.Skipped}");}
// 2. A crash while applying the effect: the first attempt fails, the bus delivers the message again.foreach (var (label, mode) in new[] { ("inbox, two transactions", InboxMode.SeparateTransaction), ("inbox, one transaction", InboxMode.SameTransaction) }){ var bus = new MessageBus(); bus.Publish("reserve 1 unit for order 1"); var consumer = new StockConsumer(mode); var deliveries = 0; while (bus.TryReceive(out var message)) { deliveries++; try { consumer.Handle(message, effectFails: message.Attempt == 1); } catch (InvalidOperationException) { bus.Nack(message); } } var verdict = consumer.Reserved == 1 ? "the retry ran, the effect happened once" : "the retry was skipped, the effect is lost"; Console.WriteLine($"{label,-24} deliveries={deliveries} reserved={consumer.Reserved} ({verdict})");}
enum InboxMode { None, SeparateTransaction, SameTransaction }
class StockConsumer(InboxMode mode){ private readonly HashSet<int> _inbox = []; // ids of processed messages: in a real database, a table with a unique key public int Reserved { get; private set; } public int Skipped { get; private set; }
public void Handle(Message message, bool effectFails) { switch (mode) { case InboxMode.None: Apply(effectFails); break;
case InboxMode.SeparateTransaction: // The id is committed first. If the effect then fails, the id stays, and the retry looks like a duplicate. if (!_inbox.Add(message.Id)) { Skipped++; return; } Apply(effectFails); break;
case InboxMode.SameTransaction: // One transaction: the id and the effect are committed together, or neither is. if (_inbox.Contains(message.Id)) { Skipped++; return; } Apply(effectFails); // throws before the commit, so the id is never recorded _inbox.Add(message.Id); break; } }
private void Apply(bool fails) { if (fails) throw new InvalidOperationException("crash while applying the effect"); Reserved++; }}no inbox deliveries=6 reserved=6 skipped=0inbox, one transaction deliveries=6 reserved=5 skipped=1inbox, two transactions deliveries=2 reserved=0 (the retry was skipped, the effect is lost)inbox, one transaction deliveries=2 reserved=1 (the retry ran, the effect happened once)This is the exact code that produced this output, run with the .NET SDK when the site was built. Nothing runs in your browser.
In the first part, the bus delivers five orders and repeats the third. With no inbox the output is deliveries=6 reserved=6 skipped=0: six deliveries, six reservations, one of them wrong. With the inbox in one transaction it is deliveries=6 reserved=5 skipped=1: five reservations, and one duplicate skipped. In the second part, the effect fails on the first attempt and the bus delivers the message again. With the id saved in a separate transaction the output is reserved=0, and the comment says it: the retry was skipped and the effect is lost. With one transaction it is reserved=1: the retry ran, and the effect happened once. The code in the page is never run in the browser: the output was produced by a CI run of the same file.
How long to keep the ids
Section titled “How long to keep the ids”An inbox cannot keep every id for ever. Take a consumer that handles 200 messages a second. That is 200 × 86,400 = 17,280,000 ids a day, and 120,960,000 after a week, each one an index entry that every insert has to check. So ids are kept for a limited time, the deduplication window of the idempotency module, and deleted afterwards. A duplicate that arrives after its id was deleted looks like a new message and is processed again.
The window is therefore sized by one question: how late can a duplicate arrive? A redelivery after a lost acknowledgement arrives in seconds. A relay that was down for an hour publishes late but not twice. A message that sat in a dead-letter queue and was replayed by an operator can arrive days later. Choose the window from the longest delay your system can produce, and add a margin. Deleting a whole day’s ids at once is cheaper if the table is partitioned by day, because dropping a partition is cheaper than deleting millions of rows, as the PostgreSQL partitioning documentation notes about bulk deletes.
Where an operation is idempotent by nature, it needs no inbox. “Set status to shipped” can be written as UPDATE orders SET status = 'shipped' WHERE id = 42 AND status = 'paid', which does nothing the second time. Prefer that to an inbox where you can, and keep the inbox for effects that add, subtract or call something outside.
An inbox does not give ordering
Section titled “An inbox does not give ordering”The inbox answers “have I seen this message?”, not “is this the newest?”. A redelivered message can arrive after later ones have been processed. Message 8, retried after message 9 has been processed because its first attempt failed, is not a duplicate for the inbox, and applying it now can put the state back. Deduplication and ordering are two separate problems.
What gives ordering is outside the inbox. Brokers order messages within a partition, not across them, so messages about the same entity should carry the same key and go to the same partition. And the message itself can carry a version number: the consumer applies it only if the version is higher than the one it holds, and ignores an older one. The outbox also helps on the producer side, since the relay publishes in the order the rows were written.
What happens if the effect is not in your database?
Section titled “What happens if the effect is not in your database?”The inbox works because the id and the effect are in one database and so in one transaction. Often the effect is a call to something else, such as a payment provider. A transaction cannot span the call, so the consumer cannot make the id and the effect atomic. The way out is to pass the dedup key on: send the message id as the idempotency key of the call, so the provider recognises the repeat. Stripe’s API reference describes this: you send an idempotency key with the request, and a retry with the same key returns the saved result of the first, whether it succeeded or failed, instead of doing the work twice. Kafka’s documentation says the same of other destination systems: exactly-once generally requires their cooperation. Where the other system offers no idempotency, you are back to choosing a loss or a repeat, and a repeat that is detected afterwards by reconciliation.
The trade-off
Section titled “The trade-off”| Step of the framework | For the inbox |
|---|---|
| Decision | Record the id of each processed message in the consumer’s database, in the same transaction as the effect. |
| Why | At-least-once delivery repeats messages, and many effects are not safe to repeat. |
| Benefits | The effect happens once even when the message arrives many times. It works with any broker that gives at-least-once. It needs no coordination with the producer except a stable id. |
| Costs | An extra table, an extra insert per message, a decision about retention, and a consumer that must own a database transaction. |
| Failure modes | An id saved in a separate transaction loses the effect. An unstable id deduplicates nothing. An id deleted too early lets a late duplicate through. |
| Scaling limits | The table grows with the message rate times the window, and each message pays a unique-key check. A hot table can become a bottleneck for a very high rate. |
| Alternative | Make the operation idempotent by nature, or pass the message id on as the idempotency key of the outside call. |
Check your understanding
Section titled “Check your understanding”Check your understanding: the inbox
This quiz needs JavaScript to check your answers.
- Exactly-once is at-least-once delivery plus idempotent processing, or exactly-once processing inside a defined boundary such as read, process and write inside Kafka. A broker alone cannot give it for an effect elsewhere.
- The inbox records the message id in a table in the consumer’s database, in the same transaction as the effect. A repeat fails the unique key, the transaction is rolled back and the message is acknowledged.
- In the flow a first delivery takes 34 ms. A redelivery after a crash takes 5,058 ms with or without an inbox, and without one the stock falls by 4 instead of 2.
- Saving the id in a separate transaction loses the effect: the C# example prints
reserved=0for two transactions andreserved=1for one. - Ids are kept for as long as a duplicate can still arrive, then deleted. At 200 messages a second that is 17,280,000 ids a day.
- The inbox does not order messages. Keys and version numbers do. When the effect is outside your database, pass the message id on as an idempotency key.
Next: the strangler fig, which replaces a system one path at a time.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.