Session Variable Do’s and Don’ts
There are several factors to consider when implementing session variables in your application. The first and most obvious factor is the amount of concurrent users in your application. This means an estimate of the maximum amount of users logged into your system at the same time during your peak hours. If this number is in the 100’s for your system chances are your scalability will be fine given a reasonable amount of server RAM.
If your application has thousands of concurrent users you have to be much more careful about not only the amount of session objects, but the storage capacity of those objects. Consider 10,000 concurrent users each with 10K of session data and suddenly your ASP.NET worker process is consuming hundreds of Megs of RAM. Your scalability curve should always be linear, whereby your system resource usage is directly proportional to your number of concurrent users. If you notice your server memory decreasing at a greater curve with the more users you add, it’s probably a good idea to step back and do a performance review.
Outside of the concurrent user factor there are some general do’s and don’ts with session objects. You should always consider the storage capacity of the objects you place into the session. For example, you should never take the results of a database query and store it in the session. Datasets, datatables, dataviews should all be considered off-limits when it comes to session storage.
The best types of objects to place into the session are simple basic pieces of information which help provide shortcuts and a more customized user interface. User name, location, even basic preferences are good candidates for session storage because they don’t consume much memory.
One last tip for session objects is regarding naming conventions and clutter. Session variables are fairly free-form and don’t lend themselves to a very strict coding pattern. You simply provide a name and assign a variable and you’re done. To keep your code tidy always decide on a naming convention for session variables or even create constant variables to prevent typos in your session variable names. The main point is that session variables can become very messy very quickly so it’s always a good idea to create access functions and solid naming conventions to keep the code clean.