How Session Works in Web Applications and Why We Need It

In context of web applications, a session is a storage area (or you can say it a bucket) that hold some information on web server. But some fundamental questions are:

1. What is the nature of this bucket (session)?
2. Why we need a session?
3. How session work?
4. Where session data is stored?
5. What type of information it holds?

Lets look at each part one-by-one:

1. What is the nature of this bucket (i.e. session)?

As a programmer, you already know data structures e.g. integer, string, stack, map, queue, etc. Session is a data structure that store some value againt a key. Keys are string and value is an object stored against that key. This object can be of type array, int, string, float or others. So, we store data in the form of objects and associate a string, i.e. key. The key is used to retrieve object back from session.

2. Why we need a session?

When user opens a web page, web server send the request page contents and closes the connection. But sometime in web application, we want serve personalized contents (his email, notes, calender etc) based on user identity. One option is, user send his identification information with each request, so that the server side script (Servlet, JSP, Ruby, PHP, or code) can identify user and serve the personalized contents. A better way is, user send his identification information only once (e.g. authentication time) but for all subsequent requests, server shall identify the user making the request automatically.

The first approach seems simple but impractical. Because users would not like to send identification information with each request. It also look odd from usability perspective (as you know, you login at websites only once, then server remember you for some of time, until you signout).

Web applications use second approach i.e. user send the identification information (username and password, for example) only once. When another request is sent by same user, the server identifies which user sent the request. Sessions are used to store information associated with particular user-interaction, on subsequent requests, the server can identify a particular session (or bucket) associated with that user interaction. We can store multuple key/values in session.

3. How session works?

If you use gmail (or any other email service), you know once we login, it displays YOUR EMAILS, not the inbox of someone else. So its mean, after login, when you send a request by clicking on hyper links (e.g. fetch new email to read), the server identifies you. And, thousands of users may be visiting their inbox at same time. But server never makes a mistake to serve user A the emails of user B. So how server identifies a particular user?

When user submit login form, the server authenticate you and create a new session (a bucket or Map of key-value), a new session ID is generated which is used to identify a particular session later. Server can store any amount of information into user session e.g. your name, email address, list of emails, list of lables, etc. So if there are 1000 active sessions, there must are 1000 session IDs generated by the server to uniquely identify each session later.

When server create new session (and new session ID is generated), server send that session ID to we browser, where it is stored (we call it cookie). When user orginate a new request, browser automatically send that Session ID to server (in form of request cookie). When request comes at web server, it checks whether request carries the Session ID? If Session ID (cookie) is found in request, the server use it to retrieve a particular session object already created at server side. And server link this session object with current request, so that during the request processing, programmers can make updates to the session object (list of key/values).

You can think, the server sessions is an object of type Map. The Map has a key and value. The key is the Session ID and value is another Map. So when user send subsequent request to server, before calling our page, the server do something like this (its just a pseudo code):

if (SessionID Cookie exist) 
  Map userSession = (Map) allServerSessions.getValue(SessionID)

So when request object is transferred to our page (PHP script or a Servlet), it already contains the session object. If we have stored a User object with key "user", then we can retrieve "user" object back like this:

User user = (User)request.getSession().getValue("user")

4. Where the session information is stored?

If you have read above details, you must know, the session information is stored on web server. Only Session ID is sent browser, which it sent back to server, so that the session object can be identified.

5. What type of information the session holds?

As explains, a session is a Map of key values. Where keys are strings and values are objects. So you can store any information in session (e.g. strings, integers, or customs objects) by associating a key to them. For example, to store a Book object, I can choose the key, say 'book', and store it into session like this.

Book myBook = new Book(1, "Web Programming", "2010");
request.getSession().add("book", myBook);

This would store an object with key "book" into session scope.

// I can store a string value like this
request.getSession().add("email", "")


  1. Simple yet effective explanation. Thanks! :D

  2. Detailed explanation. Thank you !

  3. Great work. Thanks

  4. thanx.. that's very simple explanation

  5. thanks a lot great job.....

  6. More than awesome. With love from referred by Asif Shahzad

  7. Thanks. It was very helpful.

  8. great explanation on a beginner level..... thanks...

  9. Thank you for the clear explanation. I particularly like the way you see a session as a map. Very helpful.

  10. i love this explanation it makes me want to go milk a full stack leprechaun.

  11. Thank you, good job, without unneeded complications :)

  12. Thanks for the straight forward explanation. It helps to demystify Sessions. One question: where in memory is the session typically stored on the server? Main memory would be OK for a small site that need only handle perhaps a thousand sessions concurrently but what happens when there are many thousands of concurrent sessions? Can sessions be easily linked to a database? Thanks again.

    1. Yes, sessions can also be stored in DB or files. Usually its done when user shows no activity for some time but we don't want to sign-out or destroy her session. Sessions synchronizations is another issue, for example 10 servers are serving requests, the first request was served by Server 1, but then it got busy in other users, and the subsequent request from same user sent to Server 4. Now the session data exist in Server 1, so intelligent techniques are used here to make sure sessions remain synchronized on all servers or same server handle the request. It latest web architectures, e.g. SOFEA, its is recommended that server always remains stateless and any data that need to be stored in session should be maintained at client/browser side. The details of these issue is out of scope of this post.

    2. Yes it is possible but you get a overhead when storing in DB, so its batter to do only for inactive users as very well explained by Asif

    3. Thanks for clear my concept.....

  13. Nice one.. great stuff :-)

  14. I have a simple form submission. It stores some fields in the database. will that require session usage? if i do not use then? please somebody suggest as how and where to use the session code. thanks

  15. thanks sir, it makes my day... :)


Post a Comment

Popular posts from this blog

Task 12 - Create Java Program with MySQL Database Connectivity

Java Interfaces and Exception Handling - Practice Problem with Solution

Task 16 - Javafx Program to Create, Retrieve, Update and Delete records with Database