Singleton Design Patterns

Before discussing singleton design pattern let me give you some basic background of design pattern and its history

The idea of design pattern was picked by four authors: Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm, very well known by the Gang of Four where they applied a concept of typical programming. They came up with 23 design pattern for solving various real-life problems of object-oriented design.

A design pattern is one kind of recipes book to deliver delicious and tasty programming dishes ūüėČ A Design pattern act as a template which can be applied to the real world problem

Writing a code using design pattern makes your code more reliable, scalable and maintainable

There are 3 type of design pattern

  • Creational
  • Structural
  • Behavioral

Creational: This design pattern gives you the functionality of object creation and initialization based on different cases. most popular creational design pattern are Factory, Singleton

Structural: This type of design pattern is responsible for building simple and efficient class hierarchies and a relation between different classes. for example Adapter, bridge

Behavioural: This design pattern deals with communication between classes and objects. for example Chain of Responsibility, Command, Interpreter etc

Singleton Design Pattern

Singleton design pattern is a creational design pattern which let you ensure that only single object is created for a particular class. All further references to the class are referred to this object.

Now, you think then what is different between static and singleton. the main difference between those two is singleton provide you object whereas static classes provide you with a static method. Singleton can implements interfaces, inherit from other classes and it is aligned with the object-oriented concept. Also, a singleton object can be passed to other methods as a reference whereas a static object cannot be passed as a reference.

For implementing singleton pattern to your code you must consider two common steps

  1. Making default constructor as a private so that it cannot be instantiated outside of the class.
  2. Create public creator method, which will create an object using a private constructor and save it on a static variable. so whenever any user requested for the object using public creator method it will return cached object from a static variable.

Top level view of a singleton design pattern class diagram


Following is sample code which ensures you only one object of the class is created and provide you access to that object using GetInstance() method.

public class Singleton {
        /// <summary>
        /// Static field to stored instance of the singleton class
        /// </summary>
        private static Singleton _instance;

         /// <summary>
         /// Private construct to restrict user to instance outside the class
         /// </summary>
         private Singleton() { }

         /// <summary>
         /// GetInstance method which create new instance if its null, and return instance  
         /// </summary>
         public static Singleton GetInstance => _instance ?? (_instance = new Singleton());

Following are some of the example of a real-world scenario where we can use singleton design pattern

  • Logging management
  • Device management
  • File management
  • Application configuration management
  • Cache management
  • Session-based shopping cart management

I have implemented a small project which demonstrates how we can use the singleton pattern for Logging to file or to external resources. find below git repository link for this.

Github: Singleton Pattern Example

Circuit Breaker Design Pattern

Most of the enterprise application uses external services to make an external operation like sending Email or SMS to send notification or external API, external resources to add functionality to our application. Whenever we are making a call to those external services, there may be a chance that those services are down. Our application should be prepared to handle that kind of scenario. We can handle this kind of scenario using retry pattern but retry pattern assumes that external service is available and continues to make a request

The circuit breaker pattern has different than a retry pattern. The circuit breaker prevents an application to perform an external services call that is likely to fail.

This pattern has three operation state:

  • Close state
  • Open state
  • Half Open state

Close State: Operation are executed as usual (whenever we are making the first call to the external services at the time it will be in the closed state)

  • ¬†If a call to external service fails:¬†The failure count is incremented and an¬†OperationFailedException¬†is thrown. If the failure count exceeds the threshold, the circuit breaker trips into the ‚Äúopen‚ÄĚ state.
  • If a call to external service succeeds:¬†if calls succeed¬†before the threshold is reached, the failure counter is reset and operation are executed as usual

Open state: whenever circuit breaker is in open state all calls to the external services will fail and In this state, it will not make an actual call to the external services instead of it will throw an exception OpenStateException. A timeout is started when the circuit breaker trips.

Once the timeout is reached, the circuit breaker enter into the half state

Half state: In “half state” circuit breaker allows one operation to execute.

  • ¬†If a call to external service fails:¬†the circuit breaker re-enter into open state and timeout is reset.
  • If a call to external service succeeds:¬†circuit broker enters into close state and operations are executed as usual


Below sample code will be used to implement circuit breaker with Polly. Here we are creating the Polly handler for circuit breaker when WebException occurred during an external call. This policy will break the circuit with two consecutive exceptions of WebExcption type and the circuit will remain a broker

//creating policy object for handle webexception using circuit breaker
Policy policy = Policy.Handle() 
    exceptionsAllowedBeforeBreaking: 2, 
    durationOfBreak: TimeSpan.FromMinutes(1) );

//To Excute external service call

For a better understanding of the circuit breaker using Polly, you can check it out on below link

I have also created sample repo in GitHub to provide you a basic understanding to implement circuit breaker with Polly nuget package. GitHub demo-application-circuit-breaker

Secure your API with API key and HMAC authentication


This article provide you basic information about API Key and HMAC authentication and how we can implement API Key and HMAC authentication into our Web API

What is HMAC Authentication?

HMAC is message authentication code which is generated using a hash function in combination with shared secret key (API Key) and public Key (APP Id).

A server will first time provide APP Id (shared public key) and API key (shared secret key) to a consumer at the time of registration, Client will generate HMAC using APP Id and API key and then the consumer sends that HMAC to a server in the request header. At the server, side server will regenerate HMAC using same APP Id and API key, once the hash generates server will respond to compare hash sent by the client along with regenerated HMAC, If they match then server consider the request as authenticated and process further.


How to create HMAC and send an authorization header to API server?

Consumer needs to generate string by combining APP ID, HTTP Method, request URI, request timestamp, nonce and base 64 string which contains request payload then client will hash this large string using hashing algorithm (SHA256) using shared secret key (API Key), which will create unique hash signature for the request.

The signature will be sent via Authorization header using custom schema. Following is an example of a custom schema.

[Authorization: xyz APPId:Signature:Nonce:Timestamp]

APPID: Public key which shared with consumer

Signature: Hashed string using hashing algorithm (SHA256)

Nonce: It is arbitrary number or string

Timestamp: Number of seconds since 1st Jan 1970 (UNIX time)

Once the server receives a request from the client, it will regenerate HMAC and compare it with authorization header HMAC, if they are equal then the server will consider this call as an authenticated and process the request.

There are some more benefits of having API Key which is explained below

API key is a unique value which is assigned to API consumer. A consumer will use API key whenever they make an API call. A server will provide shared private secret (API Key), the consumer needs to store the API key securely and never shared it with other parties.

API key is a new way of authorizing users. API key uses secret token which will send with a request to authorize API request call.


API consumer needs to pass API Key in a request and API server will validate API key to allow grant access to resources.

API key restricts access to API methods or all methods to a particular group of people. API key doesn’t use to identify users, it mostly uses for identifying a group of people or company. Most of the company now a day uses API key by selling their API and then tracking who’s using the thing for billing purposes.

API key also uses to filter the log and to find out usage pattern in your API traffic.

You can differentiate API key by public or private. You can share public API key to other to allow them to get limited information about your API whereas private key is about your use only.


SQL Server Service Broker

Service Broker is a process of sending and receiving asynchronous messages by using T-SQL commands.

It’s similar to other queuing technologies. Messages can be sent to a queue in the same database as the sender, to another database in the same SQL Server instance, or to another SQL Server instance either on the same server or on a remote server.

Data is usually sent as an XML data and you can also encrypt your message during transmission

As per my point of view Service broker can use to achieve following functionality

  1. Asynchronous process
  2. Decoupling execution from caller
  3. Distributed Server-Side Processing

Asynchronous provide you event-driven model. Asynchronous processes do not depend on other process. Its work independently on different threads simultaneously.

Decoupled execution allows components to remain completely autonomous, unaware of each other and process by itself.

Large application use multiple SQL Server to manage client application, Service broker can be used to communicate and pass data between those multiple SQL Server

Real world example where you can use SQL service broker

  • In database we use trigger to perform particular task after insert, update or delete. Those task will execute synchronously and if trigger has lots of T-SQL statement then it‚Äôs become time consuming work. So in this situation we can use service broker for asynchronous execution.
  • Service broker doesn‚Äôt support publish-subscribe framework but you can play around service broker component to implement publish-subscribe pattern
  • Ordering web application could use service broker on the server side to send information to different database that might contain data related to inventory, customer and update other database based on message.

There are two part of the service broker end to end process

  1. Configuring the Service broker component
  2. Sending and Receiving Messages

Configuring the Service Broker

Below image help you to find out service broker component on SQL Server


Service broker components need to configure to start working on service broker. Below are step by step guideline to configure service broker component.

  1. Enable the Service Broker on the database
  2. Create valid Message Types.
  3. Create a Contract for the Conversation.
  4. Create Queues for the Communication.
  5. Create Services for the Communication.

1. Enabling Service Broker

Service broker is database level feature. It is not a SQL server instance level feature so that you need to enable it on the particular database on which you want to sue service broker feature.

Following is SQL Query which can be used to enable service broker on particular database

USE master

To verify whether service broker is enable or not on particular database you can use following query

SELECT is_broker_enabled FROM sys.databases  
WHERE name = [DatabaseName]

Following screenshot can also useful to know whether service broker is enable or not

Remote Access Guide.lnk

2. Create Valid Message Types

Message Types need to specific to send and receive messages. The initiator and the target will use the same message type to communicate between them. You can create as much as message type in database that participant in a conversation.

Following query will use to create Message Type of service broker

USE [DatabaseName]

Validation can be specified upon the content of the Message Type, most commonly used validation is WELL_FORMED_XML

3. Create a Contract for the Conversation

Service broker requires a contract to send and receive message. It also define Message type that is used during service broker conversion and also define which side of conversion can be send a message.

Following T-SQL statement used to create contract

USE [DatabaseName]
CREATE CONTRACT [ContractName] ([MessageTypeName] SENT BY INITIATOR);

4. Create Queues for the Communication

Service broker queue used for storing message during sending and receiving. There should be two queue one sender and other for receiver

Following T-SQL statement used to create queue one for initiator and one for target

USE [DatabaseName]
CREATE QUEUE [InitiatorQueueName];
CREATE QUEUE [TargetQueueName]; 

5. Create Services for the Communication

Service broker Services route the message to particular queue. When the initiator or the target send a message, it will route the message to specific queue. So, we will define each service with their appropriate queue.

Following T-SQL statement is used for create service for initiator and target

USE [DatabaseName]
CREATE SERVICE [InitiatorServiceName]
ON QUEUE [InitiatorQueueName] ([ContractName]);
CREATE SERVICE [TargetServiceName]
ON QUEUE [TargetQueueName] ([ContractName]); 

Sending and Receiving Messages

Once service broker is setup on you SQL server now you can send message between initiator and target queue using service broker component

For sending message to target you need to first determine the service and contract then prepare message and send the message.

Following T-SQL statement is used to send message to receiver queue

Determine service and contract using @Dialog on initiator side and send message

FROM SERVICE [InitiatorServiceName]
TO SERVICE [TargetServiceName]
ON CONTRACT [ContractName]

SET @Message¬†=¬†‚ÄėHello World‚Äô;
MESSAGE TYPE [MessageTypeName] (@Message)

Receive Message

RECEIVE CONVERT (NVARCHAR (MAX), message_body) AS Message
FROM [TargetQueueName]

SQL Example: Send and Receive ‚ÄúHello World‚ÄĚ service broker example

 -- This example configure service broker and performing sending and receiving ‚ÄúHello World‚ÄĚ message
USE SBHelloWorld
 -- Configure service broker
-- 1. Enable the Service Broker on the database
-- 2. Create valid Message Types
-- 3. Create a Contract for the Conversation
-- 4.a. Create Sender Queues for the Communication
-- 4.b. Create receiver queue for the communication
CREATE QUEUE SBReceiverQueueTest
-- 5.a. Create sender services for the communication
CREATE SERVICE SBSenderServiceTest ON QUEUE SBSenderQueueTest (SBContractTest)
-- 5.b. Create services for the communication
CREATE SERVICE SBReceiverServiceTest ON QUEUE SBReceiverQueueTest (SBContractTest)

-- Send and receiver message over service broker

DECLARE @SBDialogTest uniqueidentifier
FROM SERVICE SBSenderServiceTest
TO SERVICE 'SBReceiverServiceTest'

-- Sending Message
SET @Message = N'Hello World';
-- View messages from Receive Queue
SELECT CONVERT(NVARCHAR(MAX), message_body) AS Message FROM SBReceiverQueueTest
-- Receive Message
RECEIVE TOP(1) CONVERT(NVARCHAR(MAX), message_body) AS Message FROM SBReceiverQueueTest
-- Drop database
USE master

Some useful information that will help you out while working on service broker

—- Checking out queue
SELECT TOP 1000 *, casted_message_body =
CASE message_type_name WHEN ‘X’
ELSE message_body

—- Checking out transmission queue
SELECT * FROM sys.transmission_queue


Service Broker uses a transmission queue as a holding area for messages. Outgoing messages are added to the transmission queue in the database that sends the message. The message remains in the transmission queue until the destination has acknowledged receipt of the message.


  • Microsoft TechNet
  • SQL Authority with pinal dave