Azure Service Bus .NET SDK Deep Dive – Connections

Explains connections and how they relate to senders and receivers, for more posts in this series go to Contents.

So far, we’ve been creating a ServiceBusClient to create senders and receivers. The below code illustrates a small example that sends a message to a destination and then receives a single message from that destination.

 await using var serviceBusClient = 
   new ServiceBusClient(connectionString);
 await using var connectionSharingSender = serviceBusClient
 await connectionSharingSender
   .SendMessageAsync(new ServiceBusMessage("Deep Dive"));
 await using var connectionSharingReceiver = serviceBusClient
 await connectionSharingReceiver.ReceiveMessageAsync(); 

The common thing that we’ve seen in the samples so far as well as in the code above is that we are the same ServiceBusClient to create senders and receivers. Let’s explore what happens under the hood with netstat while the above sample code is running:

netstat -na | find "5671"

Only the existing already established connection is used, and we can create senders and receivers without paying the overhead of re-initiating the connection all the time. But what if we want to have a dedicated connection for the sender and one for the receiver to improve the throughput?

 await using var senderServiceBusClient = 
   new ServiceBusClient(connectionString);
 await using var receiverServiceBusClient = 
   new ServiceBusClient(connectionString);
 await using var senderWithDedicatedConnection = 
 await using var receiverWithDedicatedConnection = 
 await senderWithDedicatedConnection
   .SendMessageAsync(new ServiceBusMessage("Deep Dive"));
 await receiverWithDedicatedConnection.ReceiveMessageAsync(); 

Let’s consult our good old netstat while the above code is running:

netstat -na | find "5671"

Now two dedicated connections are established and the sender and receiver are separated using their TCP connection. Before you jump too early conclusions and think you are going to use the connection sharing approach or always create multiple connections, I suggest you carefully think about usage patterns you are anticipating. Measure it with a realistic load, which makes the most sense for your application or system and then choose the approach which is best for your scenario.

Updated: 2021-03-23 to use the new SDK

About the author

Daniel Marbach

1 comment

By Daniel Marbach

Recent Posts