Sub topic 5
At-most-once, at-least-once, and exactly-once delivery
Prerequisites and scope
This chapter assumes you know what a producer, a consumer, a broker and a queue are. It also assumes you know that a consumer sends an acknowledgement (ack) after handling a message. If those ideas are new, read the earlier chapters on brokers and acknowledgements first.
A delivery guarantee is a promise about how many times a consumer's processing logic runs for each message, even when connections drop or processes crash. There are three common names for these promises. Each one is a different answer to the question: what should happen when the broker is not sure whether a message was handled?
The core problem: uncertainty
Networks and processes fail. When a consumer receives a message, the broker cannot see inside the consumer. It only sees whether an ack arrives. Consider these cases:
- The consumer crashes before it does any work. No ack arrives.
- The consumer finishes the work and crashes before it sends the ack. No ack arrives.
- The consumer finishes the work and sends the ack, but the network drops it. No ack arrives.
From the broker's point of view, all three look identical. It must pick a policy. It can assume the message was lost and never send it again. Or it can assume the message was not handled and send it again. Every delivery guarantee follows from this choice.
The same uncertainty exists on the producer side. If a producer sends a message and the connection drops before the broker confirms it, the producer does not know whether the broker stored it. Retrying may create a duplicate. Not retrying may lose the message.
At-most-once delivery
At-most-once means each message is delivered zero or one times. A message may be lost, but it is never processed twice.
The broker achieves this by treating a message as finished as soon as it hands it over. In RabbitMQ this is the auto_ack=True mode of a consumer. In some systems it corresponds to a consumer committing its position before processing.
import pika
def handle(ch, method, properties, body):
# The broker already considers this message done.
# If we crash here, the message is gone.
print("handling", body)
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.queue_declare(queue="metrics", durable=True)
ch.basic_consume(queue="metrics", on_message_callback=handle, auto_ack=True)
ch.start_consuming()Cost: you accept data loss. Benefit: low latency, no redelivery logic, and no duplicates to defend against.
Use it when a lost message does not matter and a duplicate would be harmful or wasteful. Examples are high-volume metrics samples, a "user is typing" signal, or a cache-warming hint. The next sample replaces the lost one.
At-least-once delivery
At-least-once means each message is delivered one or more times. A message is never lost (assuming it was durably stored), but it may be processed more than once.
The broker achieves this by keeping the message until it receives an ack. If the ack does not arrive, because the consumer crashed, the channel closed, or a timeout expired, the broker redelivers the message. You saw this pattern in the acknowledgements chapter:
import pika
def process(body):
print("handling", body)
def handle(ch, method, properties, body):
try:
process(body)
ch.basic_ack(delivery_tag=method.delivery_tag)
except Exception:
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False)
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.queue_declare(queue="tasks", durable=True)
ch.basic_qos(prefetch_count=10)
ch.basic_consume(queue="tasks", on_message_callback=handle, auto_ack=False)
ch.start_consuming()The ack comes after process. If the process dies between those two lines, the side effect has happened but the broker will redeliver. That is the duplicate window.
Duplicates also arise in other ways:
- A producer retries after a timeout, and the broker had already stored the first attempt.
- The broker restarts and redelivers messages that were delivered but not yet acked.
- A consumer takes longer than the broker's ack or visibility timeout, so the broker hands the message to a second consumer while the first is still working.
Cost: your consumer must tolerate duplicates. Benefit: no silent loss. This is the default choice for most business workloads, such as sending email, charging an order, or resizing an image.
Exactly-once delivery
Exactly-once means each message has its effect once, with no loss and no duplicates.
True exactly-once delivery over an unreliable network is not achievable in the general case. The uncertainty described earlier cannot be removed. The sender can never know whether the receiver acted before the failure. What systems offer in practice is exactly-once processing, or effectively-once: at-least-once delivery combined with a mechanism that makes duplicates have no extra effect.
There are two main ways to get this effect.
- Idempotent consumers. The consumer records which message IDs it has handled and ignores repeats. This works with any broker.
- Transactional processing inside one system. Some platforms, such as Kafka with transactions, can commit the output messages and the consumer's input position atomically. This gives exactly-once only within that system. If your handler also calls an external HTTP API or sends an email, the guarantee does not reach those side effects.
The following example shows the first approach. It records the message ID in the same database transaction as the side effect. If the transaction commits, both are saved. If it rolls back, neither is.
import sqlite3
def handle_once(db, message_id, apply):
with db:
cur = db.execute(
"INSERT OR IGNORE INTO processed (message_id) VALUES (?)",
(message_id,),
)
if cur.rowcount == 0:
return False
apply(db)
return True
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE processed (message_id TEXT PRIMARY KEY)")
print(handle_once(db, "m-1", lambda d: None))
print(handle_once(db, "m-1", lambda d: None))The first call prints True. The second prints False because the insert was ignored, so apply did not run again. The next chapter covers this technique in more detail.
Cost: extra storage, an extra write per message, and care about which side effects share the transaction. Benefit: results that behave as if each message ran once.
Comparing the three
| Guarantee | Loss possible | Duplicates possible | Typical mechanism | Typical use |
|---|---|---|---|---|
| At-most-once | Yes | No | Ack before processing, or auto-ack | Metrics, transient hints |
| At-least-once | No | Yes | Ack after processing, redeliver on timeout | Most business tasks |
| Exactly-once (effective) | No | Delivered yes, effect no | At-least-once plus idempotency or transactions | Payments, inventory, ledgers |
Ordering of ack and side effect
The guarantee you get depends largely on where you place the ack relative to the work.
- Ack, then work: a crash between them loses the message. This is at-most-once.
- Work, then ack: a crash between them repeats the message. This is at-least-once.
There is no third position that avoids both failures. The only way out is to make the work safe to repeat, so you can choose "work, then ack" and accept duplicates.
Common errors
- Assuming the broker gives exactly-once. Vendor documentation may use the phrase. Read the scope: it usually covers only messages flowing within that one system.
- Forgetting the producer side. A consumer that is idempotent does not help if the producer publishes two distinct messages for one business event. Give each business event a stable ID, generated once, and reuse it on retries.
- Using a random ID per delivery. If you generate the deduplication key inside the consumer on each attempt, every redelivery looks new. Use an ID that travels with the message.
- Side effects outside the transaction. Recording the ID in a database and then calling an external payment API leaves a gap. If the API call succeeds and the commit fails, the retry calls the API again. Pass the message ID to the external service as an idempotency key where it supports one.
- Unbounded deduplication tables. The
processedtable grows forever. Decide how long a duplicate can plausibly arrive, and expire entries after that window. - Slow handlers. If processing outlasts the ack timeout, the broker redelivers while the first attempt is still running. Set the timeout above your worst-case handler time, or extend it as the work proceeds.
Decision criteria
Ask these questions in order:
- Is losing a message acceptable? If yes, at-most-once is simpler and faster.
- Is the operation naturally safe to repeat, such as setting a value, or upserting a row by key? If yes, at-least-once is enough with no extra work.
- Does a repeated effect cause harm, such as a double charge? If yes, add idempotency keys or deduplication, giving effectively-once.
- Does the whole flow stay inside one system with transactional support? If yes, the platform's own exactly-once feature may be simpler than building deduplication yourself.
Exercise
A consumer reads a message, inserts a row into an orders table, and then calls basic_ack. The process is killed right after the insert commits and before the ack is sent. What delivery guarantee does this consumer give, what happens next, and what one change would make the outcome safe?
Show answer
This is at-least-once, because the ack follows the work. The broker never receives the ack, so it redelivers the message, and the consumer inserts a second row. To make it safe, include a stable message ID (or order ID) with the message and enforce uniqueness on it, for example a primary key with INSERT OR IGNORE in the same transaction as the insert. The redelivered message then has no further effect, which gives effectively-once processing.
Exercise
Why can a broker not provide exactly-once delivery by itself when a consumer's handler sends an email?
Show answer
The broker only sees whether an ack arrives. If the consumer sends the email and then crashes before acking, the broker cannot tell that the email was sent and must redeliver, so the email may be sent twice. The email service is outside the broker's transaction. The fix is to make the send idempotent, for example by passing the message ID as an idempotency key or recording a sent marker before retrying.