Stateless services and sessions

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

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

  1. 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.
  2. 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).
  3. 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.
  4. 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.
  5. 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