Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage sessions in a distributed application

I have a Java web application which is deployed on two VMs. and NLB (Network Load Balancing) is set for these VMs. My Application uses sessions. I am confused that how the user session is managed in both VMs. i.e. For Example- If I make a request that goes to VM1 and create a user session. Now the second time I make request and it goes to VM2 and want to access the session data. How would it find the session which has been created in VM1.

Please Help me to clear this confusion.

like image 477
Vivek Mishra Avatar asked Sep 21 '15 06:09

Vivek Mishra


People also ask

How are sessions managed?

Session management refers to the process of securely handling multiple requests to a web-based application or service from a single user or entity. Websites and browsers use HTTP to communicate, and a session is a series of HTTP requests and transactions initiated by the same user.

How do you maintain a session across multiple servers?

If you are deploying application on more than one server, you should use "Clustering". Application servers are able to handle this scenario using "session replication". With session replication, each server will have a copy of the active users session.

How session is managed in web application?

Sessions are maintained automatically by a session cookie that is sent to the client when the session is first created. The session cookie contains the session ID, which identifies the client to the browser on each successive interaction.


1 Answers

There are several solutions:

  • configure the load balancer to be sticky: i.e. requests belonging to the same session would always go to the same VM. The advantage is that this solution is simple. The disadvantage is that if one VM fails, half of the users lose their session
  • configure the servers to use persistent sessions. If sessions are saved to a central database and loaded from this central database, then both VMs will see the same data in the session. You might still want to have sticky sessions to avoid concurrent accesses to the same session
  • configure the servers in a cluster, and to distribute/replicate the sessions on all the nodes of the cluster
  • avoid using sessions, and just use an signed cookie to identify the users (and possibly contain a few additional information). A JSON web token could be a good solution. Get everything else from the database when you need it. This ensures scalability and failover, and, IMO, often makes things simpler on the server instead of making it more complicated.

You'll have to look in the documentation of your server to see what is possible with that server, or use a third-party solution.

like image 187
JB Nizet Avatar answered Oct 19 '22 20:10

JB Nizet