Skip to main content

Creating and Managing Queues

1. Declaring Queue

Property Description Default Value Notes
name Queue name Empty string Must be unique within the broker
durable Persists queue across broker restarts false Set to true for persistent queues
exclusive Queue is deleted when the connection closes false Used for temporary queues
autoDelete Queue is deleted when the last consumer unsubscribes false Useful for temporary queues
arguments Additional queue arguments Empty map Used for queue-specific configurations

Example: Declaring a Queue in Java

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

// Create a channel and declare a queue
Channel channel = connection.createChannel();
channel.queueDeclare("myQueue", true, false, false, null);
Note: The durable parameter ensures that the queue survives broker restarts. If set to false, the queue will be lost if the broker crashes.

2. Creating Durable Queue

Property Value Description
name queue_name Name of the queue to be created
durable true Ensures queue survives broker restarts
auto_delete false Queue is deleted when last consumer unsubscribes
exclusive false Queue is exclusive to the connection that created it

Example: Creating a Durable Queue in RabbitMQ

const amqp = require('amqplib');

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

  const queueName = 'my_durable_queue';
  const durable = true;

  await channel.assertQueue(queueName, { durable });
  console.log(`Durable queue '${queueName}' created successfully`);

  await channel.close();
  await connection.close();
}

createDurableQueue().catch(console.error);

3. Creating Exclusive Queue

Property Description Default Value Notes
exclusive When set to true, the queue is exclusive to the connection that created it. false Only one consumer can use an exclusive queue, and it is deleted when the connection closes.

Example: Creating an Exclusive Queue in RabbitMQ (Java)

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

// Assume 'channel' is already created and connected
String queueName = channel.queueDeclare("", false, true, true, null).getQueue();
Note: Exclusive queues are automatically deleted when the connection that created them is closed.

4. Creating Auto-Delete Queue

Property Value Description
auto_delete true When set to true, the queue will be deleted when the last consumer unsubscribes.
durable false Indicates whether the queue is durable (persisted to disk). Auto-delete queues are typically non-durable.
exclusive false When set to true, the queue is exclusive to a single connection and will be deleted when the connection closes.

Example: Creating an Auto-Delete Queue in RabbitMQ

const amqp = require('amqplib');

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

  const queueName = 'auto-delete-queue';
  const options = {
    autoDelete: true,
    durable: false
  };

  await channel.assertQueue(queueName, options);
  console.log(`Auto-delete queue "${queueName}" created.`);

  await channel.close();
  await connection.close();
}

createAutoDeleteQueue().catch(console.error);
Note: Auto-delete queues are useful for temporary workloads or testing scenarios where you don't want to manage queue cleanup manually.

5. Setting Queue Arguments

Argument Description Values Notes
durable Makes queue survive broker restarts true / false Default: false
auto_delete Deletes queue when no consumers left true / false Default: false
exclusive Queue is deleted when consumer closes connection true / false Default: false
max_length Maximum number of messages in queue Positive integer Messages are dropped from the front
max_length_bytes Maximum total size of messages in queue Positive integer (bytes) Messages are dropped from the front
message_ttl Time-to-live for messages in queue (milliseconds) Positive integer Messages expire after this time
dead_letter_exchange Exchange to send expired or rejected messages to String (exchange name) Used for DLX routing
dead_letter_routing_key Routing key for dead letter exchange String (routing key) Optional, defaults to original routing key
max_priority Maximum priority value for messages Positive integer Messages with higher priority are delivered first
overflow Behavior when queue reaches max length drop-head / reject-publish Default: drop-head

Example: Declaring a durable queue with TTL and DLX

const queueOptions = {
  durable: true,
  autoDelete: false,
  arguments: {
    'x-message-ttl': 30000,
    'x-dead-letter-exchange': 'dlx_exchange',
    'x-dead-letter-routing-key': 'dlx_routing_key'
  }
};

await channel.assertQueue('my_queue', queueOptions);

6. Configuring Queue TTL

Property Value Description
x-message-ttl 3600000 Time-to-live for messages in milliseconds
x-expires 7200000 Queue expiration time in milliseconds
x-max-length 1000 Maximum number of messages in queue
x-max-length-bytes 1048576 Maximum size of queue in bytes

Example: Setting Queue TTL via RabbitMQ Management UI

curl -u guest:guest -X PUT http://localhost:15672/api/queues/%2f/my-queue \
-H "Content-Type: application/json" \
-d '{"arguments":{"x-message-ttl":3600000,"x-expires":7200000}}</code>
</pre>
</div>
</div>
<div class="note">
<strong>Note:</strong> Messages that exceed the TTL will be dropped or dead-lettered if a dead letter exchange is configured.
</div>
<h2 id="7-setting-max-length">7. Setting Max Length<a href="#7-setting-max-length" class="toc__headingLink" aria-label="Link to this section"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h2>
<table>
<tbody>
<tr>
<th>Property</th>
<th>Value</th>
<th>Description</th>
</tr>
<tr>
<td class="property">x-max-length</td>
<td><code>1000</code></td>
<td>Maximum number of messages the queue can hold before it starts dropping old messages</td>
</tr>
<tr>
<td class="property">x-max-length-bytes</td>
<td><code>1048576</code></td>
<td>Maximum size in bytes of the queue before it starts dropping old messages</td>
</tr>
</tbody>
</table>
<div class="example">
<h2 id="example-setting-max-length-on-queue-creation">Example: Setting Max Length on Queue Creation<a href="#example-setting-max-length-on-queue-creation" class="toc__headingLink" aria-label="Link to this section"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h2>
<div class="codeBlock" data-language="javascript">
<pre><code>const queueOptions = {
  durable: true,
  autoDelete: false,
  arguments: {
    'x-max-length': 1000
  }
};

Example: Setting Max Length by Bytes

const queueOptions = {
  durable: true,
  autoDelete: false,
  arguments: {
    'x-max-length-bytes': 1048576
  }
};

8. Setting Max Length Bytes

Property Value Description
x-max-length-bytes 10485760 Maximum size in bytes of the queue's content (including message headers and body). When this limit is exceeded, older messages are removed to make space for new ones.

Example: Configuring max-length-bytes in a queue declaration

const queueOptions = {
  durable: true,
  autoDelete: false,
  arguments: {
    'x-max-length-bytes': 10485760 // 10 MB
  }
};

await channel.assertQueue('my-queue', queueOptions);
Note: The x-max-length-bytes setting applies to the total size of all messages in the queue, including headers and bodies. It works in conjunction with x-max-length to control both message count and total size.

9. Configuring Overflow Behavior

Property Values Description
overflow reject-publish, drop-head, ring Determines behavior when queue reaches its limit
max-length Integer Maximum number of messages in queue before overflow policy is applied
max-length-bytes Integer (bytes) Maximum total size of messages in queue before overflow policy is applied

Example: Setting overflow behavior to drop-head

{
  "overflow": "drop-head",
  "max-length": 1000
}
Note: The ring overflow policy is only available in RabbitMQ 3.10+.
Warning: Using reject-publish will cause publishers to receive errors when the queue is full.

10. Purging Queue Messages

Use the purge method to remove all messages from a queue while keeping the queue itself.

Example: Purging Messages from a Queue

const amqp = require('amqplib');

async function purgeQueue() {
  const connection = await amqp.connect('amqp://localhost');
  const channel = await connection.createChannel();
  
  const queueName = 'my-queue';
  
  // Purge all messages from the queue
  await channel.purgeQueue(queueName);
  
  console.log('Queue purged successfully');
  
  await channel.close();
  await connection.close();
}

purgeQueue().catch(console.error);
Method Description Notes
purgeQueue(queue) Removes all messages from the specified queue Does not delete the queue itself
Note: Purging a queue is irreversible and should be used carefully in production environments.

11. Deleting Queue

Option Values Notes
queue.delete queue.name Name of the queue to delete
queue.delete if_unused Boolean, delete only if not in use
queue.delete if_empty Boolean, delete only if empty

Example: Delete a Queue

const amqp = require('amqplib');

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

  const queueName = 'my-queue';
  await channel.deleteQueue(queueName);

  console.log(`Queue ${queueName} deleted`);
  await channel.close();
  await connection.close();
}

deleteQueue().catch(console.error);

12. Listing Queues

Property Description Values
queue.name Name of the queue string
queue.durable Whether the queue survives broker restarts true or false
queue.auto.delete Whether the queue is deleted when no consumers remain true or false
queue.arguments Additional queue arguments (e.g., TTL, dead-lettering) object

Example: Listing Queues via CLI

rabbitmqctl list_queues name messages consumers durable auto_delete

Example: Listing Queues via Management API

const axios = require('axios');

async function listQueues() {
  const response = await axios.get('http://localhost:15672/api/queues', {
    auth: {
      username: 'guest',
      password: 'guest'
    }
  });
  
  console.log(response.data);
}

listQueues();
Note: The list_queues command shows all queues in the current vhost. Use rabbitmqctl list_queues -p <vhost> to filter by vhost.

13. Checking Queue Status

Property Description Value
queue.name Name of the queue to check my_queue
queue.length Number of messages in the queue 0
queue.consumers Number of active consumers 2
queue.messages.unacked Unacknowledged messages 0

Example: Using RabbitMQ Management API to Check Queue Status

curl -u guest:guest http://localhost:15672/api/queues/%2f/my_queue

Example: Using RabbitMQ CLI to Check Queue Status

rabbitmqctl list_queues name messages consumers
Note: The messages field in the management API response includes both ready and unacknowledged messages.

Was this article helpful?