title: How to Determine Azure ServiceBus PrefetchCount and ReceiveBatch Size
body: <p>I have a queue processor that is retrieving all messages from a ServiceBus Queue. I am wondering how I should determine the MessageReceiver <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.servicebus.queueclient.prefetchcount?view=azure-dotnet" rel="nofollow noreferrer">PrefetchCount</a> and the ReceiveBatch <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.servicebus.messaging.messagereceiver.receivebatchasync?view=azure-dotnet" rel="nofollow noreferrer">messageCount</a> to optimize performance. I am currently setting these to the arbitrary number 500, as seen below:</p>
  
  <pre><code>var receiverFactory = MessagingFactory.CreateFromConnectionString("ConnectionString");
  var receiver = await receiverFactory.CreateMessageReceiverAsync("QueueName", ReceiveMode.PeekLock);
  receiver.PrefetchCount = 500;
  
  bool loopBatch = true;
  while (loopBatch) 
  {
      var tempMessages = await receiver.ReceiveBatchAsync(500, TimeSpan.FromSeconds(1));
      // Do some message processing...
      loopBatch = tempMessages.Any();
  }
  </code></pre>
  
  <p>When running, I see that my batches often take time to "warm up," retrieving counts such as "1, 1, 1, 1, 1, 1, 1, 1, 125, 125, 125, 125..." where the batch retrieval number suddenly jumps much higher.</p>
  
  <p>From the <a href="https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-performance-improvements#prefetching" rel="nofollow noreferrer">Prefetching optimization</a> docs:</p>
  
  <blockquote>
    <p>When using the default lock expiration of 60 seconds, a good value for SubscriptionClient.PrefetchCount is 20 times the maximum processing rates of all receivers of the factory. For example, a factory creates 3 receivers, and each receiver can process up to 10 messages per second. The prefetch count should not exceed 20 X 3 X 10 = 600. By default, QueueClient.PrefetchCount is set to 0, which means that no additional messages are fetched from the service.</p>
  </blockquote>
  
  <p>I don't really understand how to determine the receiver's "messages per second" when the batch retrieval seems to retrieve widely-varying numbers of messages at a time. Any assistance would be greatly appreciated.</p>