Friday, January 30, 2009

Session Managment

Recently my work has lead me down the path to analyze how various enterprise applications use the HttpSession object and to propose and implement a strategy that would optimize its usage. Pretty interesting right ?

So first and foremost, what should be the ideal size of an HttpSession ? IBM proposes that it should not be greater than 10K. Overall the general consensus is that we need to keep the session as small as possible.

What should we know about the http session ?
- The HttpSession shares memory with the running web applications inside the JVM heap
- There's no limitation to the size of the http session, although some application servers can limit the number of sessions.
- The objects you store in the http session often contain other objects too (nested objects). So the cumulative size of the http session includes all of the objects you store.
- Managing session is important for application  performance as well as for scalability. If one user occupies 10MB of session data, and if 100 users hit the application, then thats 10*100 MB of memory used up for session data - which most servers wont be able to handle ( the average JVM heap is around 256 - 512 MB).

This is why managing session is so important for enterprise applications.

So here's what we decided to do.
- Quite simple really. Minimise using the session :) , if we have to keep something in session, then move it to a cache (hosted seperately) and just keep the keys in session. 
- Monitor how frequently the objects in the session are used. If they are used very rarely, then it makes sense to keep them in the database and fetch them only when required.
- Monitor on average, how many sessions are used by the web application. This will give you a decent idea if the memory on the box is sufficient or if you need to upgrade OR if you need to control the number of sessions permitted for each server so that the JVM wont trash.
- Even data that needs to stored in session should be analyzed to see which fields should be declared as transient. 
- HttpSessions should be invalidated properly during logout and browser close actions. Session timeouts cause the httpsession to be destroyed automatically.
- Keep profiling the application to see if we're utilizing the session ( and other objects ) optimally.

[Performance Analysis for Java websites, Http Session Management, Http Session Best Practises]

Search This Blog