Tuesday, January 21, 2014

Still using Session State?

Is there anyone out there still using Session State? I know there are because I inherit code from other development teams all the time, and more often than not it is littered all over the place with variables being stored in the session.

A little background on me. I have been developing web sites and web applications in ASP.Net since 2001, and Classic ASP before that. I have literally built hundreds of applications personally, plus hundreds more through my web development company, Business Edge.

Here are a few reasons why using Session is a bad idea. For one, it takes up memory on the server for each user that has opened up a session with their browser. Applications that use Session are far less scalable than ones that don't, simply because of the memory requirements on the server. Another reason is that the code is harder to follow. When I have to read someone else's code and I see a reference to a session variable, it is difficult to determine if that session variable contains the value I expect, because it could have been set (and re-set) multiple times in the call stack. Third, those session variables are volatile, and time out after their configured time is up. And finally, if you go to a load balanced environment, additional considerations need to be taken into account in order to make sure that session state is handled by the load balancer and your front end web servers correctly.

But how do I do what I need to do without using session variables, you ask? Off the top of my head, there are 6 other viable alternatives to using the session to store variables. You can store data in cookies, query string variables, hidden form fields, the http context, the database, or the view state. In all of my years building web applications, I think I can count on one hand the amount of times where I had no other choice than to store a variable in the session state. All other times I was able to store data somewhere else that didn't require additional, per user, memory on the server.

So please, if you can avoid it, don't use Session State. I know that every book on ASP.Net contains a full chapter on Session State and how great it is, but take my advice and avoid it as much as possible.

No comments:

Post a Comment