GotchaDifficulty: Intermediate1 min

Sessions in Server Memory

The next request lands on another server, and the user is suddenly logged out.

A session kept in one application server's memory ties its user to that server. Once there are several servers behind a load balancer, a request that lands on a different one finds no session, and the user appears logged out. The fix is to keep sessions where every server can read them.

The symptom. The team adds a third server to cope with growth. Within the hour, support hears that users are being logged out at random, and that baskets empty between pages. Nothing in the logs shows an error.

Two requests from one user, two servers

The trigger. The framework's default session store keeps sessions in the process's memory. With one server, every request found it. With two, the load balancer happened to be configured to keep each client on one server, and the problem stayed hidden; the new server was added without that setting.

The mechanism. The cookie carries only the session's id. The data behind it exists on server A alone. Server C receives a valid id it has never seen, treats it as no session, and asks the user to sign in.

The cost. Users lose their place and their basket, and every restart or redeploy logs out everyone on the restarted server.

The remedy. Move sessions to a shared store every server reads, such as Redis or the database. Or put the session in a signed token the client carries, which any server can check without a lookup. Sticky sessions, which pin each user to one server, hide the problem without fixing it: when that server goes, its users are logged out anyway.

So before adding a second server, find every place a server keeps a user's state in its own memory, and move it out.