Updated on 2024-07-25 GMT+08:00

Configuring RabbitMQ TTL

Time to live (TTL) is a RabbitMQ feature that must be used with caution because it may adversely affect system performance.

TTL

TTL indicates the expiration time. You can configure TTL for messages and queues. Message TTL can be configured in the following ways:

  • Configure a TTL in queue properties: All messages in the queue have the same expiration time.
  • Configure a TTL for each message: Each message has a dedicated TTL.

If both methods are used, the smaller TTL value is used.

If a message that has stayed in a queue for longer than the TTL, the message will be discarded. If a dead letter exchange has been configured for the queue, the message will be sent to the dead letter exchange, and then routed to the dead letter queue.

For more information about TTL, see TTL.

Configuring Queue TTL

The x-expires parameter in the channel.queueDeclare argument is used to control how long a queue will remain active after being unused before it is automatically deleted. "Unused" indicates that the queue has no consumer and is not re-declared, and the Basic.Get command is not called during this period. The value of x-expires must be an integer other than 0, in milliseconds.

The following example shows how to configure a queue TTL on a Java client.

Map<String, Object> args = new HashMap<String, Object>();
args.put("x-expires", 1800000);
channel.queueDeclare("myqueue", false, false, false, args);

Configuring Message TTL

Configure a TTL in queue properties: Add the x-message-ttl parameter to the channel.queueDeclare argument. The value must be an integer other than 0, in milliseconds.

The following example shows how to configure a message TTL in queue properties on a Java client.

Map<String,Object> arg = new HashMap<String, Object>();
arg.put("x-message-ttl",6000);
channel.queueDeclare("normalQueue",true,false,false,arg); 

Configure a TTL for each message: Add the expiration parameter to the channel.basicPublish argument. The value must be an integer other than 0, in milliseconds.

The following example shows how to set a per-message TTL on a Java client.

byte[] messageBodyBytes = "Hello, world!".getBytes();
AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                                   .expiration("60000")
                                   .build();
channel.basicPublish("my-exchange", "routing-key", properties, messageBodyBytes);