Consumer Acknowledgements: When Is a Message Done?
Kill a RabbitMQ worker mid-job with automatic and manual acks, watch Ready and Unacked, and learn when to ack, nack or reject a message.
On this page (11)
- The problem: a worker dies halfway through a resize
- The big picture: acknowledgement modes
- Run it: kill -9 a worker in both modes
- Automatic acks: the job is gone
- Manual acks: the job comes back
- Automatic vs manual acks
- Ack, nack and reject
- Why does acking twice close the channel?
- What happens if a worker never acks?
- Summary
- Sources
Chapter 1 ended with a message sitting in a queue. The previous lesson showed how it gets there. Now it has to leave. When may RabbitMQ delete a resize job: when it sends the job to a worker, or when the worker says the job is done? You will kill a worker in the middle of a resize, once each way, and count what is left.
The problem: a worker dies halfway through a resize
Darkroom's resize worker takes a job like {photoId, sizes} and makes the 320 px and 1080 px versions of a photo. A big panorama takes a while. Workers crash: out of memory, a deploy that kills the process, a bug in an image library.
If RabbitMQ forgot the job the moment it handed it over, a crash would lose the photo's thumbnails without any error. If it keeps the job until the worker confirms, a crash costs only time. The confirmation is called a consumer acknowledgement, or ack.
The big picture: acknowledgement modes
A consumer picks its mode when it subscribes. The RabbitMQ docs describe two modes:
- Automatic. "In automatic acknowledgement mode, a message is considered to be successfully delivered immediately after it is sent." The docs call this "fire-and-forget". A worker that dies before it finishes takes the job with it. In amqplib this is
noAck: true. - Manual. The broker waits until the consumer sends an ack (or a negative ack). Until then the message counts as unacknowledged, shown as Unacked in the management UI. This is amqplib's default,
noAck: false.
In manual mode, if the channel or connection closes while a delivery is still unacked, RabbitMQ puts the message back in the queue on its own. A lost TCP connection and a crashed consumer process both count. The next delivery carries the flag redelivered: true.
Run it: kill -9 a worker in both modes
The lab uses its own queue, darkroom.ack.resize, so it starts empty. It is declared the same way as darkroom.resize in lesson 3: a durable quorum queue. Set up a project as in lesson 3 (type: module, amqplib@2.4.2) and add two files.
enqueue.js queues three jobs and closes cleanly:
// enqueue.js: the Darkroom API queues three resize jobs for the lab.
import amqp from 'amqplib';
const QUEUE = 'darkroom.ack.resize';
const connection = await amqp.connect('amqp://127.0.0.1', {
clientProperties: { connection_name: 'upload-api' },
});
connection.on('error', (err) => console.error('connection error:', err.message));
const channel = await connection.createChannel();
channel.on('error', (err) => console.error('channel error:', err.message));
await channel.assertQueue(QUEUE, {
durable: true,
arguments: { 'x-queue-type': 'quorum' },
});
for (const photoId of ['p-501', 'p-502', 'p-503']) {
const job = { photoId, sizes: [320, 1080] };
channel.sendToQueue(QUEUE, Buffer.from(JSON.stringify(job)), {
contentType: 'application/json',
});
}
console.log('queued p-501, p-502, p-503');
await channel.close();
await connection.close();
resize-worker.js takes the mode from the command line. Each "resize" is a 15-second sleep, and jobs run one after another:
// resize-worker.js: resizes one photo at a time (each takes 15 s).
// Usage: node resize-worker.js auto | manual
import amqp from 'amqplib';
const QUEUE = 'darkroom.ack.resize';
const mode = process.argv[2] === 'auto' ? 'auto' : 'manual';
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const connection = await amqp.connect('amqp://127.0.0.1', {
clientProperties: { connection_name: `resize-worker-${mode}` },
});
connection.on('error', (err) => console.error('connection error:', err.message));
const channel = await connection.createChannel();
channel.on('error', (err) => console.error('channel error:', err.message));
await channel.assertQueue(QUEUE, {
durable: true,
arguments: { 'x-queue-type': 'quorum' },
});
let work = Promise.resolve(); // jobs run one after another
await channel.consume(
QUEUE,
(msg) => {
if (msg === null) return console.log('consumer cancelled by the broker');
const { photoId } = JSON.parse(msg.content.toString());
console.log(`got ${photoId} (redelivered: ${msg.fields.redelivered})`);
work = work.then(async () => {
console.log(`resizing ${photoId}...`);
await sleep(15000); // stands in for the real resize
if (mode === 'manual') channel.ack(msg); // done: now RabbitMQ may delete it
console.log(`done ${photoId}`);
});
},
{ noAck: mode === 'auto' },
);
console.log(`pid ${process.pid}, ${mode} acks, waiting on ${QUEUE}`);
You will check the queue with the management HTTP API. The broker emits these statistics every 5 seconds by default, and a fresh read can still show the previous numbers. So every read in this lesson starts with a 10-second wait. This is the exact command behind each queue count below:
sleep 10; curl -s -u guest:guest http://127.0.0.1:15672/api/queues/%2F/darkroom.ack.resize | jq -c '{messages, messages_ready, messages_unacknowledged}'
Automatic acks: the job is gone
Queue the jobs and start an auto-ack worker in terminal 1:
node enqueue.js
node resize-worker.js auto
queued p-501, p-502, p-503
got p-501 (redelivered: false)
got p-502 (redelivered: false)
got p-503 (redelivered: false)
pid 2856733, auto acks, waiting on darkroom.ack.resize
resizing p-501...
All three jobs arrived at once. Right after starting the worker, run the read command in terminal 2. It answers about 10 seconds later, while p-501 is still resizing:
{"messages":0,"messages_ready":0,"messages_unacknowledged":0}
The queue is already empty, with one job in progress and two not started. When terminal 1 prints resizing p-502..., kill the worker with the pid it printed, then run the read command again:
kill -9 2856733
The read still shows {"messages":0,...}. p-502 and p-503 are lost, and nothing reported an error.
Manual acks: the job comes back
Same steps, manual mode:
node enqueue.js
node resize-worker.js manual
The read started right after the worker, during p-501, shows all three jobs as Unacked:
{"messages":3,"messages_ready":0,"messages_unacknowledged":3}
After done p-501 and resizing p-502..., run kill -9 on the new pid, then the read command:
{"messages":2,"messages_ready":2,"messages_unacknowledged":0}
p-501 was acked and deleted. The two unacked jobs moved back to Ready. The broker log names the cause. --since 1m keeps older lines out:
docker logs --since 1m rabbitmq 2>&1 | grep -A1 'closing AMQP connection.*resize-worker-manual'
2026-11-29 16:25:46.638791+00:00 [warning] <0.3360.0> closing AMQP connection <0.3360.0> (172.17.0.1:60188 -> 172.17.0.2:5672 - resize-worker-manual, vhost: '/', user: 'guest', duration: '16s'):
2026-11-29 16:25:46.638791+00:00 [warning] <0.3360.0> client unexpectedly closed TCP connection
kill -9 let the operating system close the socket at once, so the broker noticed right away. A network failure sends no such signal, and the docs warn that "it takes a period of time to detect an unavailable client".
Start a manual worker again:
got p-502 (redelivered: true)
got p-503 (redelivered: true)
pid 2858601, manual acks, waiting on darkroom.ack.resize
resizing p-502...
done p-502
resizing p-503...
done p-503
Both jobs come back flagged redelivered: true. Once done p-503 appears, the read command shows {"messages":0,"messages_ready":0,"messages_unacknowledged":0}. Stop the worker with Ctrl+C and delete the lab queue in the UI.
Automatic vs manual acks
Automatic (noAck: true) | Manual (noAck: false) | |
|---|---|---|
| Broker deletes the message | When it sends it | When the consumer acks it |
| Worker killed mid-job | Delivered jobs are lost | Unacked jobs go back to Ready |
| What you saw after the kill | 0 messages | messages_ready 2 |
| Cap on deliveries in flight | None, by definition | Prefetch (next lesson) |
| Redeliveries | None, so losses instead | Yes, even after partial work |
Manual mode trades loss for repeats. If the worker had written the 320 px file before it died, the redelivery writes it again. The docs put it plainly: "consumers must be prepared to handle redeliveries". The second delivery can also land on a different consumer. A later lesson makes the resize worker idempotent.
In the run, the manual worker held all three jobs as Unacked at once. With no prefetch limit, any number of deliveries can be unacked on a channel. Quorum queues cap consumer prefetch at 2,000. The next lesson sets a limit.
Ack, nack and reject
A consumer in manual mode answers each delivery in one of three ways:
| amqplib call | AMQP method | Meaning | Several at once |
|---|---|---|---|
channel.ack(msg) | basic.ack | Done, delete it | ack(msg, true) |
channel.nack(msg, false, requeue) | basic.nack | Not processed | nack(msg, true, requeue) |
channel.reject(msg, requeue) | basic.reject | Processing failed | No |
requeue: true returns the message to the queue, at its old place when RabbitMQ can manage it. requeue: false removes it: RabbitMQ dead-letters it when the queue has a dead letter exchange, and drops it otherwise. In amqplib, requeue defaults to true, so pass false when you mean "give up".
ack-lab.js runs one message through all of them on a lab queue, darkroom.ack.lab, using channel.get to take one message at a time. It publishes on a confirm channel and waits for the confirm, so the message is in the queue before the first get; the publisher confirms lesson explains how that works.
// ack-lab.js: what ack, nack and reject do to one message.
import amqp from 'amqplib';
const QUEUE = 'darkroom.ack.lab';
const connection = await amqp.connect('amqp://127.0.0.1', {
clientProperties: { connection_name: 'ack-lab' },
});
connection.on('error', (err) => console.error('connection error:', err.message));
// A confirm channel lets us wait until the broker has each message (lesson 8).
const channel = await connection.createConfirmChannel();
channel.on('error', (err) => console.error('channel error:', err.message));
await channel.assertQueue(QUEUE, {
durable: true,
arguments: { 'x-queue-type': 'quorum' },
});
const job = Buffer.from(JSON.stringify({ photoId: 'p-777', sizes: [320] }));
channel.sendToQueue(QUEUE, job);
await channel.waitForConfirms(); // the message is in the queue before we get it
// Take the message once (manual ack) and print what the consumer sees.
async function take(step) {
const msg = await channel.get(QUEUE, { noAck: false });
if (!msg) {
console.log(`${step}: queue is empty`);
return null;
}
const count = msg.properties.headers?.['x-delivery-count'] ?? '-';
console.log(`${step}: tag ${msg.fields.deliveryTag}, redelivered ${msg.fields.redelivered}, x-delivery-count ${count}`);
return msg;
}
let msg = await take('1 first get');
channel.nack(msg, false, true); // not processed, put it back
msg = await take('2 after nack(requeue=true)');
channel.reject(msg, true); // processing failed, put it back
msg = await take('3 after reject(requeue=true)');
channel.reject(msg, false); // give up: dropped, or dead-lettered if a DLX is set
await take('4 after reject(requeue=false)');
// A second ack for the same delivery breaks the channel.
channel.sendToQueue(QUEUE, job);
await channel.waitForConfirms();
msg = await take('5 new message');
channel.ack(msg);
channel.ack(msg);
await new Promise((resolve) => channel.once('close', resolve));
const cleanup = await connection.createChannel();
await cleanup.deleteQueue(QUEUE);
await connection.close();
node ack-lab.js
1 first get: tag 1, redelivered false, x-delivery-count -
2 after nack(requeue=true): tag 2, redelivered true, x-delivery-count -
3 after reject(requeue=true): tag 3, redelivered true, x-delivery-count 1
4 after reject(requeue=false): queue is empty
5 new message: tag 4, redelivered false, x-delivery-count -
channel error: Channel closed by server: 406 (PRECONDITION-FAILED) with message "PRECONDITION_FAILED - unknown delivery tag 4"
Two things to read in it, plus the error on the last line.
Nack and reject are not the same on a quorum queue. The amqplib docs describe reject as the single-message form of nack, but RabbitMQ counts them differently. Quorum queues track failed attempts in the x-delivery-count header. A basic.reject raises it and a basic.nack does not, as lines 2 and 3 show. Client crashes and connection loss raise it too (table). Since RabbitMQ 4.0 the default delivery limit is 20; past it, the message is dropped or dead-lettered. Since RabbitMQ 4.3, requeues with basic.nack do not count. The docs add: "Before 4.3, a message requeued using basic.nack counted towards the delivery limit." So nack with requeue on every failure can loop forever, and reject lets the limit stop a broken photo.
Delivery tags are per channel. Each delivery gets a tag that counts up on its channel: 1, 2, 3, 4 above. You must ack on the same channel that received the message.
Why does acking twice close the channel?
After the first ack, tag 4 no longer exists on that channel. The docs say acking the same tag again, or any unknown tag, gives a channel error PRECONDITION_FAILED - unknown delivery tag. That is the 406 on the last line, line 6. The channel closes, and every other unacked message on it goes back to the queue. In real code this usually comes from two code paths both calling ack, for example a finally block plus a success branch. Keep exactly one place that answers each message.
What happens if a worker never acks?
A worker can also hang instead of dying. RabbitMQ has a delivery acknowledgement timeout for that. What the 4.4 docs state:
- Since RabbitMQ 4.3 it applies only to quorum queues.
- The default is 30 minutes, set per node with
consumer_timeoutin milliseconds inrabbitmq.conf. - You can override it per queue with the
x-consumer-timeoutargument or theconsumer-timeoutpolicy key, also in milliseconds. - On expiry, RabbitMQ returns the unacked deliveries to the queue. For an AMQP 0-9-1 client that understands consumer cancel notifications, it cancels the consumer. For one that does not, it closes the channel with
PRECONDITION_FAILED.
amqplib announces support for cancel notifications when it connects, so a cancelled consumer sees its callback called with null. That is the msg === null branch in the worker. The demo only logs there; a real worker should exit so its supervisor restarts it, or subscribe again. If your resize jobs can take longer than 30 minutes, raise the timeout for that queue rather than turning acks off.
Summary
- An ack tells RabbitMQ a message is done. Only then may the broker delete it.
- Automatic acks (
noAck: true) delete on send. A killed worker loses every job it was holding. - Manual acks keep delivered jobs as Unacked. If the channel or connection closes, they return to Ready with
redelivered: true. - Ack after the work is finished, never before.
nackandrejectwithrequeue: falsedrop the message or send it to a dead letter exchange. On quorum queues since RabbitMQ 4.3,rejectcounts toward the delivery limit andnackdoes not.- Ack each delivery once, on the channel that received it.
- Manual acks mean redeliveries, so plan for duplicates.
Sources
Looked up on 2026-11-29 against RabbitMQ 4.4 (Docker image rabbitmq:4.4.1-management), amqplib 2.4.2 and Node.js 24.18.0. Every output above comes from a real run.
