Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Mindcracker MVP Summit 2012
Search :       Advanced Search »
Home » Programming Best Practices » WEB farm - Load Balancing in Asp.net

WEB farm - Load Balancing in Asp.net

The concept behind the web farm is that a number of different web sites share pooled resources. They typically share a common front-end dispatcher to perform load control and distribute customer requests. They share the multiple web servers themselves.

Page Views : 139782
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
DevExpress Free UI Controls
Become a Sponsor
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Scope:

 

Considering the high volume of traffic the Web site uses two or more servers needed to handle user requests. The concept behind the web farm is that a number of different web sites share pooled resources. They typically share a common front-end dispatcher to perform load control and distribute customer requests. They share the multiple web servers themselves. Based on experience and with reference to Microsoft sites this document was created to address certain issues faced in web farm while using ASP.NET.

 

Machine Key:

 

Consider a scenario while doing a PostBack in ASP.NET and which looses the form information.

 

For Example:

 

When a user selects an item from a DropDownList and then clicks a submit button, the Click event on the button redirects them to the value of the selected item. This works fine if you are on Webserver1 and the button click PostBacks to Webserver1. If you are on Webserver1 and the load balance submits back to Webserver2, the page reloads and the Button click event never fires. This happen site wide and affects utilities such as submitting a textbox search and other form posting events.

 

Approach 1


You can modify the pages element in In machine.config of both the servers:

<system.web> 

   <pages enableViewStateMac="false" /> 

</system.web>


EnableViewStateMac indicates that ASP.NET should run a machine authentication check (MAC) on the page's view state when the page is posted back from the client;

True - if view state should be MAC checked
False - We need to ensure that it is kept to false.

 

Approach 2

 

Force every server in your farm to use the same key; generate a hex encoded 64-bit or 128-bit <machineKey> and put that in each server's machine.config.

Example: <don't use the below key>

<machineKey     validationKey='A130E240DF1C49E2764EF8A86CEDCBB11274E5298A130CA08B90EED016C0

14CEAE1D86344C29E67E99DF83347E43820050A2B9C9FC89E0574BF3394B6D0401A9'

decryptionKey='2CC37FFA8D14925B9CBCC0E3B1506F35066FEF33FEB4ADC8' validation='SHA1'/>

 

You can generate a key from

http://www.eggheadcafe.com/articles/GenerateMachineKey/GenerateMachineKey.aspx 

 

Session Management:

 

ASP.NET provides two solutions for sharing state information between multiple servers:

 

  1. The ASP.NET State Server service
  2. Microsoft SQL Server.

State Server

 

In a web farm, make sure you have the same <machinekey> in all your web servers.

 

http://support.microsoft.com/default.aspx?scid=kb;EN-US;q3103091

For session state to be maintained across different web servers in the web farm, the application path of the website (for example. \LM\W3SVC\2) in the IIS metabase should be identical in all the web servers in the web farm.

http://support.microsoft.com/default.aspx?scid=kb;EN-US;q325056

Make sure objects are serializable. Here in state server session gets serialized and stored in memory in a separate process (aspnet_state.exe). Also if you try to store instance of a class that is not marked as serializable into a session variable, the request returns without an error. However, Asp.net actually fails to save the session data and blocks subsequent requests in the same session. (Because the class is not marked as serializable).

SQL Server

Make sure objects are serializable (as like above).

If you specify integrated security in the connection string (For example "trusted_connection= true", or "integrated security=sspi") it won't work also if you turn on impersonation in asp.net.

For session state to be maintained across different web servers in the web farm, the application path of the website (for example. \LM\W3SVC\2) in the IIS metabase should be identical in all the webservers in the web farm.

Using SQL Server to Store ASP.NET Session State:

Run the InstallSqlState.sql script on the Microsoft SQL Server where you intend to store session state. This script will create the necessary database and database objects.

The .NET Framework installs this script in the same folder as its compilers and other tools.

For example: C:\WINNT\Microsoft.NET\Framework\v1.0.3705 on a Windows 2000 computer with the 1.0 version of the Framework.

Edit the sessionState element in the web.config file for your ASP.NET application as follows:

<sessionState mode="SQLServer" StateConnectionString="tcpip=127.0.0.1:42424"

SqlConnectionString = "data source=SERVERNAME; user id=sa; password=sa"

cookieless="false" timeout="20" />

 

Supply the server name, user name, and password for a SQL Server account that has access to the session state database in the sqlConnectionString attribute.

Steps to run the InstallSqlState.sql and the UninstallSqlState.sql script files to configure SQL Server mode session state management.

In SQL Query Analyzer, on the File menu, click Open.

 

In the Open Query File dialog box, browse to the InstallSqlState.sql script file, and then click Open. By default, InstallSqlState.sql is located in one of the following folders:

 

system drive\Windows\Microsoft.NET\Framework\version\

 

After InstallSqlState.sql opens in SQL Query Analyzer, click Execute on the Query menu to run the script.

 

Before you run the UninstallSqlState.sql script file to uninstall SQL Server mode session state management configuration, you must stop the w3svc process. To do this, follow these steps:

 

  • On the Windows Start menu, click Run, type cmd, and then click OK to open a command prompt.
  • At the command prompt, type net stop w3svc. You receive confirmation that the w3svc process is stopped.

In SQL Query Analyzer, on the File menu, click Open.

 

In the Open Query File dialog box, browse to the UninstallSqlState.sql script file, and then click Open. By default, UninstallSqlState.sql is located in one of the following folders:

 

system drive\Windows\Microsoft.NET\Framework\version\

 

After UninstallSqlState.sql opens in SQL Query Analyzer, click Execute on the Query menu to run the script.

 

After you uninstall SQL Server mode session state management configuration, you must restart the w3svc service. To restart the w3svc process, type net starts w3svc at a command prompt.

 

Security Considerations Sql Server [Session]:

 

The following aspects need to be kept in mind:

 

  • Use Windows authentication to the database
  • Encrypt sqlConnectionString
  • Limit the application's login in the database
  • Secure the channel

Caching Considerations:

 

There are three options explained below.

  1. Synchronizing all servers in web farm
  2. Centralized Cache location to be maintained.
  3. SQL server caching

1. Synchronizing all servers in web farm

 

By providing a wrapper class simply having a CacheControl.aspx receiver page in each of the Applications, it is possible to send a WebRequest to each of the machines (maintained in an easy-to-configure web.config AppSettings element) and have each enabled with code to do its own update "on demand".

So, whenever add a "real" item to the Cache, it will also create a new populated instance of the same class, serialize it into a compact byte stream, and iterate through our server list sending it over the wire via the WebRequest so that each app in the farm, WebGarden, etc can receive and deserialize it, and update its own Cache. Simple, elegant, and fast! Even if it is a complex object such as a class that you have added to your Cache, provided that it is serializable, it will work.

2. Centralized Cache location

One Cache-application is to be created, which will take care of the caching and returning the cached items. And that is to be placed in centralized location. All applications should send the data to be cached, to that cache-application. The Cache-application will store the data. When any application requests the cached data, it will be retrieved from the Cache-application. (The centralized Cache-application can be called with credentials.)

 

3. SQL server caching

 

SQL Server caching is easy to implement by using ADO.NET and the .NET Framework, and it provides a common development model to use with existing data access components. It provides a robust security model that can easily be configured to work across a Web farm using SQL Server replication.

 

If the application requires cached data to persist across process recycles, reboots, and power failures, in-memory cache is not an option. In such cases, Caching mechanism based on a persistent data store, such as SQL Server or the NTFS file system. It also makes sense to use SQL Server to cache smaller data items to gain persistency.

 

Because the cache service needs to access SQL Server over a network and the data is retrieved using database queries, the data access is relatively slow. We need to carefully compare the cost of recreating the data versus retrieving it from the database.

 

NLB(Network Load Balancing):

 

Network Load Balancing_NLB is a network driver that distributes the load for networked client/server applications across multiple c luster servers. Network Load Balancing works by distributing client requests across a set of servers.

Shopping cart contents at an e-commerce site and Secure Sockets Layer (SSL) authentication data are examples of a client's session state. Network Load Balancing can be used to scale applications that manage session state spanning multiple connections. When its client affinity parameter setting is enabled, Network Load Balancing directs all TCP connections from one client IP address to the same cluster host. This allows session state to be maintained in host memory.

NLB provides the client affinity parameter, which, when enabled, basically makes you "always come back to the server you landed on first", thereby insuring that your Session and Application variables don't get thrown away. Use the client affinity feature. When client affinity is enabled, Network Load Balancing directs all TCP connections to the same cluster host. This allows session state to be maintained in host memory. You can enable client affinity in the Add/Edit Port Rules dialog box in Network Load Balancing Manager. Choose either Single or Class C affinity to ensure that only one cluster host will handle all connections that are part of the same client session. This is important if the server application running on the cluster host maintains session state (such as server cookies) between connections.

Network Load Balancing, a clustering technology included in the Microsoft Windows 2000 Advanced Server and Datacenter Server operating systems, enhances the scalability and availability of mission-critical, TCP/IP-based services, such as Web, Terminal Services, virtual private networking, and streaming media servers. This component runs within cluster hosts as part of the Windows 2000 operating system and requires no dedicated hardware support.

Other Tasks:

Request distribution: Incoming HTTP requests must be distributed among all servers by using a mechanism such as round-robin DNS, Microsoft Application Center 2000, or a third-party load distribution device.

Log aggregation: Before you process HTTP usage logs, it is a good idea to combine the logs to create a single log that includes requests sent to all systems.

Monitoring: To detect problems that affect a single server or the whole site, you must monitor both the external URL for the site and the URLs for each of the Web servers.

Scheduler:  Scheduling an event to occur on a single server should cause only that one server to run the task. Scheduling an event to occur on all servers should cause all servers to run the task. [Updations need to be done and should get reflected in all servers hence scheduler should appropriately picked-up]

Centralized database: Web applications that use a database must have a single database that is shared between multiple Web servers. In environments that require no single point of failure, cluster the database server.

Synchronize Configuration and Content:

You need to ensure that the config files are present in the right path on all the servers, and that their contents are continuously in sync.

 

You can copy configuration files to servers by using any standard file copy or synchronization method, including DFS, the File Replication service, and Microsoft Application Center 2000.

 

The following batch file will work in environments where each Web server has the virtual server root folder shared as:

 

wwwroot$: XCOPY \\source-server\wwwroot$ \\destination-server#\wwwroot$\D\E\O\X

 

When you deploy configuration information and ASP.NET content to multiple servers, it is critical to deploy the content from a single staging server to all production servers at the same time. This reduces the chance of problems occurring when a user's requests are sent to different servers. Microsoft recommends that all configuration and content updates occur on the staging server. Ideally, this staging server does not receive requests from users. It is dedicated to the task of testing and deploying new content.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 Article Extensions
Contents added by srinivasan on Apr 20, 2011
 [Top] Rate this article
 
 About the author
 
P Gopenath
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
load balancing - another suggestion by m On August 8, 2007
You never mentioned the fact that you can also use Stateless and Stateful Objects in load balancing. calls. The calls can be made to a virtual IP.
Reply | Email | Modify 
Good article by Mahesh On September 21, 2007
Good article Gopi. We would like to see more articles on Web Farms and related topcis. Keep up the good work. Cheers!
Reply | Email | Modify 
Microsoft Project code named "Velocity" by Touqeer On May 27, 2010
We can use Microsoft Project code named "Velocity" as well instead of SQL Server or State Server in order to manage the Session and Cache data.
Reply | Email | Modify 
Session State & Scalability by troy On June 25, 2010
Developers/Admins should be aware that SQL Server setup to be a session state repository does not scale well when getting high amounts of traffic.  Things like AppFabric, SharedCache and MemCache should be used in it's place.  

AppFabric (FKA: Velocity) has just been released and will probably be the easiest to integrate into an IIS web farm/garden... SharedCache would be the next in line for ease of configuration.
Reply | Email | Modify 
Need more info on the option "Synchronizing all servers in web farm" by Ven On November 1, 2010
Hi,
     I need more info on the option "Synchronizing all servers in web farm". I have a scenario where there are 5 Web Front End web servers in the MOSS farm and after deploying new content, the output cache needs to be cleared on all the load balanced servers in the farm, programmatically. Kindly help.
Reply | Email | Modify 
Very well explained article! by Cameron On July 18, 2011
ASP.net needs to cache data when request load to the database increases. NCache is a Distributed cache it manages sessions in HTTP module (http handler is used to maintain sessions), session state store provider and in multi regional session cache. Furthermore it uses sticky sessions for load balancing.
Reply | Email | Modify 
Well Written and Well Explained article by Pankaj On December 1, 2011
Thanks, It was really helpful for new bie of Load balancing and was in pretty good detail to do by self.
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.