System Design · 02. Scaling · 8 min · Beginner

Stateless Services

Keep no user data on the server, so any server can answer any request.

In short

A stateful server pins users to itself, so a restart logs them out and scaling is awkward. A stateless server keeps its state in a shared store or in the user's token.

Then any server can serve any request. Deploys, crashes and autoscaling cost no one a login, and 1,000 users on each of three servers can become 600 on each of five.

Key ideas

  • State is anything the server must remember between two requests. A server that remembers it is called stateful. (step 1)
  • Stateless does not mean the system has no state. It means the app servers do not hold it. (step 4)

Good to know

  • Rolling deploys, crashes and replacements all become routine, because no single server is special. (step 7)

Watch out

  • Sticky sessions hide the problem. The load gets uneven, and the sessions are still stuck on one machine. (step 2)
  • You cannot deploy, scale in or lose a machine without hurting real users. That is the cost of state in memory. (step 3)
  • The store is now a shared part. If it dies, everyone is logged out, so run it with a replica and failover. (step 5)
  • Store: easy to log someone out, one extra lookup per request. Token: no lookup, but hard to revoke early. (step 6)
  • Check for hidden state too: files saved on the local disk, in-process caches that must agree, and open WebSocket connections. (step 8)
UsersServer 4Load balancerServer 1Server 2Server 3Session store (Redis)Server 5

Key numbers

Logged-out users
0
Servers up
5 of 5

Terms

Session
A small server-side record of who is logged in, found by an id that the browser sends in a cookie.
Stateful server
A server that remembers data about users between requests.
Sticky session
The load balancer always sends a user to the same server, so that server's memory can hold the session.
Stateless service
A server that keeps nothing about users between requests, so any server can answer any request.
Session store
A shared fast store, such as Redis, where every server reads and writes sessions.
Signed token (JWT)
A user-carried record signed with a secret key, so the server can trust it without a lookup.
Token revocation
Cancelling a token before it expires, which is hard because the server keeps no record of it.
Autoscaling
Starting and stopping servers automatically as load changes, which is safe when they are stateless.