Home / Posts tagged "Azure"

Introduction to the MultiProducerConcurrentConsumer for Azure Service Bus message completion

In the last post in the series about Azure Service Bus message completion, I briefly talked how the message batch completion could benefit from a more reactive approach. Before I dive into the inner workings of the reactive structure that I’m going to outline in the next few posts, I need to briefly recap the functional and non-functional requirements we need from the component.

The component shall

  • Make sure messages are only completed on the receiver they came from
  • Reduce the number of threads used when the number of clients is increased
  • Autoscale up under heavy load
  • Scale down under light load
  • Minimise the contention on the underlying collections used
  • Be completely asynchronous
  • Implements a push based model from the producer and consumer perspective
  • Respect the maximum batch sized defined by the client of the component or a predefined push interval
  • Provide FIFO semantics instead of LIFO
  • Be as lock-free as possible

From a design viewpoint the MultiProducerConcurrentConsumer (MPCC) component will look like

The MPCC manages internally N number of slots that can contain items of type TItem. Whenever the timeout or the batch size is reached the component fans out up to a provided concurrency per slot the completion callback.

class MultiProducerConcurrentConsumer<TItem> {
    public MultiProducerConcurrentConsumer(int batchSize, TimeSpan pushInterval, int maxConcurrency, int numberOfSlots) { }

    public void Start(Func<List<TItem>, int, object, CancellationToken, Task> pump) { }

    public void Start(Func<List<TItem>, int, object, CancellationToken, Task> pump, object state) { }

    public void Push(TItem item, int slotNumber) { }

    public async Task Complete(bool drain = true) { }
}    

Shown above is the class outline that we are going to use for the component. The constructor allows specifying the batch size, the push interval, the number of slots and the concurrency per slot. The component has a method to push items to it called Push. As soon as the component is started the provided pump delegate will be called whenever the batch size is reached or the push interval. The concurrency per slot is probably best explained by giving an example.

Let’s assume we have a batch size of 500 and a push interval of 2 seconds. When producers can produce 1500 items per second the batch size is reached three times per second. MPCC will auto-scale in that case up to the provided concurrency. So in the above example, it will take out 500 items and invoke the callback and then concurrently try to fetch another 500 items and again another 500 items until the slot is empty or the maximum concurrency is reached.

The Complete method is available for the deterministic stopping of the MPCC. It allows to asynchronously wait for all slots to be drained (by default) or immediately stop and throw away all items that haven’t been processed.

In the next post, we are going to depict the inner workings of the MultiProducerConcurrentConsumer, hope you’ll enjoy.

Complete messages where they came from with Azure Service Bus

In the last post, we made a simplistic attempt to speed up batch completion of messages by having multiple dedicated background completion tasks. Unfortunately, this introduced an interesting side effect.


static async Task BatchCompletionLoop() {
   while(!token.IsCancellationRequested) {
         ...
         await receiveClient.CompleteBatchAsync(lockTokens).ConfigureAwait(false);
         ...
      }
      await Task.Delay(TimeSpan.FromSeconds(5), token).ConfigureAwait(false);
   }
}

The code above is using a single receive client to complete message lock tokens in batches. Those lock token could come from multiple receive clients, but they would end up being completed on the same instance. Depending on the transport type you use it might work or it won’t. When you are using the NetMessaging (also known as SBMP) transport type the above code will just work. If you switch to AMQP as the transport type, the code will blow up with the following exception

Microsoft.ServiceBus.Messaging.MessageLockLostException: The lock supplied is invalid. Either the lock expired, or the message has already been removed from the queue.
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.MessageReceiver.EndCompleteBatch(IAsyncResult result)

For Azure Service Bus v3 and higher AMQP is the new standard protocol and SMBP is an opt-in choice.

The proprietary SBMP protocol that is also supported is being phased out in favor of AMQP. see documentation

What does that mean for our message completion? To have a robust completion code which works for both transport types, we have to make sure we only complete lock tokens on receivers the messages were coming from.

In its simplest form, we would need the following moving pieces. A concurrent stack or queue per message receivers, a generic message handling body which closes over the concurrent stack as an input parameter and similarly a parameterized completion loop.

var lockTokensToComplete = new ConcurrentStack<Guid>[numberOfReceivers];
// initialize the concurrent stacks
  
receiveClient1.OnMessageAsync(message => ReceiveMessage(message, lockTokensToComplete[0]);
...
receiveClientN.OnMessageAsync(message => ReceiveMessage(message, lockTokensToComplete[N-1]);

static async Task ReceiveMessage(BrokeredMessage message, ConcurrentStack<Guid> lockTokensToComplete) {
   await DoSomethingWithTheMessageAsync().ConfigureAwait(false);
   lockTokensToComplete.Push(message.LockToken);
}

and the completion loop

for(int i = 0; i < numberOfReceivers; i++) { 
   completionTasks[i] = Task.Run(() => BatchCompletionLoop(receivers[i], lockTokensToComplete[i]));
}
 
static async Task BatchCompletionLoop(MessageReceiver receiver, ConcurrentStack<Guid> lockTokensToComplete) {
   while(!token.IsCancellationRequested) {
    var lockTokens = new Guid[100];
      int numberOfItems = lockTokensToComplete.TryPopRange(lockTokens)
      if(numberOfItems > 0) {
         await receiver.CompleteBatchAsync(lockTokens).ConfigureAwait(false);
      }
      await Task.Delay(TimeSpan.FromSeconds(5), token).ConfigureAwait(false);
   }
}

We have reduced the contention since we have a dedicated lock token concurrent collection to operate on per receiver. We have a dedicated completion loop which is self-contained and only operates on the correct receiver and lock token collection pair. So far so good. Despite that we are still wasting a lot of unnecessary resources. We acquired up to the number receivers dedicated completion background tasks which might idle. And we still don’t exactly know if this code constructs scales elastically up and down depending on the number of messages received and the number of clients.

Ideally, we would have a reactive approach which automatically adapts based on parameters we give it. Building such a reactive approach will be the focus of the next few posts. Stay reactive!

Batch completion with multiple receivers on Azure Service Bus

In the last post, we created multiple receivers with multiple factories to speed up our message processing. Unfortunately, this has some consequences for our background completion loop. Since the message processing logic is shared between multiple receivers, all the receivers will try to push lock tokens into the concurrent stack. So the following code will be called by numberOfReceivers * concurrencyPerReceiver concurrently.

// same as before
await DoSomethingWithTheMessageAsync().ConfigureAwait(false);
lockTokensToComplete.Push(message.LockToken);
// same as before

So for example when we’d use 10 receivers with each a concurrency setting of 32 we’d be ending up pushing lock tokens to the concurrent stack from up to 320 simultaneous operations. Not a big deal you could say since the ConcurrentStack implementation is lock-free. Unfortunately, lock-free doesn’t necessarily mean it is contention free.

ConcurrentQueue<T> and ConcurrentStack<T> are completely lock-free in this way. They will never take a lock, but they may end up spinning and retrying an operation when faced with contention (when the CAS operations fail). Read more

The concurrent stack implementation internally uses a technique called spinning and retrying (for more information see the excellent Blocking vs. Spinning section from Joe Albahari). Under contention with a large number of concurrent operations these operations can fail multiple times and might become less efficient than we assumed them to be.

In the previous post I made the following statement:

When we’d received several hundred messages per seconds our randomly chosen “complete every one-hundredth messages” and then “sleep for five seconds” might turn out to be a suboptimal choice.

With multiple receivers pushing lock tokens into the concurrent stack, we might have made our problem even worse. It is entirely possible that our multiple concurrent receivers can fill the concurrent stack faster with lock tokens than our completion loop manage to complete. Our previously chosen five seconds sleep duration might turn out to be way too long under heavy load.

How about we just spin up multiple batch completion tasks like the following?

var completionTasks = new Task[numberOfReceivers];

for(int i = 0; i < numberOfReceivers; i++) { 
   completionTasks[i] = Task.Run(() => BatchCompletionLoop());
}

static async Task BatchCompletionLoop() {
   while(!token.IsCancellationRequested) {
    var lockTokens = new Guid[100];
      int numberOfItems = lockTokensToComplete.TryPopRange(lockTokens)
      if(numberOfItems > 0) {
         await receiveClient.CompleteBatchAsync(lockTokens).ConfigureAwait(false);
      }
      await Task.Delay(TimeSpan.FromSeconds(5), token).ConfigureAwait(false);
   }
}

Now we’ve just made the contention problem on the concurrent stack even worse. Multiple background completion operations are competing on the concurrent stack as well. Because all those completion tasks would have the same Task.Delay value, there is a high chance we would see a pattern where multiple background completion operations are dispatch on a worker thread but only a few would succeed and idle again, effectively wasting a lot of resources in production.

Leaving contention and resource waste aside we’ve now introduced another major flaw in our completion logic. Can you spot it? If not, don’t worry. I’ll pick it up in the next post.

Multiple message receivers with Azure Service Bus

In the first post of this series we looked at a simple message receive loop. We tried to optimize the receive loop by moving out the message completion into a dedicated background operation. It turns out we can do more to boost the message throughput. Here is how our simple loop looked like

var receiveClient = QueueClient.CreateFromConnectionString(connectionString, queueName, ReceiveMode.PeekLock);
receiveClient.OnMessageAsync(async message =>
{
...
},
..)

We created a queue client with QueueClient.CreateFromConnection. If we carefully read the best practices for improvements using Service Bus Messaging we can see that there are multiple ways of creating queue clients or message receivers. We can also create receivers with a MessagingFactory.

var factory = await MessagingFactory.CreateAsync(address, settings).ConfigureAwait(false);
var receiveClient = await factory.CreateMessageReceiverAsync(queueName, ReceiveMode.PeekLock).ConfigureAwait(false);
receiveClient.OnMessageAsync(async message =>
{
...
},
..)

So far we haven’t achieved much. We’ve just changed the creation of the receiver. But we could now try to create multiple receive clients like the following snippets illustrate.

var factory = await MessagingFactory.CreateAsync(address, settings).ConfigureAwait(false);
var receiver1 = await factory.CreateMessageReceiverAsync(queueName, ReceiveMode.PeekLock).ConfigureAwait(false);
var receiver2 = await factory.CreateMessageReceiverAsync(queueName, ReceiveMode.PeekLock).ConfigureAwait(false);
receiver1.OnMessageAsync(async message => { ... }, ..);
receiver2.OnMessageAsync(async message => { ... }, ..);

To avoid duplication of the message receive loop logic, we would need to move the logic out into a dedicated method.

receiver1.OnMessageAsync(ReceiveMessage, ..);
receiver2.OnMessageAsync(ReceiveMessage, ..);

static async Task ReceiveMessage(BrokeredMessage message) {
   ...
}

Unfortunately, this will not bring us the desired throughput. The performance as mentioned earlier best practice documentation states:

all clients (senders in addition to receivers) that are created by the same factory share one TCP connection. The maximum message throughput is limited by the number of operations that can go through this TCP connection. The throughput that can be obtained with a single factory varies greatly with TCP round-trip times and message size. To obtain higher throughput rates, you should use multiple messaging factories.

So ideally we would need to have a one-to-one relationship between factories and receivers. Let’s apply that to your snippet above.

var factory1 = await MessagingFactory.CreateAsync(address, settings).ConfigureAwait(false);
var factory2 = await MessagingFactory.CreateAsync(address, settings).ConfigureAwait(false);
var receiver1 = await factory1.CreateMessageReceiverAsync(queueName, ReceiveMode.PeekLock).ConfigureAwait(false);
var receiver2 = await factory2.CreateMessageReceiverAsync(queueName, ReceiveMode.PeekLock).ConfigureAwait(false);
receiver1.OnMessageAsync(ReceiveMessage, ..);
receiver2.OnMessageAsync(ReceiveMessage, ..);

With this approach, each receiver is created by a dedicated messaging factory. There is no TCP connection sharing involved anymore, and each receiver has a dedicated connection. The concurrency settings can be applied as desired to each receiver. With this approach, we can have as many factories and receivers as needed and concurrently fetch messages from the same queue on multiple dedicated connections. If we combine this with a wisely chosen PrefetchCount and potentially partitioned queues or topics we can speed up our message, receive loop to race car speed.

How this influences the batch completion will be outlined in the next installment.

Improved batch completion loop for Azure Service Bus

In the last post, we created a dedicated completion loop inside a worker thread to complete messages in batches. There are a few obvious or not so obvious things we can improve in our code. But first, how did it look like again?

// same as before
var batchCompletionTask = Task.Run(async () => {
   while(!token.IsCancellationRequested) {
      var lockTokens = new Guid[100];
      int numberOfItems = lockTokensToComplete.TryPopRange(lockTokens)
      if(numberOfItems > 0) {
         await receiveClient.CompleteBatchAsync(lockTokens).ConfigureAwait(false);
      }
      await Task.Delay(TimeSpan.FromSeconds(5), token).ConfigureAwait(false);
   }
});

We could make a simple assumption: If the numberOfItems returned by TryPopRange is equal the maximum lock token range we want to complete in batches (here one hundred) then we have potentially more things to complete, and we can try to avoid the delay.

// same as before
var batchCompletionTask = Task.Run(async () => {
   while(!token.IsCancellationRequested) {
      // same as before
      if(numberOfItems == lockTokens.Length) {
         continue;
      }
      await Task.Delay(TimeSpan.FromSeconds(5), token).ConfigureAwait(false);
   }
});

So if we were able to fill the lock token array we assume we have more to fetch and continue in the while loop. If the ConcurrentStack happens to be empty after the continuation, we will then end up in the Task.Delay. If there are still lock tokens to fetch, we will continue fetching at least another round. What else could we improve?

We randomly pick a Guid array size of one hundred. An Azure Service Bus request can be up to 256 KB in size. A Guid has a size of 16 bytes. One hundred Guids, therefore would have a size of roughly 1.6 KB. We could easily increase the array size to a much larger number. For example, 5000 Guids would mean a payload size of approximately 80 KB which is roughly a third of the maximum payload size. This seems to be a reasonable trade-off. Of course, you’d need to make your analysis based on your application’s need and your Service Bus tier and data center you are connecting to.

We could also start tweaking the delay interval. Are five seconds too much for faster receiving of messages? Or should we increase the timespan for lighter load? These are all questions that are hard to answer without particular non-functional requirements of your application or system.

We have shed light on message receiving and mostly batch completion outside the receive loop. In the next installment, we will circle back to the message receive loop and see how we can get even more receive performance and how this potentially impacts our completion logic.

 

Another attempt to batch complete with Azure Service Bus

In the last post, we tried to be smart with batch completion and completed every one-hundredth message. Unfortunately, this way of doing completion might not work under with few messages in the queue. We decided to go back to the drawing board and see if we can come up with a better approach which can cope with high but also small loads of messages. The heart of the code we wrote in the last post (omitting the exception handling part) looks like

var lockTokensToComplete = new ConcurrentStack<Guid>();
 
receiveClient.OnMessageAsync(async message =>
{
   // same as before
   await DoSomethingWithTheMessageAsync().ConfigureAwait(false);
   lockTokensToComplete.Push(message.LockToken);
   // same as before
},..)

Instead of completing messages in batches of hundred lock tokens we can try to move out the batch completion into a dedicated batch completion task. Hopefully that is not too hard. Let’s see

var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;

var batchCompletionTask = Task.Run(async () => {
   while(!token.IsCancellationRequested) {
      var lockTokens = new Guid[100];
      int numberOfItems = lockTokensToComplete.TryPopRange(lockTokens)
      if(numberOfItems > 0) {
         await receiveClient.CompleteBatchAsync(lockTokens).ConfigureAwait(false);
      }
      await Task.Delay(TimeSpan.FromSeconds(5), token).ConfigureAwait(false);
   }
});

We schedule a task to be run on the worker thread pool to offload the actual completion loop away from the thread that is starting the task. We loop until the cancellation is requested on the cancellation token source which is linked to the token passed as closure into the completion loop. We then try top pop a range of lock tokens from the ConcurrentStack. If we received more than zero items, we would complete the lock tokens we popped on the receiveClient. At the end of the loop, we asynchronously sleep until either we shut down or five seconds are over.

This is beautiful and straightforward. We have a dedicated completion circuit, the contention on the concurrent stack is in a controllable range. Under small load, we complete lock tokens in in batches of one to maximum one hundred tokens. If we receive only a limited number of messages, the loop might complete messages with their tokens one by one (for example when we receive a message every 6 seconds). But what happens when the load increases?

When we’d received several hundred messages per seconds our randomly chosen “complete every one-hundredth messages” and then “sleep for five seconds” might turn out to be a suboptimal choice. We will dive more into this topic in upcoming posts. Could we try to optimize a few things in this simple loop? Feel free to exercise your brain or just wait for the next post 😉

 

Let’s try batch completion of messages on Azure Service Bus

In the last post, we deferred the message completion task into the background to remove the additional latency from the message receive callback. This time we want to save even more latency by batching multiple message completions together into a single Azure Service Bus broker call. It turns out this is possible with the Azure SDK.

The MessageReceiver has a method called CompleteBatchAsync which accepts an IEnumerable<Guid> called lockTokens. But where do we get these lock tokens from? It turns out the BrokeredMessage type that is passed into the OnMessageAsync callback contains a GUID property called LockToken. The lock token is a GUID generated by the service bus which uniquely identifies a message on the broker. So if we managed to track the lock tokens for the messages, we receive we can at a later stage execute CompleteBatchAsync. Let’s see how this would change our message receive logic.

var lockTokensToComplete = new ConcurrentStack<Guid>();
 
receiveClient.OnMessageAsync(async message =>
{
   try {
      await DoSomethingWithTheMessageAsync().ConfigureAwait(false);
      lockTokensToComplete.Push(message.LockToken);
   catch(Exception) {
      // in case of an exception make it available again immediately
      await message.AbandonAsync().ConfigureAwait(false);
   }
},..)

With this small change, we would be pushing lock tokens of messages to be completed into a ConcurrentStack. Only if a message fails we’d be directly abandoning the message asynchronously inside the message receive callback. The assumption / we are making here is that the contention on the ConcurrentStack will be far less than the latency on the remote call to complete a message. But at some point, we have to complete the messages.Can we do it directly in the callback like illustrated with the following code?


receiveClient.OnMessageAsync(async message =>
{
   // same as before
   var lockTokens = new Guid[100];
   if(lockTokensToComplete.Count > 100 && lockTokensToComplete.TryPopRange(lockTokens) > 0) {
      await receiveClient.CompleteBatchAsync(lockTokens).ConfigureAwait(false);
   }
   // same as before
},..)

We’ve chosen a concurrent stack here in order to be able to do range pops of lock tokens. This might seem a bit strange since we’d we completing messages with the lock token in another order than we received it. Normally that is not a big deal since in concurrency scenarios we should not make any assumptions about ordering.

With a lot of messages in the queue, and when the queue constantly has a particular load of messages coming in, this code would improve the latency. We would only do a remote call every hundred messages. So we theoretically save 99% of the latency we’d have when completing every message. What a success! But wait, there is a problem in this code: What if we only receive one message every ten seconds?

Assuming a peek lock duration of roughly thirty seconds, we would almost always run into the expiration of the peek lock duration and therefore the messages would be processed over and over again until they’d get dead lettered by the Azure Service Bus. That’s some bad hat harry!

So how can we make this trouble maker better? Well, I think you know it already: That’s a topic for another post.

Defer message completion on Azure Service Bus

In the last post, we started sketching code around the idea of deferring the actual message completion out of the message receive callback. A simple way to achieve our goals would be to kick off the completion task without await it like the following code shows

receiveClient.OnMessageAsync(async message =>
{
   try {
      await DoSomethingWithTheMessageAsync().ConfigureAwait(false);
      message.CompleteAsync();
   catch(Exception) {
      // in case of an exception make it available again immediately
      await message.AbandonAsync().ConfigureAwait(false);
   }
},..)

This is inelegant in multiple ways. Since the code is contained in a delegate which is marked as async, the compiler would warn us with CS4014 that the call is not awaited. Of course, we could work around that by suppressing the compiler warning or by writing an empty extension method which “consumes the task returned” *1. With this approach, the message completion would become a fire & forget operation.

The fire & forget nature of this approach imposes yet another problem. We don’t know what the outcome of the operation is. The operation might fail for various reasons like when there is a connection interruption to the broker or when the client is shutting down, and the receiver is closed. Furthermore, when we’d like to shut down in a clean way, we could have up to 100 concurrent message completions (remember MaxConcurrentCall was set to 100) which we might want to await to complete or fail. We could track the tasks somehow like the following:

var runningTasks = new ConcurrentDictionary<Task, Task>();

receiveClient.OnMessageAsync(async message =>
{
   try {
      await DoSomethingWithTheMessageAsync().ConfigureAwait(false);
      var completionTask = message.CompleteAsync();
      runningTasks.TryAdd(completionTask, completionTask);
      completionTask.ContinueWith(t => { 
         Task toBeRemoved;
         runningTasks.TryRemove(t, out toBeRemoved);
      }, TaskContinuationOptions.ExecuteSynchronously)).Ignore();
   catch(Exception) {
      // in case of an exception make it available again immediately
      await message.AbandonAsync().ConfigureAwait(false);
   }
},..)

In the above sample code, we use a ConcurrentDictionary to track the tasks. The trick here is that we rely on the Task object having a proper object identity. We use a dictionary since we want to remove a specific Task which completed. *2 We add the completion task to the runningTasks dictionary. After that, we schedule a continuation which removes the completed task from the dictionary for a proper housekeeping. The continuation is scheduled to be executed synchronously for efficiency reasons.

When we shutdown we first close the receive client to no longer pump messages to us and then we await all pending runningTasks until they completed or failed. *3

public async Task Stop() {
   await receiveClient.CloseAsync().ConfigureAwait(false);
   await Task.WhenAll(runningTasks.Values).ConfigureAwait(false);
   runningTasks.Clear();
}

By using the fire & forget approach we were able to defer the completion of the message into the background and out of the receive loop. We were able to achieve our goals to remove the latency of the completion call from the actual message receive. We are still completing messages one by one which means each completion is still a remote call. Can we do even better? Yes we can by leveraging batch completion capabilities of the Azure SDK. But that is a topic for the next post!
*1

public static class TaskExtensions {
    public static void Ignore(this Task task) { // intentionally ignored }
}

*2 Since we know the maximum number of concurrent requests we could also preallocate an array of Tasks, keep track of them with an index which is incremented in a thread safe way and kept inside the boundaries of the array as well as passing that current index to the delegate which is scheduled as a continuation of the completion task (exercise left to the readers of this post 😉 ).

*3 This solution would indefinitely hang when one of the running tasks hangs, feel free to improve the code (again an exercise left to the readers 😉 ).

Latency to Azure Service Bus matters

In the last post, we optimized the throughput on the client by increasing the concurrency of the message receive loop. What else could we try to improve? Let’s have a closer look at the lambda body of the OnMessageAsync declaration.

receiveClient.OnMessageAsync(async message =>
{
   // do something with the message
   await message.CompleteAsync().ConfigureAwait(false);
},..)

As we can see, we have technically two operations inside the callback delegate. The first operation is the code we want to execute when a message is pushed to us (here represented with comment). The second operation is the completion or abandon of the message we received depending on the outcome of the business logic.

For the business logic, there is an important aspect we need to take into consideration. If the business logic happens to call into I/O bound resources the whole call stack of the business logic on the I/o bound path needs to be asynchronous and return a Task or Task<T>.

receiveClient.OnMessageAsync(async message =>
{
   await DoSomethingWithTheMessageAsync().ConfigureAwait(false);
   await message.CompleteAsync().ConfigureAwait(false);
},..)

This makes the callback delegate fully asynchronous and therefore allows to more efficiently use the resources provided by the Azure SDK since we are never blocking on the I/O bound path. Naturally, we would also make sure that the implementation of DoSomethingWithTheMessageAsync is as efficient as possible (for example following best-practices of async ADO.NET calls when we call into a SQL Azure Database and more).

Could we save more? How about the second operation? Can we just leave it out? Not really, since if we would leave it out the message would not be completed and therefore always reappear after the PeekLock duration is over. So we’d be processing the same Thanksgiving order over and over again. So at some point in time, we need to complete the message. But what if we could complete it at a later stage? It turns out we can by making a few trade-offs:

receiveClient.OnMessageAsync(async message =>
{
   try {
      await DoSomethingWithTheMessageAsync().ConfigureAwait(false);
      // omit the completion of the message
   catch(Exception) {
      // in case of an exception make it available again immediately
      await message.AbandonAsync().ConfigureAwait(false);
   }
},..)

By assuming exceptions are like the name suggests “exceptional” we abandoned immediately when an exception occurred in our message processing logic to make the message directly accessible again without needing to wait for the PeekLock duration to expire. For the good case, we omit the completion of the BrokeredMessage and delay the completion slightly.

Why is that useful? The CompleteAsync operation on the brokered message calls to the Azure Service Bus. So essentially it is a remote call which can take up a few dozens of milliseconds depending on the latency of the datacenter you’re connecting to. While I’m writing this post, the latency from my computer to Azure is roughly 40-50 ms (usually it averages between 20-30 ms)*. By omitting the complete call, we save per message receive 40 ms in my example. Saving 40 ms per message with a load of 120K messages means we save 4.8 Million Milliseconds (4800 seconds) on the entire batch of messages.

By not hammering Azure Service Bus for each message received we gain more throughput because the overall execution time of the actual message received is reduced. So instead of bobby car speed we are probably now at rusty old car speed.

But hey, I’m totally cheating now! Since at some point in time, we need to complete the messages not to let them reappear. We also should make sure we complete the messages in the time of a PeekLock duration of a received message. But that is a topic for another post!

* Of course by placing your application into the data center the latency would decrease. But there will always be latency. Remember the speed of light is a constant ;)?

Let’s save our Thanksgiving sales with Azure Service Bus

As we saw in the last post, naive receiving of messages with Azure Service Bus destroys our Thanksgiving sales. But how can we do better to satisfy our bosses and first and foremost our precious customers? As Sean Feldman rightfully pointed out in the comments section, our sample was using MaxConcurrentCalls set to one.

How silly! Who wrote that… Oh, it was me 😉

So how about we correct my mistake and set to 100 to like the following

receiveClient.OnMessageAsync(async message => {...},
new OnMessageOptions { AutoComplete = false, MaxConcurrentCalls = 100 })

With this tiny change, we can suddenly receive 100 messages concurrently as well as complete and abandon (if necessary) them concurrently. Let’s do the math again. Our 120 K orders we received ca now be processed in 20 minutes instead of 33 hours. On a lucky Thanksgiving rush, we’d be able to process the 1.2 million orders we received in about 200 minutes or 3 hours and 20 minutes. That is a significant improvement for such a tiny change!

The hard part is to pick a decent concurrency number. From an Azure SDK perspective setting the MaxConcurrentCalls to a higher number doesn’t necessarily mean the SDK will use a significant amount of more resources like Threads. Internally the SDK is almost completely asynchronous using the old APM style. The concurrency is limited by using an asynchronous semaphore* which is acquired before each asynchronous receive and released as soon as the callback delegate is executed (that is a bit of a simplification but let’s stick to that analogy). So potentially we could set it to a much higher number.

But it depends on what we are executing inside the callback delegate. For example, if we’d be executing operations against a database like SQL Azure for argument’s sake we’d be needing dedicated connections for each concurrent access to the database. SqlConnections are pooled, and by default the pool, size is set to 100. So if we’d set the concurrency to a higher number, we would eventually be exhausting the connection pool, and the throughput would suffer significantly. So let’s stick for now with 100 for MaxConcurrentCalls.

We went from Snail orders to orders that are processed at least as fast as my son can drive his bobby car. So I think your Thanksgiving sales is almost saved and we can enjoy our turkey. Or can we do even better? Of course, we can! But that is a topic for another post.

 

* A semaphore is like a nightclub: it has a certain capacity, enforced by a bouncer. Once it’s full, no more people can enter, and a queue builds up outside. Then, for each person that leaves, one person enters from the head of the queue. […] Albahari