Sub topic 6
Keeping Sessions in a Shared Store
This chapter assumes you know how HTTP cookies work, have built a web service in some language, and understand what a load balancer does. It covers the central session store: what it is, how to build one on Redis, and the errors that most often appear in practice.
The working model
In a shared-store design, the app instances keep no session data in their own memory. The browser holds only a random session ID in a cookie. The data itself lives in a separate server, such as Redis, that every instance can reach.
On each request, the instance reads the ID from the cookie, looks it up in the store, and gets the session data back. Any instance can serve any request, so the load balancer can use plain round-robin and you can add or remove instances freely.
The session ID is the only thing the client holds. The ID is a lookup key, so it must be unguessable. Anyone who learns it can act as that user.
Building it with Redis
The code below has three functions: create, load, and destroy.
import json
import secrets
import redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
SESSION_TTL_SECONDS = 1800
def create_session(user_id: str) -> str:
session_id = secrets.token_urlsafe(32)
r.set(f"session:{session_id}", json.dumps({"user_id": user_id}), ex=SESSION_TTL_SECONDS)
return session_id
def load_session(session_id: str):
key = f"session:{session_id}"
data = r.get(key)
if data is None:
return None
r.expire(key, SESSION_TTL_SECONDS) # sliding expiry
return json.loads(data)
def destroy_session(session_id: str) -> None:
r.delete(f"session:{session_id}")Here is what each part does:
secrets.token_urlsafe(32)draws 32 bytes from the operating system's secure random source. That gives 256 bits of entropy, which is too large to guess. Do not userandomor a counter for IDs.ex=SESSION_TTL_SECONDSsets a time to live (TTL) on the key. Redis deletes the key when the TTL runs out, so idle sessions clean themselves up.r.expire(...)inload_sessionresets the TTL on every read. This is a sliding expiry: a user who stays active stays logged in, and an idle user is logged out after 30 minutes.- The
session:prefix keeps session keys apart from other data in the same Redis database.
The ID travels in a cookie. Set the cookie with these attributes:
Set-Cookie: sid=3q2-7wXk...; Path=/; Max-Age=1800; HttpOnly; Secure; SameSite=LaxHttpOnlystops JavaScript from reading the cookie, which limits what an XSS bug can steal.Securesends the cookie only over HTTPS.SameSite=Laxstops the browser from sending the cookie on most cross-site requests, which reduces CSRF risk.
Common errors
Forgetting the TTL. If you call set without ex, sessions never expire and Redis memory grows until it fills. Always set a TTL at creation. Remember too that expire on an already-deleted key does nothing.
Resetting the TTL on every request without an upper limit. Sliding expiry alone means a session can live forever if the user (or a stolen cookie) keeps making requests. Store a created_at value in the session and reject sessions older than an absolute maximum, such as 12 hours.
Read-modify-write races. Two concurrent requests can each load the session, change it, and write the whole object back. The second write overwrites the first. For fields that change often, use a Redis hash (HSET) so each field updates on its own. You can also keep the session small and treat it as read-mostly.
Storing too much. Every request pays a network round trip to Redis plus the cost of parsing the session. Keep the session to identifiers and a few flags. Load large records from the database when needed.
Reusing an ID across login. If the same ID is kept when a user logs in, an attacker who planted that ID beforehand (session fixation) gains access. Issue a new ID at login and delete the old one. Chapter on rotation covers this in detail.
Treating Redis as durable. By default a Redis restart or failover can lose recent writes. A lost session means the user must log in again. That is acceptable for many systems, but you should decide so on purpose.
Trade-offs at a glance
| Aspect | Shared store |
|---|---|
| Load balancing | Any instance serves any request |
| Revocation | Immediate: delete the key |
| Per-request cost | One store lookup |
| New dependency | Yes. The store must be available |
| Data size on the client | Only the ID |
The extra lookup and the new dependency are the price. In return you get instant logout and revocation, and the client never sees session contents.
Exercise
A user logs in and stays active all day. Your Redis TTL is 30 minutes with sliding expiry. Name one risk of this setup and one fix.
Show answer
Risk: because every request resets the TTL, a session never expires while it is in use, so a stolen cookie that keeps being used stays valid indefinitely. Fix: store a creation timestamp in the session and reject any session older than an absolute maximum (for example 12 hours), forcing a fresh login.
Exercise
Why does create_session use secrets.token_urlsafe(32) instead of an incrementing integer ID?
Show answer
The ID is the only credential that identifies the session. An incrementing integer can be guessed by trying neighbouring values, while 32 random bytes from a secure source have too much entropy to guess.