AWS Builder Center

RabbitMQ: Delayed Queue

A Delayed Queue in RabbitMQ is a queue where messages are not delivered immediately. They wait for a specified delay before being available to consumers.

RabbitMQ: Delayed Queue

1. Overview

A Delayed Queue in RabbitMQ is a queue where messages are not delivered immediately. They wait for a specified delay before being available to consumers.
Use cases:
  • Sending reminder emails
  • Delayed retries for failed jobs
  • Scheduled notifications

2. Delayed Queue Using DLX (Dead Letter Exchange)

How it Works

  • Messages go into a holding queue first
  • Each message has a TTL (Time-To-Live)
  • After TTL expires, message is dead-lettered to the real queue

Producer Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const amqp = require("amqplib");

async function sendDelayedMessage() {
const connection = await amqp.connect("amqp://localhost");
const channel = await connection.createChannel();

// Real queue where message will be consumed
await channel.assertQueue("real_queue", { durable: true });

// Delayed queue (holding queue)
await channel.assertQueue("delayed_queue", {
durable: true,
arguments: {
"x-message-ttl": 5000, // 5 seconds delay
"x-dead-letter-exchange": "", // default exchange
"x-dead-letter-routing-key": "real_queue" // route to real_queue after TTL
}
});

// Send message to delayed queue
channel.sendToQueue("delayed_queue", Buffer.from("Hello after 5 seconds"));

console.log("Message sent to delayed queue. Waiting for delivery...");
setTimeout(() => connection.close(), 1000);
}

sendDelayedMessage();

Consumer Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const amqp = require("amqplib");

async function consumeRealQueue() {
const connection = await amqp.connect("amqp://localhost");
const channel = await connection.createChannel();

await channel.assertQueue("real_queue", { durable: true });

console.log("Waiting for messages from real_queue...");
channel.consume("real_queue", (msg) => {
console.log("Received:", msg.content.toString());
channel.ack(msg);
});
}

consumeRealQueue();
Explanation:
  • Message waits in delayed_queue for TTL (5s)
  • Then automatically moved to real_queue
  • Consumer receives it after delay
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article