Skip to content

Duplicate messages

The same problem, in the middle of the system

Section titled “The same problem, in the middle of the system”

A request has a client and a server. A message has a producer, a queue and a consumer, and the doubt moves to the point where the consumer says it is done. A consumer takes a message and does the work, and then it must tell the queue, so that the queue deletes the message. If that acknowledgement is lost, or the consumer crashes just before sending it, the queue cannot tell whether the work was done. It does the only safe thing and delivers the message again.

Amazon’s SQS documentation says this for its standard queues: copies of a message are stored on several servers, and on rare occasions a server that holds one may be unavailable when you receive or delete a message. The copy is then not deleted and you might get it again. Its advice is to design your applications to be idempotent, so that they are not affected adversely when processing the same message more than once.

That is the bargain of at-least-once delivery. The queue keeps a message until it is acknowledged, and in exchange the consumer may see one more than once. Delivering at most once would instead lose a message when a consumer crashes before it finishes.

Mental model. A post office will not take a parcel off its books until you sign for it. If your signature is lost on the way back, it delivers the parcel again. The post office is not careless: it is the only way never to lose a parcel.

The lab starts with 10 messages per second arriving, four consumers that can take 5 each per second, and a share of the acknowledgements lost. Raise Lost acknowledgements and watch the work done.

Some acknowledgements are lost, so the queue sends a message again after its work was done: the consumer sees duplicates.

Traffic
10 per second

With backpressure on, the queue holds at most 100 messages and producers are slowed to what it accepts. Without it, the queue just grows.

Consumers
Consumers
4
5 per second
Failures and delivery
0%
0%
20%
5 s
3

Share of receives where the consumer crashes before it finishes. The message comes back after the visibility timeout, and a retry may succeed.

Share of messages that fail every time they are tried. Only the dead-letter queue gets rid of them.

Share of finished messages whose acknowledgement never reaches the queue: the work was done, and the message comes back anyway.

Time controls
Time: 10 s

One second of model time passes each half second while the lab runs. Step and Skip move time on by hand.

What is happening

Producers send 10 a second and the consumers can take 20, so the queue does not grow.

Work done again after a lost acknowledgement: 15. With at-least-once delivery a consumer must cope with seeing a message twice.

Waiting in the queue
017 in flight, invisible until their timeout
Work done
115100 different messages, 15 runs repeated
Dead-letter queue
0gave up after 3 attempts
Accepted from producers
100backpressure is off, nothing is refused
The queue: one square per message, waiting first, then in flight.
Messages waiting over time
035110 seconds

Waiting in the queue Dead-letter queue

Where every message is, after 10 s
StateMessagesWhat it means
Waiting in the queue0Visible in the queue, ready to be received.
In flight17Received and invisible until the visibility timeout, waiting for an acknowledgement.
Acknowledged83Done and deleted from the queue.
Work repeated15Times a message already processed was processed again, because its acknowledgement was lost.
Dead-letter queue0Gave up after the allowed number of attempts, kept apart to be looked at.
Refused0Not accepted because the queue was full, with backpressure on. The producer is slowed down.

Illustrative values, not benchmarks of any real product.

Model notes

Assumptions

  • The lab advances one second at a time. A consumer receives up to its rate each second and finishes each message in the same second; processing time, the network and the broker itself are not modelled.
  • A message is hidden for the visibility timeout after each receive. A crash or a lost acknowledgement makes it reappear, and after the allowed number of attempts it moves to the dead-letter queue. A random draw, seeded so the same settings give the same run, decides each outcome.

Simplifications

  • The work queue does not track the order of messages: retries are received first, which stands for the oldest. Order is shown in the stream, where a partition keeps its messages in the order they were appended.
  • Exactly-once processing, transactions, replicated brokers, retention, message size and a consumer that is slow rather than dead are not modelled. The numbers are floors and illustrations, not measurements of a product.

Parameter values are illustrative. They are not benchmarks of any real product.

The lab opens after 10 seconds of running. By then 100 messages have arrived and the consumers have done work 115 times: 15 runs are repeats of work that was already done. Each of those 15 messages was done, its acknowledgement was lost, the visibility timeout ran out, and the queue delivered it again. Nothing is wrong with the queue, and every message was handled at least once. A consumer that charges a card for each message it sees has charged 15 customers twice.

The other half: publishing the event at all

Section titled “The other half: publishing the event at all”

Duplicates are one failure. Loss is the other, and it starts earlier. An order service saves an order and then publishes an event, “order created”. Those are two systems, and no transaction covers both. If the service crashes between them, the order exists and the event never does. That is a dual write.

The transactional outbox removes the gap. The service saves the order and the event in the same database transaction, the event going into an outbox table. A separate relay reads unsent rows and publishes them, then marks them sent. A crash can delay an event, but it cannot lose one.

C# exampleA dual write loses an event, an outbox does not
transactional-outbox.cs
// The transactional outbox: write the business row and the event in the same transaction,
// then let a relay publish the events. A crash can delay an event, but it cannot lose one.
using ShardCraft.Playground;
// 1. Dual write: save the order, then publish. A crash between the two loses the event.
var db = new OrderDb();
var bus = new MessageBus();
try
{
db.SaveOrder(1);
throw new InvalidOperationException("crash before publish");
}
catch (InvalidOperationException) { }
Console.WriteLine($"dual write orders={db.Orders.Count} published={bus.Pending} (order 1 saved, its event is lost)");
// 2. Outbox: the order and its event are saved atomically.
db = new OrderDb();
bus = new MessageBus(duplicateEvery: 2);
db.SaveOrderWithEvent(1);
db.SaveOrderWithEvent(2);
Console.WriteLine($"outbox orders={db.Orders.Count} outbox={db.Outbox.Count} published={bus.Pending}");
// The relay publishes unsent rows. It crashes after publishing event 1 but before marking it sent,
// so event 1 is published again on the next run: at-least-once.
var first = db.Outbox.First(o => !o.Sent);
bus.Publish(first.Body);
Console.WriteLine($"relay crash published={bus.Pending} sent={db.Outbox.Count(o => o.Sent)}");
foreach (var row in db.Outbox.Where(o => !o.Sent).ToList())
{
bus.Publish(row.Body);
row.Sent = true;
}
Console.WriteLine($"relay rerun published={bus.Pending} sent={db.Outbox.Count(o => o.Sent)}");
// The consumer sees duplicates, so it remembers the ids it has handled.
var handled = new HashSet<string>();
var effects = 0;
var deliveries = 0;
while (bus.TryReceive(out var m))
{
deliveries++;
if (handled.Add(m.Body)) effects++;
}
Console.WriteLine($"consumer deliveries={deliveries} effects={effects} (every order handled once)");
class OutboxRow(string body) { public string Body { get; } = body; public bool Sent { get; set; } }
class OrderDb
{
public List<int> Orders { get; } = [];
public List<OutboxRow> Outbox { get; } = [];
public void SaveOrder(int id) => Orders.Add(id);
// Both writes belong to one transaction: here, one method that cannot stop halfway.
public void SaveOrderWithEvent(int id)
{
Orders.Add(id);
Outbox.Add(new OutboxRow($"order-created:{id}"));
}
}
// In a real database the two inserts share one BEGIN/COMMIT, and the relay polls the outbox table or reads the log.
Output
dual write orders=1 published=0 (order 1 saved, its event is lost)
outbox orders=2 outbox=2 published=0
relay crash published=1 sent=0
relay rerun published=4 sent=2
consumer deliveries=4 effects=2 (every order handled 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.

The example shows both. With the dual write, order 1 is saved and the crash comes before the publish: 1 order, 0 events published. With the outbox, 2 orders are saved with 2 outbox rows. Then the relay crashes after publishing the event for order 1 but before marking it sent, so it publishes that event again on its next run. The consumer receives 4 deliveries for 2 orders, and by remembering the ids it has handled, it does the work 2 times, once per order.

So the outbox solves loss by accepting duplicates. It is at-least-once delivery from the first step to the last, and each step that can be retried adds a place where a duplicate can appear.

What happens if the consumer does not expect duplicates?

Section titled “What happens if the consumer does not expect duplicates?”

Whatever the consumer does with a message happens as often as the message arrives. If it adds to a balance, sends an email or charges a card, it does so each time. The queue cannot help, because from its side the duplicate is a message that was never acknowledged. The fix is in the consumer, which the next lesson covers.

  • A queue that cannot tell whether the work was done delivers the message again, which is at-least-once delivery.
  • In the lab, 100 messages arrive in the first 10 seconds and the work is done 115 times, so 15 runs are repeats.
  • Saving the order and the event in one transaction, with a relay that publishes the outbox, stops events from being lost.
  • The relay can crash after publishing, so the outbox can deliver an event twice: in the example, 4 deliveries for 2 orders.
  • The consumer has to be able to see a message twice.

Next: Deduplication windows and idempotent consumers.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.