Time to Live

Time to live for automatic message expiration

User requests an OTP. Your queue is backed up; the SMS worker is 8 minutes behind. By the time the message is handled, the code is invalid and you spam the user with a useless code. Time to Live drops the message if it sits in the queue longer than its lifetime — useful for OTPs, real-time notifications, cache-warm requests, and any message whose value expires before delivery.

Message Handler Time to Live

You may delay handling given asynchronous message by adding #[Delayed] attribute.

#[TimeToLive(new TimeSpan(seconds: 50))]
#[Asynchronous("notifications")]
#[EventHandler(endpointId: "welcomeEmail")]
public function sendWelcomeNotificationWhen(UserWasRegistered $event): void
{
   // handle welcome notification
}

Using Expression language

To dynamically calculate expected TTL, we can use expression language.

#[TimeToLive(expression: 'headers["expirationTime"]']
#[Asynchronous("notifications")]
#[EventHandler(endpointId: "welcomeEmail")]
public function sendWelcomeNotificationWhen(UserWasRegistered $event): void
{
   // handle welcome notification
}

We could also access any object from our Dependency Container, in order to calculate the delay and pass there our Command:

Message Time to Live

We may send an Message and tell Ecotone to set Time to Live using timeToLive Message Header:

Asynchronous Message Channel need to support this option to be used

Controlling Header Override Behavior

By default, the #[TimeToLive] attribute will override any existing timeToLive header that was set when sending the message. However, you can change this behavior using the shouldReplaceExistingHeader parameter.

Using Attribute as Default (Not Override)

When you want the attribute to act as a default value that can be overridden by message metadata:

With shouldReplaceExistingHeader: false:

  • If the message already has a timeToLive header, the attribute will not override it

  • If the message does not have a timeToLive header, the attribute value will be used

This is useful when you want:

  • Handler-level defaults via attributes

  • Per-message overrides via metadata (e.g., different TTL based on message priority or type)

Last updated

Was this helpful?