0
0
RabbitmqHow-ToBeginner ยท 3 min read

How to Set Queue TTL in RabbitMQ: Simple Guide

To set a queue TTL in RabbitMQ, use the x-message-ttl argument when declaring the queue. This argument defines the time in milliseconds that messages live before expiring and being removed from the queue.
๐Ÿ“

Syntax

When declaring a queue in RabbitMQ, you add the x-message-ttl argument to set the message time-to-live in milliseconds. This controls how long messages stay in the queue before they expire.

Example parts:

  • queue_name: Name of the queue.
  • durable: Whether the queue survives server restarts.
  • arguments: A dictionary where x-message-ttl is set to the TTL value in milliseconds.
python
channel.queue_declare(queue='my_queue', durable=True, arguments={'x-message-ttl': 60000})
๐Ÿ’ป

Example

This example shows how to declare a queue with a TTL of 60 seconds (60000 milliseconds). Messages older than 60 seconds will be removed automatically.

python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()

# Declare queue with message TTL of 60000 ms (60 seconds)
channel.queue_declare(queue='my_queue', durable=True, arguments={'x-message-ttl': 60000})

print('Queue declared with TTL of 60000 ms')
connection.close()
Output
Queue declared with TTL of 60000 ms
โš ๏ธ

Common Pitfalls

Common mistakes when setting queue TTL include:

  • Setting x-message-ttl on the queue but expecting it to affect existing messages already in the queue.
  • Using TTL values in seconds instead of milliseconds (RabbitMQ expects milliseconds).
  • Not setting the arguments parameter correctly when declaring the queue.
  • Confusing x-message-ttl (message TTL) with x-expires (queue expiration).

Always declare the queue with the TTL argument before publishing messages.

python
## Wrong way (TTL in seconds, no dictionary):
channel.queue_declare(queue='my_queue', durable=True, arguments={'x-message-ttl': 60})

## Right way (TTL in milliseconds):
channel.queue_declare(queue='my_queue', durable=True, arguments={'x-message-ttl': 60000})
๐Ÿ“Š

Quick Reference

PropertyDescriptionValue Type
x-message-ttlTime in milliseconds a message lives in the queueInteger (milliseconds)
x-expiresTime in milliseconds for queue to auto-delete if unusedInteger (milliseconds)
durableWhether queue survives broker restartBoolean
argumentsDictionary of queue parameters including TTLDictionary
โœ…

Key Takeaways

Set queue TTL using the x-message-ttl argument in milliseconds when declaring the queue.
TTL affects only messages published after the queue is declared with the TTL setting.
Use milliseconds, not seconds, for TTL values in RabbitMQ.
x-message-ttl controls message expiration; x-expires controls queue expiration.
Declare the queue with TTL before publishing messages to ensure TTL applies.