Delayed re-queuing RabbitMQ using PHP


While using RabbitMQ I got in a situation that some code was failing since an external service was unreachable. To overcome this problem I wanted to re-queue some messages for later processing. I decided that I wanted to wait for X seconds before trying again.

My solution to this problem is using (two) dead-letter-exchanges.
By returning a Negative Acknowledgement (NACK) on the failure of the external service, RabbitMQ will deliver the message to a configured dead letter exchange. By configuring this exchange correctly it will publish the messages on a retry queue with the delay interval set as the messages time to live. The retry queue (in its turn) has the dead letter exchange set to the main queue. So when the time to live interval passes the retry queue publishes the message back on the main queue again causing my initial code to process it again.

In the sample a negative acknowlegdment is returned when a message with body “10” is received. This NACK puts the message on the dead letter exchange with a message TTL of 5 seconds. After 5 seconds it is placed back on the main queue.

You can find the code sample at Github