Search code examples
node.jsexpresssessionload-balancing

How to handle sessions on multiple account servers / while scaling horizontally?


I'm working on a web app and want to do it properly, so I'm keeping scalability at the back of my mind. One thing that is boggling my mind is how to handle sessions on multiple servers.

Short Example:
Let's say Anna logs in on my web page and the load-balancer redirects her to server X. Server X stores Anna's session data and shortly after Anna closes the web page.
After 10 minutes or so, Anna opens the page again and gets redirected to server Y. Her session should still be alive.

How does server Y know it's her?

  │
  ├── Anna ─> load-balancer ─> Server X ─> Session Data on X
  │
10 mins pass
  │
  └── Anna ─> load-balancer ─> Server Y ─> How to get session data on X?

  • Is there a possibilty to serve authenticated api requests sessionless?
  • Is it best practice to store session data on a central data base?
  • Is there another common solution I might not know how to search for?

I'm very greatful for any answers but especially if in context of node/express apps. In general I am looking for best practice solution, as I'm eager to learn.


Solution

  • For this scenario, there is some options you can check:

    1. If you need to store access tokens (oauth), you can use redis, a fast database to check the token by any Node.js server in each request (https://redis.io)
    2. You can use JWT, in that case, the token is secure thanks to the calculated sign (https://www.npmjs.com/package/jsonwebtoken)
    3. Use sticky sessions, in that case each user request will go to same server. NOT recommended

    For step 1 and 2, you can send the token in the http Authorization header