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 wherex-message-ttlis 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-ttlon 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
argumentsparameter correctly when declaring the queue. - Confusing
x-message-ttl(message TTL) withx-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
| Property | Description | Value Type |
|---|---|---|
| x-message-ttl | Time in milliseconds a message lives in the queue | Integer (milliseconds) |
| x-expires | Time in milliseconds for queue to auto-delete if unused | Integer (milliseconds) |
| durable | Whether queue survives broker restart | Boolean |
| arguments | Dictionary of queue parameters including TTL | Dictionary |
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.