How to turn your RabbitMQ into a timer

During my work, I’ve run in to a problem. Mobile applications tokens can be dispatched to server, but there’s no guarantee at this moment that this token arrived, is still in transit, or the user just uninstalled the application. You can ask the server some time later for the status of these. My colleague suggested putting these tokens in a so-called dead-letter queue, in order to later call the server to check whether the delivery has happened, and remove non-existing tokens from the system.

A dead-letter-marked queue will try to deliver it’s messages to a predefined (in queue’s arguments) exchange (the dead-letter exchange) with the same routing_key that they were sent with. This may happen for following reasons:

This way, using TTL, you can turn RabbitMQ into a timer.

How do I shot web?

First:

  • declare a normal exchange say deadman of type direct
  • declare a queue named morgue with following arguments:
    • x-dead-letter-exchange: deadman
    • x-message-ttl: however you wish long in milliseconds. This has to be an int
  • declare a queue called graveyard, and bind it to exchange deadman with a routing key of morgue.

Now take care to never consume directly from the morgue queue. It’s simply a queue where messages wait to expire, and then to be dead-lettered straight towards graveyard. If you consume something from it, you can be sure that it was posted to the morgue queue x-message-ttl milliseconds ago.

If you want something to wait for the specified time period, you can just post the message to morgue queue. You can even override x-message-ttl with AMQP’s own message property of expiration.

Now, consume the graveyard queue and be happy with your own RabbitMQ-powered timer!

Enjoy!

Published

By Piotr Maślanka

Programmer, paramedic, entrepreneur, biotechnologist, expert witness. Your favourite renaissance man.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.