Tuesday, October 14, 2003

Session Variables - Operational Information and Performance

MSDN Article By Vishal Joshi

Article Posted: October 21, 2003

It is many a times said that you should use minimum session variables in your web application and use of session variables actually affects the performance adversely. Did you ever try to analyze why is it so? In this article I have explained (in not so detail but have given required operational information) about the Session Variables, their use and their affect on web application performance.

Recollect your writing this simple code int intUserId = Convert.ToInt32(Session[“UserId”]);

Do you know what all does ASP.NET runtime actually does behind the scene? Well in fact to handle this there are lots of considerations taken into account and there is a lot of background processing happening.

To explain this in brief let me re-iterate over the fact that ASP.Net provides 3 different kinds of session storage facilities namely “InProc”, “StateServer” and “SQLServer”. So you can have your session data stored at any of these three different locations.

1. In Process – This is the default option by which the session values are kept alive as objects in Windows Server, by ASP.Net worker process.
2. State Server (Out of Process) – aspnet_state.exe runs as a separate process on the same box or on another machine. In this case the session values are serialized and stored in the memory of this separate process.
3. SQL Server – As the name suggests in this case the session values are stored in the SQL Server table. Again in this case the SQL server can be on the same box as well can be a dedicated DB server.

You can specify the state provider in the web.config file of your application in the section like

sqlConnectionString="data source=;user id=sa;password="
cookieless="false" timeout="20” />

The mode in the above case can have four different values representing different locations of storage discussed above.

Off – Indicating application wide session state is not enabled. If your application is not going to use any session information remember to set the mode to “Off”. (Note: If you have not set the mode to “Off” and you have a Session_OnStart handler in your application session is saved even though it is empty, which can adversely affect the performance, so do not have Session_OnStart handler unless it is required for your application.)

InProc – This is the default option

StateServer – If you set this as mode then providing stateConnectionString parameter is important. (Note: indicate local host, you may provide any server name, and 42424 is the default port number, providing it is mandatory. Also note that state service, process named - aspnet_state.exe, is installed but is stopped by default, so you may need to start that on the server before use.)

SQLServer – If you set this as mode then providing sqlConnectionString parameter is important (Note: ASP.Net uses default Databases and Initial Catalog so providing such arguments in the connection string is not allowed)

The cookieless parameter indicates whether session without cookies should be used to identify the client sessions or not. The default value is false indicating that cookies should be used to identify client sessions. (Note: This is one of the major differentiating features provided by ASP.NET Session State over classic ASP. In a single line cookieless sessions use mangled URL concept for browsers to identify the session state.)

The timeout parameter indicates the time in minutes after which, an idle user session should be abandoned. (Tip: You may want to take care of this parameter sometimes - like if you are building a catalog or gallery you may not want a user to get time-out notices in a short while but in case of banking application you may want to reduce the limit.)

Now, we understand that ASP.NET can store our session variables at different locations according to our choice, let us now understand roughly what it does behind the scene to get or set our session variables. Take a hypothetical scenario in which you have made no changes to the above settings and a single web page (in consideration) of the web application has got multiple frames. Each frame is reading or writing information into the Session. To add up to the trouble let us assume that only one particular Session Variable is being accessed and modified by all the frames. This scenario is possible right!! ASP.NET runtime needs to handle all such scenarios. To handle this ASP.NET runtime implements LOCK. There are two different types of locks namely - Reader Lock and Writer Lock. If a reader lock is set then concurrent read-only requests will be entertained but write requests will be held back and given last priority. But if a writer lock is set then all the remaining read-only or write requests have to wait. Thus it might so happen that till your one frame finishes the other frames might not even get start their processing. You can see how performance will be affected in this case. Thus ASP.NET implements queuing of requests to session and tries to handle it in an optimized way but we also need to be judicious in requests to the session too!!

Among the available three ways of maintaining session state it is quite evident that InProc mode is the most efficient. Researches have indicated that the use of OutProc (StateServer) mode effects performance up to 15% whereas SQL Server effects up to 25%. The figures indicated by these studies are for basic types and for user defined types they may even go higher. The reasons behind these hits are the serialization and de-serialization that occurs while moving the objects to the session state and then retrieving them. This overhead is clearly saved in InProc mode as the objects are saved in memory and there is no need to go through the serialization/de-serialization processes. The hit that is present in the InProc mode thus is mainly due to the memory consumption by addition of session variables. By judiciously adding objects to sessions thus can help in case of InProc mode.

So now if you ask why we at all need the other two modes when they are so performance expensive then the answer is because of the reliability. The data persisted in SQL Server or in OutProc mode is much safer as it is not hit by failures in IIS or ASP.NET or even by process recycling. Though if SQL Server or aspnet_state.exe is stopped or failed then there are potential chances of the loss of data (in case it is not handled properly!!) but when data is critical then these modes need to be used. So if we rate these modes according to performance then the ranks would be

1. InProc
2. StateServer
3. SQLServer

But if we rate the same from reliability perspective then the ranks would be

1. SQLServer
2. StateServer
3. InProc

Though you can note the ease that the way your application would read/write the data will remain the same as Session[“key”] = value;

Thus again, as usual you have to do the correct trade-off and decide what is good for your application no one can really give a statement on this. But at the first place remember that if you can do away without Session Variables then you should never go ahead and use them.

Now, as we understand the performance implications related to session state usage let us be conscious programmers and understand how we can control sessionState to increase performance of our individual pages. @page directive of ASP.NET page has a property called “EnableSessionState”. If your page is not accessing any session related information you can set this variable to “false”. If your page is going to only read from session then ensure that you set this value to “ReadOnly” and if you are going to do read write operations to session then set it to “true”.

At the end we will conclude by saying that Session Variables are designed for the convenience of us designers/developers but we should be careful enough to use them and should be conscious enough to know how much performance we are trading off by the way we use them.

Vishal Joshi
Microsoft MVP

Friday, October 03, 2003

This came in DotNetNuts.com and was brought to attention by Deepak Kumar Vasudevan, a fellow MVP... Thanks Deepak for the same...

The Ten Commandments of .NET

1. Thou shall learn XML, now! If .NET is an angel from Microsoft then its wings are woven with XML, and you need to understand the basics of XML before you can fly with .NET. XML is used for configuration files, SOAP,Serialization, and it's tightly integrated with ADO.NET. You can get away without knowing XML, but you won't get far.

2. Thou shall become an object-oriented programmer! To understand .NET and build successful applications you must understand OOP. VB programmers now have new object-oriented capabilities, but may not know how or when to use them. You should understand interfaces and abstract classes (there's a difference between the two in .NET), implementation inheritance, function overriding, and shared members. If your not familiar with OOP at all, start learning ASAP. If your established with OOP as it applies to VB6 then dig deeper into OOP methodology, it will certainly make .NET more enjoyable.

3. Thou shall concentrate on the .Net framework, not the language being used. No matter what .NET language you use, your still using the same framework, so it's very important to focus on the framework, not a particular language. Keep in mind that most of the functions you'll use while programming are from the framework, so using a new language is easy, simply adjust to the syntax. Plus, having C#, C++, VB, Perl, Pascal, COBOL, Fortran, and Eiffel on your resume is more impressive than having just one.

4. Thou shall not go it alone. Get involved in the .NET community. This is the best way to dive into .NET. Message boards are a great resource because you can read problems and questions posted by beginners, and examine the solutions they received. After all, it's better to learn from others mistakes than to learn by repeating them. DotNetNut.com is a great place to start. You'll find message boards, original articles, constantly updated FAQ, and an enormous amount of links to other great resources. We 'll help you spend more time learning and less time digging for answers.

5. Thou shall adapt to new development environment. For VB programmers the VS.NET IDE is a big change, and it's going to take some effort to adjust. Not only is there much better support for debugging than in VB6, but there is also the ability to record and playback macros. Get intimate with the IDE, missing out on great new features is shameful.

6. Thou shall abandon DCOM and use remoting. DCOM was a big step in Microsoft distributed computing, but it's time has passed. Remoting is the .NET model for distributed computing. It's more flexable, featuring plugable channels and protocols, and it generally out performs DCOM (Though note:Remoting outperforms DCOM is in intra-appdomains where as between processes and across network Remoting is slower by 250%..Thanks Sanjay Vyas for his inputs). Administration is done easily through application configuration files which elevate the headache of DCOM administration. Althought it takes a little more coding than DCOM the benefits are well worth it.

7. Thou shall not use VS.NETs code generators without understanding the code they generate. VS.NET has some great code generators that can save you time, but only use them if you understand the code they generate. Create a sample application, use the code generators, and be come very familiar with the results. It's impossible to support code ou don't understand.

8. Thou shall use structure error handling in VB. VB developers have a choice, either learn how to use structured error handling, or use the old On Error method. Using structured error handling brings flexibility and maintainability to VB and is one of the best new features. There are two reasons On Error should be left behind. One is because Try Catch Finally will be used in all .NET languages, On Error is VB specific. Two, because structured error handling is much more powerful, giving you the ability to nest Try Catch statements and layer exceptions.

9. Thou shall avoid using COM+ for single phase transactions. COM+ is great for two phase commits because of the DTC, but there is extra overhead for database locks due to the nature of the transaction. It's a waste of database resources to indiscriminately use COM+ when a less intensive lock can be used. Transactions through the Data namespaces are lighter and should be used for single phase transactions. It is possible to get the same automatic transaction enrollment available in COM+ by using the SinglePhaseTransactionContext component available for download (complete with source files) at DotNetNut.

10. Thou shall not underestimate the complexity of .NET. Is .NET going to make development easier? Yes, but (there's always a but) the .NET framework is so vast, and there are so many new concepts involved that NET will be difficult at first. If your new to the .NET runtime, than you may not know what value types and boxed types are, how the garbage collector works, or what application domains are. All these concepts are new to microsoft developers and important, to ignore them is sinful.