Skip to main content

Active/Passive Mechanism over Azure Service Bus

A messaging system like Azure Service Bus is great for scenarios when you need to have a reliable communication channel between different components.
There are cases when even the SLA offered by a cloud provider it is not enough. For example in the case of Azure Service Bus is 99.9% uptime. In this scenarios we need a failover mechanism that will offer us better reliability.
Imagine a system where Service Bus Queue is used to transmit commands from backend to cars. The backend can order to the car to open/close doors or to start the engine. In this scenarios you cannot be out of order for 1h or 2h because the client will not be very happy. You don't want to stay in the front of the car for 2h until the doors will open.

What should we do in this cases?
A solution to this problem is to look at a failover mechanism like Active-Active or Active-Passive. In this post we will talk about Active-Passive and tomorrow we will talk about the Active-Active.

An Active-Passive solution it is based on duplication of a service, having two instances of that service available for the same job. The main channel that it is used for communication is the Active channel. In the moment when Active channel goes down, the secondary channel (Passive) will be used immediately to send or receive messages. The Passive channel will be used until in the moment when the Active one will be available once again.

If we take Active-Passive mechanism and apply on Service Bus Queue we will end up with the following flow:

  1. If the Active Service Bus Queue is available
    1. Use the Active one for Sending and Receiving messages
    2. Check from time to time the Passive one to see if there are some messages there also
  2. If the Active Service Bus Queue is not available 
    1. Use the Passive one for Sending and Receiving messages
    2. Check the Active one from time to time to check if is available again
      1. If the Active one is available again
        1. Switch to the Active one

There are two steps that are very important in this flow and can make the system reliable and in the same time very simple.

  1. Even when the Active channel is up and running, we check the Passive channel from time to time. This is an important step to not lose messages. Even if we detect that the Active channel is up and running, the other system (at the other end of the wire) could detect that the channel is down – because of this he could start to send content on the Passive channel. 
  2. Switching between Active to Passive is only a temporary action and we need constantly to check the Active channel to see if it up and running again. This needs to be done because it is impossible for the system to know what channel (Active or Passive) it used by the other system.

The good part on the SDK of Azure Service Bus is that we can need to specify the time interval when a check is made to see if new content is available on the Queue (pooling time interval). If content is available under this time interval than another check for new content will be made immediately.

With Active-Passive approach if we have messages on the Active channel we risk to lose them when Active goes down OR to receive them when is to late. If this is acceptable from our business requirements that we should use Active-Passive approach.
In this post we will not discuss abouts costs and how are costs affected using Active-Passive mechanism. We will talk with another occasion abouts costs and what we should take into account.

A part of the code for Active/Passive can be found below - only the receiver part is covered. When Active is down, the Passive one is used as the 'primary' one. The timer will check if the Active is back again.
public interface IServiceBusListener<out TInput, TMessageType>
   void OnMessageAsync(Func<TMessageType, Task> actionMethod, Converter<TInput, TMessageType> converter);
   void OnMessageError(Action<Exception> action);
   Task CloseAsync();

public class ActivePassiveServiceBusListener<TInput, TMessageType, TListener> 
               TListener : IServiceBusListener<TInput, TMessageType>
   protected readonly TListener PrimaryChannel;
   protected readonly TListener SecondaryChannel;        

   private Action<Exception> onMessageError;
   private Timer checkPrimary;
   private readonly int primaryCheckingIntervalInSeconds;
   private readonly int secondaryCheckingIntervalInSeconds;

   public ActivePassiveServiceBusListener(TListener primaryChannel, TListener secondaryChannel)
       PrimaryChannel = primaryChannel;
       SecondaryChannel = secondaryChannel;

       primaryCheckingIntervalInSeconds = 1;
       secondaryCheckingIntervalInSeconds = 10;

   public void OnMessageAsync(Func<TMessageType, Task> actionMethod, Converter<TInput, TMessageType> converter)
       PrimaryChannel.OnMessageAsync(actionMethod, converter);
       SecondaryChannel.OnMessageAsync(actionMethod, converter);


   public void OnMessageError(Action<Exception> action)
       onMessageError = action;

   protected void SecondaryChannelOnMessageError(Exception e)
       if (onMessageError != null)

   protected void PrimaryChannelOnMessageError(Exception e)
       if (checkPrimary != null)


           checkPrimary = new Timer(async state =>

                   await ResetTCheckTimesToNormal();
                   checkPrimary = null;
               catch (Exception)
                   checkPrimary.Change(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(secondaryCheckingIntervalInSeconds));

           checkPrimary.Change(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(secondaryCheckingIntervalInSeconds));
       catch (Exception ex)

   private async Task ResetTCheckTimesToNormal()
       await PrimaryChannel.SetTimeoutInterval(primaryCheckingIntervalInSeconds);
       await SecondaryChannel.SetTimeoutInterval(secondaryCheckingIntervalInSeconds);

   public override async Task CloseAsync()
       await PrimaryChannel.CloseAsync();
       await SecondaryChannel.CloseAsync();


Popular posts from this blog

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine:
threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration:

TeamCity.NET 4.51EF 6.0.2VS2013
It seems that there …

Entity Framework (EF) TransactionScope vs Database.BeginTransaction

In today blog post we will talk a little about a new feature that is available on EF6+ related to Transactions.
Until now, when we had to use transaction we used ‘TransactionScope’. It works great and I would say that is something that is now in our blood.
using (var scope = new TransactionScope(TransactionScopeOption.Required)) { using (SqlConnection conn = new SqlConnection("...")) { conn.Open(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = conn; sqlCommand.CommandText = ... sqlCommand.ExecuteNonQuery(); ... } scope.Complete(); } Starting with EF6.0 we have a new way to work with transactions. The new approach is based on Database.BeginTransaction(), Database.Rollback(), Database.Commit(). Yes, no more TransactionScope.
In the followi…

GET call of REST API that contains '/'-slash character in the value of a parameter

Let’s assume that we have the following scenario: I have a public HTTP endpoint and I need to post some content using GET command. One of the parameters contains special characters like “\” and “/”. If the endpoint is an ApiController than you may have problems if you encode the parameter using the http encoder.
using (var httpClient = new HttpClient()) { httpClient.BaseAddress = baseUrl; Task<HttpResponseMessage> response = httpClient.GetAsync(string.Format("api/foo/{0}", "qwert/qwerqwer"))); response.Wait(); response.Result.EnsureSuccessStatusCode(); } One possible solution would be to encode the query parameter using UrlTokenEncode method of HttpServerUtility class and GetBytes method ofUTF8. In this way you would get the array of bytes of the parameter and encode them as a url token.
The following code show to you how you could write the encode and decode methods.