Delivery semantics: at most once, at least once, effectively once
Three promises
Section titled “Three promises”When a producer sends a message and a consumer does the work, things can fail on the way: the message can be lost, or it can arrive twice. Kafka’s documentation names the three guarantees a messaging system can give:
- At most once. Messages may be lost but are never redelivered.
- At least once. Messages are never lost but may be redelivered.
- Exactly once. Each message is processed once and only once.
The first two are cheap, and each accepts one kind of failure. The third is a promise about the result, and it is the hard one: the rest of this lesson is about what it takes to get its effect.
The moment of the acknowledgement decides
Section titled “The moment of the acknowledgement decides”The same consumer can give the first or the second guarantee, depending on when it tells the broker that it is done. Kafka’s documentation describes it with the consumer’s position, the offset: if the consumer reads a message, saves its position, and then processes the message, a crash between the two loses the message, because the new consumer starts after it. That is at most once. If it processes the message first and then saves the position, a crash between the two means that the new consumer starts from the old position and processes the message again. That is at least once.
A queue with acknowledgements has the same choice. Acknowledge on receipt, and a crash during the work loses it: at most once. Acknowledge after the work, and a crash before the acknowledgement brings the message back: at least once, the behaviour of the last lesson. A common choice for work that matters is the second, because a repeated message can be dealt with and a lost one cannot be recovered.
Mental model. The acknowledgement is the broker’s only evidence that the work is done, and it travels over a network that can lose it. After the work, the loss of the acknowledgement makes the broker send the message again. Before the work, a crash makes it never happen. You can choose a repeat or a loss, but you cannot avoid both.
Try it: lost acknowledgements
Section titled “Try it: lost acknowledgements”The lab does the work and then loses 20% of the acknowledgements. The consumers finish the message, but the queue does not hear, and the message comes back after the 5 s visibility timeout. Read Work done, whose detail line counts the different messages and the runs that were repeated, and the status sentence about the work done again.
Some acknowledgements are lost, so the queue sends a message again after its work was done: the consumer sees duplicates.
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
Waiting in the queue Dead-letter queue
| State | Messages | What it means |
|---|---|---|
| Waiting in the queue | 0 | Visible in the queue, ready to be received. |
| In flight | 17 | Received and invisible until the visibility timeout, waiting for an acknowledgement. |
| Acknowledged | 83 | Done and deleted from the queue. |
| Work repeated | 15 | Times a message already processed was processed again, because its acknowledgement was lost. |
| Dead-letter queue | 0 | Gave up after the allowed number of attempts, kept apart to be looked at. |
| Refused | 0 | Not 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.
At the start, after 10 s, the work was done 115 times for 100 different messages: 15 runs were repeated. Press Skip 30 s twice, to 70 s: 871 runs for 700 different messages, 171 of them repeated. No message was lost, and some were done two or three times.
The size of the effect follows from the rate. A message is done again whenever its acknowledgement is lost, and with a loss rate of 20% the number of runs a message needs until one acknowledgement gets through is on average 1 / (1 - 0.2), which is 1.25. For 700 messages that is about 875 runs, and the lab shows 871. The draw is random, and the limit of 3 attempts and the messages still in flight pull the figure a little below. The formula ignores the limit of 3 attempts, which matters more as the loss rate rises. The cost of at-least-once is not a rare accident: it is a steady share of the work, and it grows with the loss rate.
Effectively once
Section titled “Effectively once”Exactly-once is the name of a promise about the result. The way to get its effect with a broker that gives at-least-once is to let the message arrive more than once and make the second arrival harmless. The consumer remembers the identifiers of the messages that it has handled, or does an operation that has the same effect if it is repeated, and ignores a message that it has already handled. Delivery is at least once, and the effect is once: effectively once. This is the idea of the idempotency module. The lab does not model it: it counts the repeated runs that such a consumer would have to absorb.
The same duplicate problem appears on the producer’s side, and the transactional outbox is the standard fix. A service that saves an order and then publishes an event does two writes to two systems, and a crash between them loses the event: the order exists and nobody was told. The outbox puts the event in the same database transaction as the order, in a table of its own, and a separate relay process reads that table and publishes the events. The microservices.io description is that the service stores the messages in the database as part of the transaction that updates the business entities. The relay may crash after publishing and before it records that it published, so an event can be published twice, and the consumer must be idempotent.
The C# example shows all of it with the same fake broker. The first part is the lost event, the second the outbox, the third the relay’s crash and the consumer that remembers what it has handled.
// 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.dual write orders=1 published=0 (order 1 saved, its event is lost)outbox orders=2 outbox=2 published=0relay crash published=1 sent=0relay rerun published=4 sent=2consumer 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.
In the output, the dual write leaves 1 order and 0 published events: the order’s event is lost. The outbox saves 2 orders and 2 outbox rows, and the relay’s crash leaves 1 event published and 0 rows marked as sent. After the rerun the broker holds 4 messages, so the consumer sees 4 deliveries, and since it remembers the ids, they produce 2 effects, one for each order. The code in the page is never run in the browser: the output was produced by a CI run of the same file.
Check your understanding
Section titled “Check your understanding”Check your understanding: delivery semantics
This quiz needs JavaScript to check your answers.
What happens if the acknowledgement goes first?
Section titled “What happens if the acknowledgement goes first?”Say the worker acknowledges each message as soon as it receives it, to avoid ever seeing a duplicate. The queue now deletes the message before the work starts. If the worker crashes during the work, nobody is going to retry it, since the queue believes it is done. There is no repeat and there is a loss: at most once. For a metric where one missing point does not matter, it is a fair choice. For an order or a payment it is not, and the usual choice is to acknowledge after the work and to make the handler safe to repeat.
- Three promises: at most once (may lose), at least once (may repeat) and exactly once (each message processed once and only once).
- The moment of the acknowledgement or of the commit decides between the first two: before the work gives at most once, after the work gives at least once.
- With 20% of the acknowledgements lost, a message needs on average 1.25 runs. In the lab, 700 different messages gave 871 runs at 70 s, 171 of them repeated.
- Effectively once is at-least-once delivery plus a consumer for which a repeat changes nothing.
- The transactional outbox removes the lost event between a database write and a publish, and brings back the duplicate that the consumer must absorb: in the example 4 deliveries, 2 effects.
Next: partitioned logs and consumer groups, the other way to build a broker.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.