Thursday, 12 April 2018

Azure Functions: Add a message to a storage queue after a delay

I was looking at a specific problem today dealing with Azure Functions and adding messages to storage queues: I needed my Function to add a message to an output queue in order to trigger another function, but the challenge was, the message should not get added immediately and the second queue trigger function should not fire immediately as well.

We needed a delay between the completion of the first function and execution the second queue triggered function.

A not-so-great way of achieving this would be to add a Thread.Sleep before the message is added to the output queue but we really wanted to avoid that as it would keep the function running and would not be a truly "serverless" way of doing things.

I had a look at the visibilityTimeout setting in the host.json file but turns out it is meant for configuring the delay after which a retry is made when a function fails: https://docs.microsoft.com/en-us/azure/azure-functions/functions-host-json#queues

Fortunately, Jeff Hollan on twitter suggested a nice solution for this which utilised the initialVisibilityDelay property of the CloudQueue.AddMessage function. The great thing is this works seamlessly with Azure Function output bindings so we don't have to use the SDK ourselves.

Here is a sample of how my final code looks and it works pretty great!

Hope you find this useful!

No comments: