Why you need it
Once there are several servers behind a load balancer, your next click may land on a different server from the last one. If the first server kept your login in its own memory, the second has never heard of you. Servers that keep nothing of their own fix this.
Think of it like this
A bank with many counters. Your account is in the bank's shared records, not in the head of the clerk you met last week. Any clerk can help you.
Where you’ll find it
- Heroku: Made this a rule of the Twelve-Factor App: every running copy keeps nothing, and anything that must last goes in a shared store.
- Redis: Is a common shared store for sessions, fast enough to ask on every click.
- AWS: Offers sticky sessions on its load balancer for apps that are not stateless yet.
What to know first
State. Anything a server remembers between requests: who is logged in, what is in a cart, a file someone just uploaded.
Session. The record that says "this visitor is logged in as Ana". Your browser holds only its ID, in a cookie.
How it works
- Spot what the server remembers. Look for anything kept in the server's memory or on its own disk between clicks. In the animation it was the note saying you are logged in.
- Move it to a shared store. Sessions and carts go to a store every server can reach, like Redis or the database. Uploaded files go to shared file storage (see Object storage and direct uploads).
- Or let the visitor carry it. Another way is to give the browser a signed token that holds who you are, so there is nothing to look up. See Sessions vs tokens.
- Sticky sessions are a stopgap. The balancer can always send you to the same server. It works, but load becomes uneven, and when that server dies its visitors are logged out.
- The pay-off. When servers keep nothing, any server can answer anyone. You can add servers at busy times, remove them later, and lose one without anyone noticing. That is what makes Scaling up vs scaling out work.
An example
A shop runs 3 servers. Ana logs in on server 1, which writes her session into its own memory.
Her next click goes to server 2: "please log in". She tries again and lands on server 3. She leaves.
After the fix, server 1 writes the session to Redis. Servers 2 and 3 look it up there in about a millisecond, and Ana stays logged in whichever server answers.
On Friday the shop adds 5 more servers for a sale. They work at once, because none of them needs to remember anything.
Further reading
- The Twelve-Factor App: Processes, Adam Wiggins, Heroku. One short page that made "keep nothing in the server" a standard rule. Start with this one.
- Sticky sessions for your Application Load Balancer, AWS docs. How the stopgap works, so you know what you are giving up.