Skip to main content

Azure Service Bus - How to extend the lock of a message | RenewLock

In this post we will discuss about Azure Service Bus Topics and Queues, with a special focus on Peek and Lock feature.

Introduction
Azure Service Bus is a messaging system that allows us to send messages between different systems in a reliable and easy way. A lot of concepts from ESB are implemented by Service Bus, allowing us to do do magic stuff with messages.
There are two ways to consume messages from Service Bus
Peek and Lock - locks a message for a specific time internal and notify Service Bus when we want to mark the message as processed (removed from Service Bus)
Receive and Delete  - once a message is received from Service Bus, it is also deleted automatically from the messaging system

Peek and Lock
When using Peek and Lock, by default we lock the message for 60 seconds. This means that in this time interval the message is not available/visible for other consumers. Once we process the message we can mark it as processed.
If we don't mark the message as processed or something happens with it, the message will become available for consumers.

Problem
The default value for Peek and Lock is 60 seconds. We can change this value based on our needs. The highest value that is accepted is 5 minutes (300 seconds). This means that we should be able to execute our logic in this time interval and mark the message as consumed.
But, what is happening when the execution takes more than 5 minutes.

What we can do to be able to keep the functionality offered by Peek and Lock but in the same time to have more time for processing?

... kind of ....solution
The most common solution in this situation is to split the logic and extract something similar with a state machine. Yes, we can keep it in a storage, we can map it in other messages with different states, there are a lot of possibilities.

RenewLock
This simple but powerful command allows us to reset the timer and keep the lock of the message. We can call this method as many times we need, one... two... or even 100.
QueueClient queueClient = QueueClient.Create("fooqueue");

BrokeredMessage brokeredMessage = queueClient.Receive();
...
message.RenewLock();
...
message.RenewLock();
...
message.RenewLock();

Behind the scene, "RenewLock" is "calling" directly the "LockedUntilUtc" property.
You can use with success "LockedUntilUtc" property to check until when the lock is available.


Scenarios
Yes, it is great that we have it. There are many cases when you don't know how long it takes to process a message. For example, when you need to persist the message in a database and call an external service, in general it could take 60 seconds, but in some situations the call of external service could take 120 seconds. In this case you might want to keep the lock and not start the rollback process. In these cases this is perfect.
Other situations is when we don't know the complexity of the task that is triggered by a message. For example converting the encoding of a video. It can take 10 seconds or even 10 hours. In this case, this feature is great.

Concerns
Personally I'm not a big fan of this feature. Why?
First of all, I'm afraid on how people would use it. Because this can be used as a hack and keep the lock of the messages in cases when you would normally release the message. For example, when you have an error accessing an external resources and you have a retry mechanism that is waiting and waiting. You will keep the lock of the message for a lot of time, even if you are in a dead end scenario and normally you would put the system in a 'freeze' state.

Precaution
We should double check all the time that the lock renew logic is done where we want and WHEN we want. We don't want to create a infinite cycle.
QueueClient queueClient = QueueClient.Create("fooqueue");
// ..
bool messageIsConsumed = false;
while (!messageIsConsumed)
{
    BrokeredMessage brokeredMessage = queueClient.Receive();
    try
    {
        // some logic with brokeredMessage
        // something happens and an error is throw 
        throw new Exception();

        messageIsConsumed = true;
    }
    catch (Exception ex)
    {
        // ...
        brokeredMessage.RenewLock();
    }
}
In the above example, the renew will be done over and over again

Conclusion
This is a great feature, that can help us in complex situations when we need a little more time to finish the work. Be aware when and how you do this.

Comments

Popular posts from this blog

How to audit an Azure Cosmos DB

In this post, we will talk about how we can audit an Azure Cosmos DB database. Before jumping into the problem let us define the business requirement: As an Administrator I want to be able to audit all changes that were done to specific collection inside my Azure Cosmos DB. The requirement is simple, but can be a little tricky to implement fully. First of all when you are using Azure Cosmos DB or any other storage solution there are 99% odds that you’ll have more than one system that writes data to it. This means that you have or not have control on the systems that are doing any create/update/delete operations. Solution 1: Diagnostic Logs Cosmos DB allows us activate diagnostics logs and stream the output a storage account for achieving to other systems like Event Hub or Log Analytics. This would allow us to have information related to who, when, what, response code and how the access operation to our Cosmos DB was done. Beside this there is a field that specifies what was th...

Can User Technical Profile Influence AI Architecture Decisions?

In the last few days, I ran a small experiment on Devin/Windsurf/Cascade, BMAD, and LLM-based architecture decisions. The initial concern was simple: if an AI coding assistant knows something about the user, for example, that the user is a Java developer or a .NET developer, can this information influence the architecture and technology stack that the AI will propose? This question is important because many companies are starting to use AI tools not only for coding but also for product discovery, architecture, documentation, and technical decision-making. If the AI is influenced by the developer's personal profile, the result may not be fully neutral. It may look like a business or architecture decision, but in reality, it may be partially shaped by the context of the person using the tool. The test was done using BMAD with Devin/Windsurf/Cascade. The scenario was a unified field service operations platform. The task was to let BMAD refine the product, define the architecture and s...

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine: threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration: TeamCity .NET 4.51 EF 6.0.2 VS2013 It see...