Wednesday, October 6, 2010

Be careful about using Session state of ASP.NET

As an ASP.NET developer, we always use session state whenever we need to keep something related to user. Usually, session’s data stays in memory. Now a day, memory is not very expensive. Since memory is not expensive, we like to keep something into session without thinking much about it. This thinking leads to a dangerous state of an asp.net project.

Recently, our team was profiling one of our asp.net applications. At the time of profiling, we figured out some CPU intensive operations. Among the CPU intensive operations, session serialization was very costly.

We are using ASP.NET state server for our session state. In order to keep an object into state server, the object has to be serialized. As mentioned before, serialization is very costly operation. The following are the thumb rules for me while using state server:

  • Always run and use state server at the time of development. In other words, never use InProc.
  • Until or unless you need anything to keep in session, don’t keep it.
  • If you need any user specific data which is costly to get and doesn’t change during the session time, keep that data in the static field. Keep in mind that for a web farm environment, each process has to initialize the static field.
  • Never use default serialization of .Net for large and heavy object. .Net default serialization uses reflection which is expensive. Implement custom serialization for such a scenario.
  • Don’t keep large object using a single key. If you don’t need the entire object at a time, splits the object. It will reduce the size of the object and reduce the de-serialization cost.

Happy Programming!

No comments: