There are two ways to set the message expiration time (TTL) for RabbitMQ:

  1. Set through queue properties, where all messages in the queue have the same expiration time.
  2. Set the expiration time for each message individually, allowing different TTL for each message. If both methods are used together, the message's TTL will be the smaller value between the two.

Tip: For the first method of setting queue properties, once the message expires, it will be removed from the queue. In the second method, even if the message expires, it will not be immediately deleted from the queue because the expiration of each message is checked before delivery to consumers.

Below is a demonstration of how to set this using Golang, similar to other programming languages.

Set Queue TTL

Set the message expiration time through queue properties (x-message-ttl).

	// Queue properties
	props := make(map[string]interface{})
	// Message expiration time is 60 seconds
	props["x-message-ttl"] = 60000

	q, err := ch.QueueDeclare(
		"tizi365.ttl.hello", // Queue name
		true,   // Whether to persist the queue
		false,
		false,
		false,
		props, // Set queue properties
	)

Set Message TTL

Set the message expiration time through message properties

err = ch.Publish(
		"tizi365",     // Exchange name
		"", // Routing key
		false,
		false,
		amqp.Publishing{
			Expiration: "30000", // Expiration time is 30 seconds
			ContentType: "text/plain",
			Body:        []byte(body),
		})