Consumer failures and dead-letter handling
🎯 Introduction
After a payment, the notification program needs to send a text message. The program is still running, but the SMS API reports failure. Should it try again? Where should the task go if sending keeps failing? First we will move unfinished tasks to a separate queue for inspection. Then we will add one retry: acknowledge on success, and send the task to that queue only if the retry also fails.
🧱 An SMS failure does not mean the notification program exited
Suppose the payment ID is P4001. A message containing P4001 means “send a notification for this payment.” The notification consumer receives it from the queue and calls the SMS API.
On success, the consumer can call the familiar ack(message) to report completion. If the API returns an error, the consumer can still handle it, log it, and decide what to do next.
“Failure” here means the SMS operation failed while the consumer remains running. These experiments also require a working RabbitMQ connection and receiving channel.
A crashed consumer cannot execute further code. With this configuration, RabbitMQ requeues unacknowledged messages after detecting disconnection. That is the scenario from consumer acknowledgements, rather than the explicit rejection demonstrated here.
🧱 Reject the current message without requeueing it
RabbitMQ does not know what the SMS API returned. Even an exception in business code does not automatically send a task to a failure queue.
Start with the simplest approach: after an SMS failure, stop trying this task and keep it elsewhere for inspection. On the channel that received it, execute:
channel.nack(message, false, false);
nack rejects a received message. Its three arguments mean:
| Argument | Value here | Meaning |
|---|---|---|
| Message to reject | message | The currently received message |
| Reject multiple messages | false | Reject only this message |
| Requeue in the original queue | false | Do not requeue |
This only says “reject without requeueing”; it does not specify where to store the message next. Configure a destination on the original queue in advance. Without that configuration, the message is discarded.
RabbitMQ treats messages rejected without requeueing as dead letters. With the configuration in place, it sends the message to an exchange, which routes it to another queue.
- The exchange receiving dead letters is the dead-letter exchange.
- The queue storing them is commonly called a dead-letter queue.
These are the same exchanges and queues introduced earlier, now used for failed tasks. The consumer sends nack; RabbitMQ performs the routing.
🛠 Configure a destination for failed notification tasks
This example uses three names for three objects:
| Name | Object | Purpose |
|---|---|---|
notice.tasks | Original queue | Stores notification tasks awaiting processing |
notice.dead-exchange | Dead-letter exchange | Receives and routes rejected messages |
notice.dead-queue | Failure queue | Stores notification tasks awaiting inspection |
Once these objects and bindings exist, the consumer chooses an action based on the SMS result. The following diagram starts without retries and assumes the consumer process, RabbitMQ connection, and receiving channel are working:
courseComponents.mermaid.loading
The success branch never enters notice.dead-queue. The failure branch is triggered by the consumer's nack, not automatically by an API error. Process exit and disconnection are not the explicit rejection shown here. The later retry example adds a limited number of attempts before nack.
Reuse the practice directory and config.mjs to create setup:
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';
const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();
await channel.assertExchange('notice.dead-exchange', 'direct', { durable: false });
await channel.assertQueue('notice.dead-queue', { durable: false });
await channel.bindQueue('notice.dead-queue', 'notice.dead-exchange', 'rejected');
await channel.assertQueue('notice.tasks', {
durable: false,
deadLetterExchange: 'notice.dead-exchange',
deadLetterRoutingKey: 'rejected',
});
console.log('Notification task and failure queues created');
await channel.close();
await connection.close();
Create the dead-letter exchange, failure queue, and binding first, then set these options on the original notice.tasks queue:
deadLetterExchange: 'notice.dead-exchange',
deadLetterRoutingKey: 'rejected',
deadLetterExchange selects the exchange receiving dead letters. deadLetterRoutingKey selects the routing key used when forwarding. The binding also uses rejected, allowing messages to reach notice.dead-queue.
Both settings belong on the original queue because RabbitMQ needs to know where to send messages removed from it.
node setup-failure.mjs
For practice, settings are supplied in code. Handle conflicts with existing queue configurations as explained earlier. Production deployments can also manage dead-letter settings with server policies; see the official dead-letter documentation.
These non-durable queues only test forwarding while RabbitMQ remains running. Default dead-letter forwarding can lose messages when, for example, the destination queue is unavailable. It is not a reliable archive.
🛠 Verify forwarding with one message
Send a task
Create send-notice.mjs to read a payment ID from the command line and send it to the original queue:
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';
const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();
const paymentId = process.argv[2] ?? 'P1001';
channel.sendToQueue('notice.tasks', Buffer.from(paymentId));
console.log('Notification task submitted', paymentId);
await channel.close();
await connection.close();
Simulate an SMS failure
Create notice-failure.mjs. Instead of calling a real SMS API, it logs a simulated failure on receipt and sends nack:
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';
const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();
await channel.prefetch(1);
await channel.consume('notice.tasks', (message) => {
if (message === null) return;
console.log('Simulated notification failure', message.content.toString());
channel.nack(message, false, false);
}, { noAck: false });
console.log('Waiting for notification tasks');
noAck: false enables manual acknowledgements. prefetch(1) limits this consumer to one unacknowledged message at a time for observation. After the callback finishes, the program waits for the next message; logging failure does not make it exit.
Check the failure queue count
Create inspect-failed.mjs to query the number of messages awaiting processing in notice.dead-queue:
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';
const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();
const state = await channel.checkQueue('notice.dead-queue');
console.log('Messages waiting in failure queue', state.messageCount);
await channel.close();
await connection.close();
messageCount counts waiting messages. The query neither receives nor deletes them, and does not identify which specific messages entered the queue.
Run and compare results
If you have tried this before, finish older tasks in the original queue and stop the old consumer. Run only one notification consumer below, and ensure no other programs read or write the failure queue.
Start the consumer in terminal one and leave it running:
node notice-failure.mjs
In terminal two, record the failure queue count before submitting a task:
node inspect-failed.mjs
node send-notice.mjs P4001
Terminal one should print:
Simulated notification failure P4001
Query again in terminal two:
node inspect-failed.mjs
After forwarding, the count should increase by 1, for example from 0 to 1. Existing failed messages do not prevent comparing the increase.
Together with the consumer log for P4001 and the absence of other readers or writers during the experiment, this verifies forwarding. The count alone contains no payment ID and does not prove SMS success. If it remains unchanged, check whether the consumer received P4001, then verify the dead-letter exchange, binding, and original queue configuration.
🔁 Retry once after failure
The previous program simulates failure and immediately rejects the message. Now give it another chance: if the first send fails, wait one second and try again. Acknowledge on success. Only reject after both attempts fail, using the existing dead-letter configuration.
Change the consumer logic
Place this code inside the consumer callback after reading paymentId. sendNotice is a custom simulation function, not a real SMS sender: true means success and false means failure. Arguments 1 and 2 identify the first and second calls.
let sent = await sendNotice(paymentId, 1);
if (!sent) {
await delay(1000);
sent = await sendNotice(paymentId, 2);
}
if (sent) {
channel.ack(message);
} else {
channel.nack(message, false, false);
}
sent stores the latest result. Success on the first call skips if (!sent) and acknowledges immediately. Failure waits one second before the second call, then acknowledges or rejects according to its result. delay(1000) waits one second; the complete file imports it from node:timers/promises.
No ack or nack is sent before retrying, so the message remains unacknowledged during the wait. This simulator represents failure with false. Real APIs may return errors or throw exceptions; handle their results instead of assuming they also return false.
Prepare the experiment
Extract notice-retry.mjs from the complete examples and place it beside your existing config.mjs. It contains the logic above, simulation function, and connection code. Run it directly below without assembling snippets yourself.
Keep the existing queues and bindings. Finish old tasks, then stop notice-failure.mjs. Run one notification consumer per round, with no other programs reading or writing the dead-letter queue.
First attempt fails, retry succeeds
Start recover mode in terminal one. It makes the first call fail and the second succeed to verify recovery:
node notice-retry.mjs recover
In terminal two, record the dead-letter queue count, then send a task:
node inspect-failed.mjs
node send-notice.mjs P5002
Terminal one should print these lines in order, with about one second between the first two:
Notification failed P5002 attempt 1
Notification succeeded P5002 attempt 2
Consumer acknowledgement sent P5002
Keep the consumer running and run node inspect-failed.mjs again in terminal two. The count should be unchanged: the retry succeeded, so this task did not enter the dead-letter queue.
Both attempts fail
After the task finishes, press Ctrl+C in terminal one to stop the recover consumer. Start down mode, which makes both calls fail:
node notice-retry.mjs down
In terminal two, record the count again and send a new task:
node inspect-failed.mjs
node send-notice.mjs P5003
Terminal one should print:
Notification failed P5003 attempt 1
Notification failed P5003 attempt 2
Message rejected without requeueing P5003
Keep the consumer running and run node inspect-failed.mjs again in terminal two. After RabbitMQ forwards the message, the count should be 1 higher than before this round.
The last line in each set of logs only indicates that the client called ack or nack. Verify dead-letter arrival by combining it with the count change as described earlier.
This example retries once within the current processing attempt. If the process is interrupted, unacknowledged messages are redelivered under the consumer acknowledgement rules, and a restarted consumer begins with the first call again. Across multiple interruptions, the total number of SMS calls for one task can therefore exceed two.
During the one-second wait, the consumer still holds the unacknowledged message. With prefetch(1), it cannot receive another task yet. This approach suits brief retries. Calling nack(message, false, true) requeues the message and may cause immediate redelivery; it does not replace the wait.
❓ Questions and answers
Q1: Do dead-letter tasks retry automatically when the SMS API recovers?
No. notice-retry.mjs reads only notice.tasks. Once a message reaches notice.dead-queue, this program no longer receives it. Inspect the cause and arrange resending separately.
Q2: Do dead letters only come from explicit consumer rejection?
No. Message expiration and other conditions can also produce dead letters. This article demonstrates only rejection without requeueing.
🧪 Exercise
Finish the current task, then stop the consumer. Use normal mode to verify that first-attempt success skips retries:
node notice-retry.mjs normal
In another terminal, record the count and send P5004:
node inspect-failed.mjs
node send-notice.mjs P5004
Expect only one “Notification succeeded P5004 attempt 1” followed by “Consumer acknowledgement sent P5004”. There is no second call, and the dead-letter count does not increase. Use the code to explain why if (!sent) was skipped.
🎉 You can now retry a failed notification once and keep tasks that still fail for inspection!
Queue durability and message persistence
Configure queue durability and message persistence so unprocessed payment messages can be read after RabbitMQ restarts.
Multiple consumers and prefetch control
Share one queue's tasks between two consumers and observe how prefetch limits unacknowledged messages.
