Delay Message and Maintain Delivery Count Azure Service Bus

Viewed 154

We have a scenario when we pull message from Azure Service Bus Queue and for some reason if one of the down stream is down than we would like to delay a message and put back to queue. I understand we can do through multiple ways(Set the property ScheduledEnqueueTime or use Schedule API)but either way we will have to create a new message and put back to queue which will lose the delivery count and also can result in an issue where we have duplicate message where sending the clone and completing the original are not an atomic operation and one of them fails.

https://www.markheath.net/post/defer-processing-azure-service-bus-message

based on the above article only way seems to be have our custom property, Is that the only way still as this article was written in 2016.

1 Answers

Scheduling a new message back does not increase the delivery count. And as you said, sending a message and completing a message are not atomic, it can be atomic with the help of transactions, thereby ensuring that all operations belonging to a given group of operations either succeed or fail jointly.

Here's an example:

ServiceBusClient client = new ServiceBusClient("<connection-string>");
ServiceBusReceiver serviceBusReceiver = client.CreateReceiver("<queue>");
ServiceBusSender serviceBusSender = client.CreateSender("<queue>");

var message = await serviceBusReceiver.ReceiveMessageAsync();
// Your condition to handle the down stream
if (true)
{
    using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
    {
        await serviceBusReceiver.CompleteMessageAsync(message);
        var newMessage = new ServiceBusMessage(message);
        newMessage.ScheduledEnqueueTime = new DateTimeOffset(DateTime.UtcNow.AddMinutes(1));
        await serviceBusSender.SendMessageAsync(newMessage);
        ts.Complete();
    }
}
Related