AI Hints
Home›System Design Tutorial›Healthy, Stateless Servers
System Design · Lesson 30 of 120

Where Sessions Live

Sticky or shared.

⏱ 2 min read▶ Video at 34:16🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

A session remembers who a user is between requests. There are three common places to keep it, and each one has trade offs.

Where Sessions Live
From the video: Where Sessions Live
  • Remember the user
  • Three places
  • Each has trade-offs

Three options

Sticky sessions keep the user on one server, which is simple, but that server becomes special. A shared store, like Redis, holds sessions for all servers, which is flexible, but one more thing to run. And a signed token, like a JWT, carries the session inside the request itself, so servers need no store at all, but it's harder to cancel.

OptionProCon
Sticky sessionssimpleserver becomes special
Shared store (Redis)any server worksone more system
Signed token (JWT)no store neededhard to revoke

A signed token

Here's the idea behind a signed token. The server signs the user's data with a secret key. Later, any server with the same secret can check the signature. Run it. The real token checks out. But if someone changes the user to admin, the signature no longer matches, and we reject it.

token.pypython
import hmac, hashlib

SECRET = b"server-secret"

def sign(data):
    sig = hmac.new(SECRET, data.encode(), hashlib.sha256).hexdigest()[:16]
    return f"{data}.{sig}"

def check(token):
    data, sig = token.rsplit(".", 1)
    return sign(data) == token

token = sign("user=sam")
print(token, "->", check(token))
fake = token.replace("sam", "admin")
print(fake, "->", check(fake))
Output
user=sam.c592aa5efa283fa9 -> True
user=admin.c592aa5efa283fa9 -> False

Summary

Sessions can be sticky, kept in a shared store, or carried in a signed token. Shared stores and tokens keep servers stateless. Next, getting content close to users with a CDN.

Key takeaways
  • Sticky: simple, fragile
  • Shared store: flexible
  • Token: no store
Next up: CDNs — content close to users