Sub topic 6
Delivery guarantees: at-most-once, at-least-once, effectively-once
This chapter assumes you know what a broker, a producer and a consumer are, and the difference between a topic and a queue. It also assumes you understand database transactions. By the end you should be able to say what each delivery guarantee promises, what it costs, and which one to build on.
Why delivery is a problem at all
A producer sends an event over a network to a broker. The broker sends it over a network to a consumer. Any step can fail, and the sender often cannot tell which step failed.
Consider a consumer that reads an event, updates its database, and then crashes before telling the broker it is done. The broker has no way to know whether the update happened. It must choose between two actions:
- Treat the event as delivered and never send it again. If the update did not happen, the event is lost.
- Treat the event as not delivered and send it again. If the update did happen, the event is processed twice.
No setting removes this choice. A delivery guarantee is the broker's policy for making it.
The three guarantees
| Guarantee | Events can be lost? | Events can be duplicated? | Typical mechanism |
|---|---|---|---|
| At-most-once | Yes | No | Acknowledge before processing, or never retry |
| At-least-once | No | Yes | Acknowledge after processing, retry on failure |
| Effectively-once | No | Duplicates arrive but have no extra effect | At-least-once delivery plus idempotent or transactional processing |
At-most-once
The broker hands over the event and forgets it. If the consumer is down, slow or crashes mid-way, the event is gone.
This is fast and simple. It suits data where a missed item is cheap and a duplicate is harmful or pointless, such as a live position ping from a vehicle that sends a new one every second.
At-least-once
The broker keeps the event until the consumer acknowledges it. An acknowledgement (ack) is a message from the consumer saying "I have finished with this event." If no ack arrives within a timeout, the broker redelivers.
Nothing is lost, but duplicates happen. They come from several sources:
- The consumer processed the event and crashed before sending the ack.
- The ack was sent but lost on the network.
- The processing took longer than the broker's visibility or ack timeout, so the broker redelivered while the first attempt was still running.
- The producer retried a publish after a timeout, and the first attempt had actually succeeded.
- A consumer group rebalanced, and a different consumer received events the previous one had already handled.
Most production brokers default to this mode, because losing business events is usually worse than seeing them twice.
Effectively-once
True exactly-once delivery over an unreliable network is not achievable in the general case. What systems offer is effectively-once processing: the event may be delivered more than once, but its effect on state happens once.
You get it in two ways:
- Idempotent processing. The consumer detects duplicates and ignores them. The next chapter covers this in detail.
- Atomic read-process-write. The consumer's input position and its output are committed together in one transaction. Some broker platforms offer this within their own boundary, for example consuming from one topic and writing to another topic. It does not extend to arbitrary external side effects such as sending an email or calling a payment API.
Be careful with the label "exactly-once" in product documentation. It is usually true only inside a defined boundary. Read the boundary before you rely on it.
Where the acknowledgement goes
The order of "process" and "ack" decides which guarantee you get. This is the most common source of mistakes.
If you ack first and crash, the work never happens and the broker believes it did. If you process first and crash, the work happened and the broker will send the event again.
Duplicates the broker cannot see
Broker-level guarantees cover only the hop between broker and consumer. Two other places produce duplicates.
Producer retries. When a publish times out, the producer does not know whether the broker stored the event. Retrying is the safe choice for avoiding loss, but it can store the event twice. Some brokers support idempotent producers, where the broker discards a repeated send using a producer ID and a sequence number. Others leave deduplication to you.
Side effects outside the broker. An HTTP call to a payment provider, an email, or a write to another system is not covered by any broker transaction. If your consumer sends a receipt and then crashes before the ack, the redelivery sends a second receipt.
A worked example
This consumer follows at-least-once rules. It processes first and acks last. The Broker class is a small simulation so the code runs on its own. It redelivers any event that was not acknowledged.
class Broker:
def __init__(self, events):
self.pending = list(events)
def deliver(self):
# Always hands out the oldest unacknowledged event.
return self.pending[0] if self.pending else None
def ack(self, event_id):
self.pending = [e for e in self.pending if e["event_id"] != event_id]
balances = {"acct-1": 100}
processed_ids = set()
crash_once = {"armed": True}
def handle(event):
if event["event_id"] in processed_ids:
return # duplicate: skip the effect
balances[event["account"]] += event["amount"]
processed_ids.add(event["event_id"])
broker = Broker([{"event_id": "e-1", "account": "acct-1", "amount": 25}])
while (event := broker.deliver()) is not None:
handle(event)
if crash_once["armed"]:
crash_once["armed"] = False
print("crash before ack, event will be redelivered")
continue
broker.ack(event["event_id"])
print(balances["acct-1"]) # 125The first pass applies the deposit and "crashes" before the ack. The broker redelivers, the consumer sees the ID in processed_ids, and the balance stays at 125. Remove the processed_ids check and the balance becomes 150. That is the difference between at-least-once alone and effectively-once.
The in-memory set is only a teaching device. In a real system the processed ID and the state change must be saved in the same database transaction. Otherwise a crash between the two writes brings the duplicate problem back.
Choosing a guarantee
Ask what happens when an event is lost and what happens when it is applied twice.
- If loss is acceptable and duplicates are not, or if freshness matters more than completeness, at-most-once can be enough. Metrics samples and telemetry are common cases.
- If loss is not acceptable, use at-least-once and make every consumer tolerate duplicates. This is the default for business events such as orders, payments and inventory.
- If a duplicate would do damage and the effect is not naturally repeatable, add deduplication or transactional processing on top of at-least-once.
Natural idempotence helps. "Set the order status to shipped" can be repeated safely. "Add 25 to the balance" cannot.
Common errors
- Acking at the start of the handler. This silently turns at-least-once into at-most-once. Failures that you expected to be retried vanish.
- Acking in a background thread before work finishes. Same result, harder to spot.
- Timeouts shorter than processing time. The broker redelivers while the first attempt is still running, and two copies run at once.
- Treating duplicates as rare. They are rare on a healthy day and common during deployments, rebalances and outages. Test them on purpose.
- Deduplicating by payload instead of event ID. Two genuine events can have identical contents. Use a unique ID assigned by the producer.
- Keeping dedup records forever, or for too short a time. Keep them at least as long as the longest period over which a redelivery or producer retry can occur, and expire them after that.
Exercise
A consumer reads an event, inserts a row into its database, and then sends the ack. The process is killed after the insert but before the ack. The broker uses at-least-once delivery. What happens next, and what must the consumer do to avoid a bad outcome?
Show answer
The broker gets no ack, so it redelivers the event after the timeout. The consumer will process it again and, without protection, insert a second row. The consumer should be idempotent: for example, check the event ID against a record of processed IDs, or use a unique constraint on the event ID, and do this in the same transaction as the insert.
Exercise
A team moves the ack call to the first line of the handler "to avoid slow redeliveries." Which guarantee do they now have, and what failure does it expose them to?
Show answer
They now have at-most-once delivery. If the handler crashes or throws after the ack, the broker considers the event done and never resends it, so the event is lost and its effect never happens.