.Net Core API - Azure Service Bus Performance

Getting messages quickly on to the bus…

I recently added Azure Service Bus to one of my API to improve performance and reliability, as well as helping with decoupling. The API receives messages and adds them to an Azure Service Bus Queue. Another process then picks the messages up from the queue, processes them and persists them to a SQL database.

When I first added the message to the Service Bus I found it was slower than adding the messages to the SQL database directly. I found that the slow part was the setup of the Queue Client and I was doing this every time a new message was received by the API. The better way was to create this once in the constructor. After this the performance was what I expected and messages were added to the queue in around 15ms.

Here’s how to add message to an Azure Service Bus queue from an .Net Core API.

Add the following NuGet packages:

  • Microsoft.Azure.ServiceBus
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
	const string serviceBusConnectionString = ".....";
	const string serviceBusQueueName = "messagesin";
	static IQueueClient queueClient;
	
	public ValuesController()
	{
		if (queueClient == null)
		{
			queueClient = new QueueClient(serviceBusConnectionString,
			serviceBusQueueName);
		}
	}

	[HttpPost, Consumes("application/x-www-form-urlencoded")]
	public async Task<IActionResult> Post([FromForm] MessageInDTO messageInDTO)
	{
		string json = JsonConvert.SerializeObject(messageInDTO);
		
		var message = new Message(Encoding.UTF8.GetBytes(json));
		
		await queueClient.SendAsync(message);
		
		return Ok();
	}
}

Service Bus Explorer

I found a great tool called Service Bus Explorer to manage and see what messages are in my queues:

I used Chocolatey to install it.

I haven’t used Chocolatey much before and I struggled to see where it had put it but eventually found it at: C:\ProgramData\chocolatey\lib\ServiceBusExplorer\tools

Alex Orpwood Written by:

Software developing and architecting for 20 years. Satellite monitoring by day, writing my own app by night. More about me