You add a second server behind a load balancer to handle more traffic, and suddenly users complain that they're logged out at random, their shopping carts empty themselves, and uploaded photos sometimes "disappear". Nothing is wrong with the new server. The problem is that your servers are stateful: each one remembers things the others don't.
This lesson explains the difference between stateful and stateless servers, the two standard ways to handle logins (shared session storage and tokens), and how to deal with other kinds of state such as uploaded files.
What is "state"?
State is anything the server remembers between requests: who's logged in, what's in a cart, a half-finished upload, a file saved to the server's disk.
- A stateful server keeps that information on itself, in its memory or on its local disk.
- A stateless server keeps nothing between requests. Every request carries, or points to, everything needed to handle it. The data itself lives in shared places: a database, a cache, or file storage.
An everyday example: a restaurant where each waiter remembers their own tables' orders in their head is stateful. If your waiter goes home, nobody knows your order. A restaurant where every order is written on a ticket hung in the kitchen is stateless: any waiter can serve any table.
Why stateful servers break when you scale
Here's a typical beginner Flask app. It stores the logged-in user in a Python dictionary in the server's memory:
import secrets
def make_random_id():
return secrets.token_urlsafe(16)
sessions = {} # session id -> username, kept in THIS server's memory
def login(username):
session_id = make_random_id()
sessions[session_id] = username
return session_id # sent to the browser as a cookie
def current_user(session_id):
return sessions.get(session_id) # None on any other server!
With one server, it works. With two behind a load balancer:
- You log in. The request goes to server A, which stores your session in its memory.
- Your next request goes to server B. B's dictionary is empty, so you're "not logged in".
It gets worse: restarting a server, or deploying new code, wipes its memory and logs everyone out. And if an autoscaler removes server A, all of its users lose their sessions.
The fix is to make the app servers stateless, which is what makes horizontal scaling and autoscaling possible.
Fix 1: store sessions in a shared store
Keep the session ID in a cookie, as before, but store the session data in a fast shared store that every server can reach, typically Redis. (To try this, run pip install redis and start a Redis server.)
import redis
store = redis.Redis(host="sessions.internal", port=6379)
def login(username):
session_id = make_random_id()
store.set(f"session:{session_id}", username, ex=7 * 24 * 3600) # expires in 7 days
return session_id
def current_user(session_id):
value = store.get(f"session:{session_id}")
return value.decode() if value else None
Now any server can look up any session. Redis lookups take well under a millisecond, and ex= makes old sessions expire automatically. Logging out, or logging a user out of every device, is just deleting their keys.
Web frameworks support this out of the box: Django can store sessions in a cache or database, and Express has Redis session stores.
Fix 2: put the data in a signed token (JWT)
Instead of storing the session on the server, give the client a token that contains the information itself, signed by the server so it can't be forged. The most common format is the JWT (JSON Web Token).
A JWT has three parts separated by dots: a header, a payload such as {"user_id": 7, "role": "student", "exp": 1767312000}, and a signature. The client sends it with every request:
GET /orders
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo3fQ.4fK...
Any server with the secret key can verify the signature and read the user ID, without looking anything up. That's fully stateless.
The payload is encoded, not encrypted: anyone can read it, so never put secrets in it.
Sessions in Redis or JWT?
| Shared session store | JWT | |
|---|---|---|
| Where the data lives | Server side (Redis) | Inside the token, on the client |
| Lookup per request | One fast Redis read | None, just a signature check |
| Log a user out right now | Easy: delete the session | Hard: the token is valid until it expires |
| Token size | A short random ID | Larger, sent with every request |
| Best for | Websites, apps needing instant logout | APIs, mobile apps, communication between services |
A common middle ground: short-lived JWT access tokens (for example 15 minutes) plus a longer-lived refresh token stored on the server, so you can still revoke access within minutes.
Other kinds of state
Sessions are the most common state, but not the only one.
| State | Stateful mistake | Stateless fix |
|---|---|---|
| Uploaded files | Saved to the server's own disk | Object storage such as Amazon S3; save the file's URL in the database |
| Shopping cart | In server memory | In the database, or Redis for guests |
| Cached data | Separate cache in each server's memory | A shared cache (Redis), or accept that local caches differ |
| Scheduled jobs | A timer running inside one server | A separate job runner or queue, so jobs don't run twice |
| WebSocket connections | Naturally tied to one server | Route messages between servers with a pub/sub system |
The goal is that any server can be killed at any moment and no user notices. That's the test of a truly stateless design.
Stateless doesn't mean "no state anywhere"
The state still exists. It has just moved out of the app servers into systems designed to keep it safe and shared: databases, caches and object storage. Those systems are harder to scale, which is why the database is usually the hardest part of scaling a system, as discussed in vertical vs horizontal scaling.
Practice
- Your app saves profile photos to
/var/www/uploadson the server. After adding a second server, some photos show as broken. Why, and how do you fix it?
Show the answer
Each photo exists only on the server that received the upload; requests reaching the other server can't find it. Store uploads in shared object storage (like S3) and save the URL in the database. Serving them through a CDN is a bonus.
- A company uses JWTs that last 30 days. An employee leaves and must lose access immediately. What's the problem, and what are the options?
Show the answer
JWTs stay valid until they expire, and servers don't look anything up, so the token keeps working. Options: short-lived access tokens with server-side refresh tokens that can be revoked, a deny-list of revoked token IDs checked on each request, or server-side sessions.
- Is a server that reads user data from a shared database on every request stateful or stateless?
Show the answer
Stateless. It keeps nothing between requests; the state lives in the database, which every server shares.
Interview questions
What is a stateless server?
A server that keeps no client-specific data between requests; each request contains, or references, everything needed, and persistent state lives in shared stores. Any instance can handle any request, which makes horizontal scaling, failover and deploys simple.
How do you manage user sessions across many servers?
Store session data in a shared, fast store such as Redis keyed by a session ID cookie, or use signed tokens like JWTs that carry the identity. Sticky sessions are a workaround, not a solution.
What are the trade-offs of JWTs?
They're stateless and need no lookup, which suits APIs and microservices. But they can't easily be revoked before expiry, they're larger than session IDs, and their payload is readable, so it mustn't contain secrets.
What to learn next
- Serve static files from near your users with a CDN.
- Protect your stateless servers from overload with rate limiting.