Message processing and consumer acknowledgements
🎯 Introduction
After receiving a payment message, the order program needs to update the order. If it exits immediately after receiving the message, the work is unfinished, but the message may already be removed. Manual consumer acknowledgements address this by letting RabbitMQ track the outstanding delivery until processing finishes.
🧱 Explicitly signal completion
Previously, noAck: true meant the consumer did not send a separate acknowledgement, so RabbitMQ could remove the message after delivery. It did not check whether the order update succeeded.
With noAck: false, a received message remains unacknowledged. After successful processing, the consumer calls ack(message) to tell RabbitMQ to remove that delivery. This is a consumer acknowledgement. The management UI labels messages awaiting delivery Ready and delivered but unacknowledged messages Unacked. As a message is delivered and then acknowledged, Ready decreases and Unacked increases, then Unacked decreases. Read noAck as “no acknowledgement required”: true means no consumer acknowledgement is required; false enables manual acknowledgements.
| Stage | Message state | Consumer action |
|---|---|---|
| Not yet received | Waiting in the queue | Wait for delivery |
| Received, work unfinished | Delivered but unacknowledged | Complete the work without acknowledging early |
| Work succeeded | Waiting for the server to process the acknowledgement | Send ack on the channel that received the message |
After a consumer disconnects, the server must detect the disconnection before rescheduling unacknowledged deliveries. Requeueing does not necessarily finish the instant you press Ctrl+C.
If the connection drops during processing, RabbitMQ requeues unacknowledged messages after detecting it so a consumer can receive them again. While the connection remains valid, a brief delay in acknowledging does not cause immediate redelivery. The server may also close a channel when acknowledgements time out.
📤 Prepare an order task
Reuse the directory, amqplib, and config.mjs from installation and connection. Save all files and run commands there. This example simulates business processing without actually updating orders or sending notifications.
Use a separate work.order queue. The body contains only a payment ID. Use a new ID each time to distinguish new tasks from redeliveries.
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';
const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();
await channel.assertQueue('work.order', { durable: false });
channel.sendToQueue('work.order', Buffer.from(process.argv[2] ?? 'P1001'));
console.log('Work message submitted');
await channel.close();
await connection.close();
process.argv[2] is the ID supplied on the command line, defaulting to P1001. The log only indicates that the client executed the send operation; the next article uses publisher confirms to check server acceptance. This queue is non-durable. Here we test consumer exit, not a RabbitMQ restart.
📥 Simulate five seconds of processing, then acknowledge
Create the consumer:
import { setTimeout as delay } from 'node:timers/promises';
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';
const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();
await channel.assertQueue('work.order', { durable: false });
await channel.prefetch(1);
await channel.consume('work.order', async (message) => {
if (message === null) return;
console.log(process.pid, 'Started', message.content.toString(), 'Redelivered', message.fields.redelivered);
await delay(5000);
channel.ack(message);
console.log(process.pid, 'Completed', message.content.toString());
}, { noAck: false });
console.log('Waiting for work messages');
delay(5000) returns a wait that completes after five seconds, simulating the time required to update an order. await ensures acknowledgement happens afterward. Real applications should successfully commit the order update before acknowledging.
prefetch(1) limits this consumer to one unacknowledged message at a time for easier observation. process.pid is the process ID; redelivered is the server's redelivery flag. The flag helps observation but does not replace application deduplication.
Call ack() on the same channel that received the message, and do not acknowledge a delivery twice. The “Completed” log means the simulated work finished and ack was called. It is not a separate confirmation from the server. If you force the program to exit immediately afterward, the acknowledgement may not arrive.
🛠 Try interrupting the consumer
Finish old tasks and stop other worker.mjs processes first. Use an unused ID for each experiment. Start the consumer in terminal one:
node worker.mjs
Submit a task in terminal two:
node send-work.mjs P1001
After “Started P1001” appears in terminal one, press Ctrl+C within five seconds. Then restart worker.mjs.
Expect P1001 again with the redelivery flag true. Leave it running this time; after five seconds, “Completed P1001” appears. Keep the program online for a few more seconds, then stop and restart it. Normally, this acknowledged delivery should not appear again. If you pressed Ctrl+C after completion was printed, you did not interrupt an unacknowledged task; retry with a new ID.
🪤 Why duplicate business operations remain possible
There is a gap in which the database update has succeeded, but the connection drops before the consumer's acknowledgement arrives. The message may be redelivered even though the previous database operation took effect.
Business processing therefore also needs idempotency: repeating the same operation should have the same final effect as executing it once. For example, enforce a unique payment ID on payment transactions. On receiving that ID again, check the existing result instead of recording money twice. Commit the deduplication record and business write together; do not mark completion first and write the business data separately.
Consumer acknowledgements preserve unfinished deliveries; they do not promise that business operations execute exactly once. See the RabbitMQ acknowledgement documentation for redelivery details.
❓ Questions and answers
Q1: Can I acknowledge before updating the order?
That does not meet this goal. If the update fails after acknowledgement, RabbitMQ cannot redeliver on that basis.
Q2: Does throwing an exception automatically report processing failure?
No. The server does not know the business meaning of a JavaScript exception. The program must explicitly handle failure, as the later article on rejecting messages explains.
🧪 Exercise
Submit P1002 and restart the consumer after completion. Then submit P1003, stop it during processing, and restart it. Verify that only the latter reappears because it was unacknowledged, and explain why in your own words.
🎉 You have verified consumer acknowledgements by interrupting a running consumer!
Wildcard routing with topic exchanges
Distinguish routing keys from binding patterns, understand asterisks and hashes segment by segment, and verify destination queues.
Publisher confirms and returned messages
Distinguish client sends, server confirms, and unroutable message returns, and verify two publication outcomes.
