Vivek Mishra
Vivek Mishra

Reputation: 1794

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.

Upvotes: 14

Views: 9481

Answers (2)

N.K.Sunil Sunilnk
N.K.Sunil Sunilnk

Reputation: 85

We can use distributed Redis to store the session and that could solve this problem.

Upvotes: -2

JB Nizet
JB Nizet

Reputation: 691685

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.

Upvotes: 32

Related Questions