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

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(

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.51 EF 6.0.2 VS2013 It see

Navigating Cloud Strategy after Azure Central US Region Outage

 Looking back, July 19, 2024, was challenging for customers using Microsoft Azure or Windows machines. Two major outages affected customers using CrowdStrike Falcon or Microsoft Azure computation resources in the Central US. These two outages affected many people and put many businesses on pause for a few hours or even days. The overlap of these two issues was a nightmare for travellers. In addition to blue screens in the airport terminals, they could not get additional information from the airport website, airline personnel, or the support line because they were affected by the outage in the Central US region or the CrowdStrike outage.   But what happened in reality? A faulty CrowdStrike update affected Windows computers globally, from airports and healthcare to small businesses, affecting over 8.5m computers. Even if the Falson Sensor software defect was identified and a fix deployed shortly after, the recovery took longer. In parallel with CrowdStrike, Microsoft provided a too