Explicitcoder

Divyang's ICollection

EB algorithm for Azure Database connection

Hi Friends,
As cloud computing  buzzing now days, so I spend my spare time to do some hand-on code for Window Azure using trial pass and reading related blogs for that

  Then during  my hand-on , once I face the problem of frequent connection failure due to  my Azure db was unavailable for few seconds .

Then I learn from forum that, It may be my database to be moved to another server at any time, causing the database from being unavailable for a few seconds, or a few minutes depending on the scenario.
So to overcome this problem my quick solution was  that make  big loop to open connection
somthing like this
private SqlConnection myconnection()
{

  int counter = 0;
  while (counter < 100)
  {
    try
    
{
       
System.Threading.Thread.Sleep(1000);
      connection.Open();
      return connection;
    }
    catch { }
   
counter ++;
  }

}

but this is problem and  lead to the error of “Denial of Service attack”. so what should I do then ..??? Then  on forum on fellow has suggested to  use Exponential Backoff(EB) algorithm to over come this problem . So I read about this algoirthm  on wiki and google it. And I found that it is  used commonly  in networking and  Ethernet protocal .
there two flavor of  EB
1)binary exponential backoff
2)truncated binary exponential backoff

so planned to use 2nd flavor  and made one extension method  to solved this problem  which provides EB when a connection timeout is encountered. In this case my extention method will tries to open a db connection up to 5 times in a row,  backing off 3 seconds exponetially everytime(3 seconds, 9seconds, 27 seconds..)


public static SqlConnection OpenwithEB(this SqlConnection connection)
{
  int counter = 0;
  while (counter < 5)
  {
    try
    
{
      if (
counter > 0)
       
System.Threading.Thread.Sleep(((int)Math.Pow(3, counter)) * 1000);
      connection.Open();
      return connection;
    }
    catch { }
   
counter++;
  }
  throw new Exception(“Unable to obtain a connection to SQL Server or SQL Azure.”);
}
Now I can use  my extension method like this 
SqlConnection connection = new SqlConnection(“my con string“);
connection.
OpenwithEB();

I hope you will find  this type of complex routine with centralize mechanization.

 

compile bye 
Divyang Panchasara
Sr. Programmer Analyst
Hitech OutSourcing

Leave a Reply

Your email address will not be published. Required fields are marked *