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> 
           where 
               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);

       PrimaryChannel.OnMessageError(PrimaryChannelOnMessageError);
       SecondaryChannel.OnMessageError(SecondaryChannelOnMessageError);
   }

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

   protected void SecondaryChannelOnMessageError(Exception e)
   {
       if (onMessageError != null)
       {
           onMessageError.Invoke(e);
       }
   }

   protected void PrimaryChannelOnMessageError(Exception e)
   {
       if (checkPrimary != null)
       {
           return;
       }

       try
       {
           SecondaryChannel.SetTimeoutInterval(primaryCheckingIntervalInSeconds).Wait();
           PrimaryChannel.SetTimeoutInterval(secondaryCheckingIntervalInSeconds).Wait();

           checkPrimary = new Timer(async state =>
           {

               try
               {
                   await ResetTCheckTimesToNormal();
                   checkPrimary.Dispose();
                   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();
   }
}

Comments

Popular posts from this blog

How to check in AngularJS if a service was register or not

There are cases when you need to check in a service or a controller was register in AngularJS.
For example a valid use case is when you have the same implementation running on multiple application. In this case, you may want to intercept the HTTP provider and add a custom step there. This step don’t needs to run on all the application, only in the one where the service exist and register.
A solution for this case would be to have a flag in the configuration that specify this. In the core you would have an IF that would check the value of this flag.
Another solution is to check if a specific service was register in AngularJS or not. If the service was register that you would execute your own logic.
To check if a service was register or not in AngularJS container you need to call the ‘has’ method of ‘inhector’. It will return TRUE if the service was register.
if ($injector.has('httpInterceptorService')) { $httpProvider.interceptors.push('httpInterceptorService&#…

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 http://go.microsoft.com/fwlink/?LinkId=260882 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 …

[Post-Event] Codecamp Conference Cluj-Napoca - Nov 19, 2016

Last day I was invited to another Codecamp Conference, that took place in Cluj-Napoca. Like other Codecamp Conferences, the event was very big, with more than 1.000 participants and 70 sessions. There were 10 tracks in parallel, so it was pretty hard to decide at  what session you want to join.
It was great to join this conference and I hope that you discovered something new during the conference.
At this event I talked about Azure IoT Hub and how we can use it to connect devices from the field. I had a lot of demos using Raspberry PI 3 and Simplelink SensorTag. Most of the samples were written in C++ and Node.JS and people were impressed that even if we are using Microsoft technologies, we are not limited to C# and .NET. World and Microsoft are changing so fast. Just looking and Azure IoT Hub and new features that were launched and I'm pressed (Jobs, Methods, Device Twin).
On backend my demos covered Stream Analytics, Event Hub, Azure Object Storage and DocumentDB.

Title:
What abo…