When to acknowledge
A consumer that has received a message must do two things: do the work, for example save an order to the database, and acknowledge the message to the broker. The order of these steps looks like a detail until the consumer crashes between them. Then the order alone decides whether the message is lost or comes back.
Back to the courier. The customer has to sign for the parcel and put the goods on the shelves. If they sign right at the door, the courier leaves and closes the order. Should the customer trip in the hallway and break the parcel, there will be no new one. If they put the goods away first and never get to sign, the courier gets no signature and comes back tomorrow with the same parcel.
The analogy breaks in one place: a real parcel cannot be brought a second time once the customer has taken it. The broker, however, keeps the message until the acknowledgement and can hand it out again, even if the first copy has already been processed.
Two orders of steps
Acknowledge first
- The consumer receives the message.
- It acknowledges the message, and the broker deletes it for good.
- The consumer crashes before finishing the work.
- After the restart the broker has nothing to hand out: the message is lost.
This is at-most-once: the message can be lost, but it is never repeated.
Process first
- The consumer receives the message.
- It does the work.
- It crashes before the acknowledgement.
- The broker sees that the message is not acknowledged and hands it out again.
This is at-least-once: the message is not lost, but the work runs twice if the consumer crashes between steps 2 and 3.
For important messages you choose the second order: a repeat can be made harmless, a loss cannot be undone. Interviewers often ask when to acknowledge a message, and the answer "after the work" is worth completing right away: "so repeats are possible".
Pick the order and the crash point, then step through.
Broker: m7 in the queue. Database: no order.
Broker: m7 in the queue. Database: no order.
What it looks like in RabbitMQ
Let's check on a real broker. A queue in RabbitMQ is a list of messages from which the broker hands each one to a single consumer and deletes it after the acknowledgement. A small Go program works with the orders queue in three modes (RabbitMQ 4.4):
publishputs three messages into the queue:m1,m2andm3.- With no arguments the program reads the queue: it acknowledges
m1, receivesm2and exits with an error before the acknowledgement, as if it crashed. drainreads whatever is left and acknowledges each message.
The rabbitmqctl list_queues command shows two counters:
messages_ready: messages waiting to be handed out;messages_unacknowledged: messages handed out but not yet acknowledged.
After publishing, the queue holds three ready messages:
$ go run . publish
$ rabbitmqctl list_queues name messages_ready messages_unacknowledged
Timeout: 60.0 seconds ...
Listing queues for vhost / ...
name messages_ready messages_unacknowledged
orders 3 0Now the consumer receives m1, acknowledges it, receives m2 and crashes:
$ go run .
got m1 redelivered=false
got m2 redelivered=false
crash before ack
exit status 1
$ rabbitmqctl list_queues name messages_ready messages_unacknowledged
Timeout: 60.0 seconds ...
Listing queues for vhost / ...
name messages_ready messages_unacknowledged
orders 2 0There are now two ready messages and zero unacknowledged. When the program crashed, its connection to the broker closed, and RabbitMQ returned to the queue everything it had handed to it without an acknowledgement. Message m1 is acknowledged and deleted for good.
Let's run drain:
$ go run . drain
got m2 redelivered=true, ack
got m3 redelivered=true, ack
$ rabbitmqctl list_queues name messages_ready messages_unacknowledged
Timeout: 60.0 seconds ...
Listing queues for vhost / ...
name messages_ready messages_unacknowledged
orders 0 0Message m2 came back, so the work on it was not lost. The flag redelivered=true means the broker has handed this message out before. Look at m3: the first consumer never got to it, yet it carries the flag too. The broker sent m3 to the program ahead of time because no limit on unacknowledged messages per consumer was set. This limit is called prefetch.
The order in code
The client is imported with the line import amqp "github.com/rabbitmq/amqp091-go": the name amqp in the examples is this alias. In the amqp091-go client the consumer receives messages as values of type amqp.Delivery from the Go channel msgs.
A Go channel is a queue of values inside the program: a for range loop takes messages from it one by one. Each message is acknowledged by calling d.Ack(false), where false means "acknowledge only this message, not all the previous ones at once".
Acknowledge first:
func consume(msgs <-chan amqp.Delivery) error {
for d := range msgs {
d.Ack(false) // ✗
if err := save(d); err != nil {
return err
}
}
return nil
}If save returns an error or the program crashes inside it, the message is already acknowledged, and the broker will not return it.
Process first:
func consume(msgs <-chan amqp.Delivery) error {
for d := range msgs {
if err := save(d); err != nil {
return err
}
d.Ack(false) // ✓
}
return nil
}Here, on an error, the function returns without acknowledging the message. When the program exits or closes the connection, the broker hands this message out again.
The same in Kafka
Kafka stores messages as numbered records in a log, and an offset is the number of a record. A Kafka consumer does not acknowledge each message; it saves the offset of the next record it needs to read, and this is called an offset commit. The choice is the same: commit the offset before processing and you get at-most-once, after it and you get at-least-once.
Common mistake
Turning on automatic acknowledgement:
msgs, err := ch.Consume(q.Name, "", true, false, false, false, nil) // ✗Here ch is an AMQP channel, the program's session with the broker inside a connection, not a Go channel; q is the declared queue.
The third argument of Consume is autoAck. With true, RabbitMQ treats a message as acknowledged as soon as it has sent it to the consumer. This is the same "acknowledge first" order, only hidden: the code has no Ack at all, and messages are lost on every crash. Pass false and call d.Ack(false) after the work.
Key points
- If you acknowledge before the work, the message is lost when the consumer crashes: this is at-most-once.
- If you acknowledge after the work, the broker returns the message when the consumer crashes: this is at-least-once, and the work may repeat.
- RabbitMQ returns everything unacknowledged to the queue when the consumer's connection closes and marks those messages
redelivered. autoAckset totrueis acknowledging before the work too.