Sub topic 4
Acknowledging Messages
This chapter covers how a consumer tells the broker that a message is done, and what happens when it does not. It assumes you know what a producer, a consumer, and a broker are, and that you can read basic Python. The examples use RabbitMQ and the pika client, but the ideas apply to most brokers.
Why acknowledgements exist
A broker hands a message to a consumer over a network. Three things can go wrong after that: the consumer crashes, the network drops, or the handler raises an error. If the broker deleted the message at the moment of delivery, any of these would lose the work.
An acknowledgement (ack) is a signal from the consumer to the broker that says "I finished this message, you can forget it." Until the ack arrives, the broker keeps the message and treats it as in flight. If the consumer's connection closes without an ack, the broker puts the message back on the queue and delivers it again, usually to another consumer.
This gives you a simple rule: the broker never discards a message until a consumer has confirmed it.
The message lifecycle
A message on a queue is in one of three states, and the ack controls the move to the last one.
- Ready: waiting in the queue for a consumer.
- Unacknowledged: delivered to a consumer, but no ack or nack has come back yet.
- Removed: acknowledged and deleted.
Brokers report the ready and unacknowledged counts separately. A growing unacknowledged count usually means slow or stuck consumers. A growing ready count means consumers are not keeping up.
Ack, nack, and reject
A consumer has three ways to answer a delivery.
| Response | Meaning | Typical use |
|---|---|---|
| `basic_ack` | Processing succeeded. | Normal completion. |
| `basic_nack` with `requeue=True` | Processing failed, try again. | Temporary failure such as a brief database outage. |
| `basic_nack` with `requeue=False` | Processing failed, do not retry here. | Poison message, or hand-off to a dead-letter queue. |
basic_reject does the same as nack for a single message. basic_nack is a RabbitMQ extension that can also act on several messages at once with multiple=True. Other brokers use different names. Amazon SQS has no nack: you simply skip the delete and the message reappears after its visibility timeout. Kafka has no per-message ack: the consumer commits an offset.
Acknowledge after processing
The most important decision is when to send the ack. The consumer below acks only after process succeeds.
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()Points to notice:
auto_ack=Falseturns off automatic acknowledgement. Withauto_ack=Truethe broker treats the message as done the moment it is sent. A crash mid-handler then loses the message.delivery_tagis a number the broker assigns to each delivery on a channel. You must ack on the same channel that received the message. Acking on a different channel, or after the connection was lost, fails.requeue=Falserejects the message without putting it back. With a dead-letter policy on the queue, the broker routes it to a dead-letter queue instead of discarding it. The retries chapter covers that setup.basic_qos(prefetch_count=10)caps unacknowledged messages for this consumer at 10. Without it, the broker may push the whole backlog to one consumer.
Ack before or after?
| Choice | If the consumer crashes mid-processing | Resulting guarantee |
|---|---|---|
| Ack before processing | The message is gone. The work is never done. | At most once |
| Ack after processing | The message is redelivered. The work may run twice. | At least once |
Ack-after is the usual default because losing work is normally worse than doing it twice. The next chapter covers these guarantees in detail, and the chapter on idempotent consumers shows how to make duplicates harmless.
The window between work and ack
Ack-after still has a gap. Suppose the handler finishes its side effect, such as charging a card, and the process dies before basic_ack is sent. The broker sees a missing ack and redelivers. The card is charged again.
You cannot close this gap by reordering ack and work. You close it by making the work safe to repeat. A broker also sets the redelivered flag on such messages, which is a hint, not a guarantee. Some duplicates arrive without it, for example when the first ack was lost in transit.
Common errors
Forgetting to ack. The handler returns without acking. The message stays unacknowledged, the prefetch window fills, and the consumer stops receiving. The queue looks stuck while the consumer sits idle. When the connection finally closes, every unacked message returns to the queue at once. Always ack or nack on every code path.
Requeue loops. A handler fails on a bad message and nacks with requeue=True. The broker returns the message to the queue, often at the front, and the same consumer receives it again immediately. This repeats forever and burns CPU. Use requeue=False with a dead-letter queue for failures that retrying will not fix, and use delayed retries for temporary ones.
Acking from another thread. pika.BlockingConnection is not thread-safe. If you process messages in worker threads, schedule the ack back on the connection's thread, for example with connection.add_callback_threadsafe. Calling basic_ack directly from a worker can corrupt the connection.
Long handlers and timeouts. RabbitMQ has a consumer acknowledgement timeout, 30 minutes by default in recent versions. A handler that exceeds it gets its channel closed, and its messages are redelivered. SQS has the equivalent visibility timeout, and if processing outlasts it, a second consumer can receive the same message while the first is still working. Set the timeout above your slowest realistic handler, or extend it while you work.
Acking too much with multiple=True. Acking tag 10 with multiple=True also acks tags 1 through 9 on that channel. If handlers finish out of order, you may acknowledge a message that has not finished.
Publisher confirms
Acks also exist in the other direction. When a producer publishes, the broker may or may not have safely stored the message. In RabbitMQ, publisher confirms let the broker ack each published message once it has accepted responsibility for it. Without confirms, a producer cannot tell a stored message from one lost in transit. Acks protect the consumer side. Confirms protect the producer side. Reliable pipelines use both.
Design checklist
- Turn off auto-ack for any work you cannot afford to lose.
- Ack after the side effect is committed, never before.
- Make every code path end in an ack or a nack.
- Set a prefetch limit so unacked messages stay bounded.
- Send permanently failing messages to a dead-letter queue rather than requeueing them.
- Treat redelivery as normal and make handlers safe to repeat.
Exercise
A consumer uses auto_ack=True and processes a message by writing a row to a database. The process is killed halfway through the handler. What happens to the message, and what single change gives you at-least-once behavior?
Show answer
With autoack=True the broker considers the message delivered and removes it as soon as it is sent, so the message is lost and the row may never be written. Set autoack=False and call basic_ack only after the database write has committed. If the process dies before the ack, the broker redelivers the message, giving at-least-once behavior. The handler may then run twice, so the write should be safe to repeat.
Exercise
A queue shows 0 ready messages and 10 unacknowledged messages, and the single consumer (prefetch_count=10) has stopped doing any work. Name a likely cause and a fix.
Show answer
The handler most likely returns on some code path without calling basicack or basicnack, so all 10 prefetched messages stay unacknowledged and the broker sends nothing more. Fix the handler so every path, including exceptions, ends in an ack or a nack, for example with try/except around the processing as in the example above.