Search code examples
c#azureazureservicebus

Service Bus Multiple Namespace Failover Round Robin


I was wondering if there was a built in mechanism within the service bus client or a libary that supports a round robin approach to send or publish messages? What I mean by this is, if:

  • I had two namespaces EUN and EUW (standard tier)
  • I don't want to send messages to both but rather attempt first one (EUN), if it fails then attempt second namespace (EUW)

Pairing namespaces is not an option unfortunately as not using premium tier. The way I have handled this so far is to attempt EUN wrapping a try catch around it then attempt EUW. Its a little more elegant than that but in a nutshell its what I am doing.


Solution

  • There is no built-in mechanism in the Azure Service Bus client or library that supports a round-robin approach to send or publish messages.

    You can implement a custom solution by wrapping a try-catch block around the first namespace (EUN) and attempting to send the message to the second namespace (EUW) if the first attempt fails.

    You can also use the file share-based failover configuration "Message replication task patterns - Azure Service Bus" <Reference 1> to share endpoint information.

    And you can put the name of the primary endpoint into a plain-text file and serve the file from an infrastructure that is robust against outages and still allows updates.

    Sample Code

     static void Main(string[] args)
            {
                string primaryNamespace = "Test1Namespace1";
                string secondaryNamespace = "Test2Namespace2";
    
                try
                {
                    SendMessage(primaryNamespace).Wait();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Sending message to primary namespace failed. Exception: " + ex.Message);
                    Console.WriteLine("Trying to send message to secondary namespace...");
                    SendMessage(secondaryNamespace).Wait();
                }
            }
    
            private static async Task SendMessage(string namespaceName)
            {
                var connectionString = $"Endpoint=sb://namespace.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=";
                var queueClient = new QueueClient(connectionString, "testqueue");
    
                var message = new Message(Encoding.UTF8.GetBytes("Test message"));
                await queueClient.SendAsync(message);
    
                Console.WriteLine("Message sent successfully.");
            }
    

    Message to Queue

    enter image description here

    Messages sent to Queue in Azure portal.

    enter image description here

    For further information, refer to the MSDoc.