Updated on 2024-09-18 GMT+08:00

Configuring RabbitMQ TTL

TTL (time to live) indicates the expiration time. 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.

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.

TTL is a RabbitMQ feature that must be used with caution because it may adversely affect system performance.

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 before expiration. 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);   // Set queue TTL to 1,800,000 ms.
channel.queueDeclare("myqueue", false, false, false, args);

Configuring Message TTL

  • In the queue configuration

    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);   // Set queue TTL to 6,000 ms.
    channel.queueDeclare("normalQueue",true,false,false,arg); 
  • For a dedicated 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")   // Set message TTL to 60,000 ms.
                                       .build();
    channel.basicPublish("my-exchange", "routing-key", properties, messageBodyBytes);