Sub topic 6
Keeping Sessions in a Shared Store
This chapter assumes you know how HTTP cookies work, have built a web service or API in some language, and know what a load balancer does. It also assumes you have read the earlier chapters on stateless services, session state and sticky sessions.
A shared session store moves session data out of the app instances and into one service that all instances can reach. The browser holds only an opaque identifier. Each instance looks the data up by that identifier on every request. Any instance can serve any request, so the instances stay stateless.
The working model
A session ID is a random string. The server uses it as a key into a store, usually an in-memory key-value database such as Redis or Memcached. The value is the session data, for example the user ID and a few flags.
The cookie carries no meaning by itself. If an attacker guesses a valid ID, they become that user. That has two consequences for how you build it:
- The ID must come from a cryptographically secure random generator and have enough entropy. 32 random bytes (256 bits) is plenty.
- The ID must never be derived from user data, a counter, or a timestamp.
A minimal implementation
The code below creates, loads, and destroys sessions in Redis. It assumes a Redis server on localhost and the redis Python package.
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}")Points worth noting in this code:
secrets.token_urlsafe(32)uses the operating system's secure random source. Do not userandomfor this.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.load_sessioncallsexpireafter a successful read. This makes the expiry sliding: each request pushes the deadline out by another 30 minutes.- The
session:prefix keeps session keys separate from other data in the same Redis database, and lets you scan or monitor them by pattern. destroy_sessionis how logout works. Deleting the key ends the session on every instance at once.
The value is stored as JSON. This keeps the data readable by every language and version of your services. Avoid language-specific binary formats such as Python's pickle. A tampered or old pickle can run code or fail to load after a deploy.
Setting the cookie
The server sends the session ID to the browser in a cookie. The cookie's attributes decide who can read it and when the browser sends it.
Set-Cookie: sid=3q2-7wXk...; Path=/; Max-Age=1800; HttpOnly; Secure; SameSite=Lax| Attribute | Effect | Why it matters here |
|---|---|---|
| `HttpOnly` | Scripts cannot read the cookie through `document.cookie` | Limits theft of the ID by cross-site scripting (XSS) |
| `Secure` | Browser sends it only over HTTPS | Prevents sniffing on plain HTTP |
| `SameSite=Lax` | Not sent on most cross-site subrequests | Reduces cross-site request forgery (CSRF) risk |
| `Max-Age=1800` | Browser discards it after 30 minutes | Should match the store TTL |
| `Path=/` | Sent for every path on the site | Needed if all routes use the session |
SameSite=Lax is a partial CSRF defense. State-changing endpoints should still use CSRF tokens or equivalent checks.
Because the sliding expiry extends the TTL in Redis, your server should also re-send Set-Cookie with a fresh Max-Age when it refreshes the session. If it does not, the browser may drop the cookie while the store still holds the session.
What to store, and what to leave out
Keep the session small. Typical contents are a user ID, a role or permission set, a CSRF token, and a few short-lived flags such as a multi-step form position.
Leave out:
- Large objects, such as full shopping cart contents with product details. Store the cart in a database and keep only its ID in the session.
- Data that other systems also change. A cached copy of a user's role in the session goes stale when an administrator changes the role. Either store the user ID and look the role up, or accept a bounded delay and keep the TTL short.
- Secrets that you do not need, such as raw passwords. Never store these.
Every request pays for the session read, so small values keep latency and network use low. A value of a few hundred bytes is typical.
Concurrency and race conditions
Two requests from the same browser can arrive at different instances at the same time. Both read the session, change it, and write it back. The second write overwrites the first, and one change is lost.
Options for handling this:
- Store only data that rarely changes, such as the user ID, and write it once at login.
- Use Redis hashes and update single fields with
HSET, so unrelated changes do not overwrite each other. - Use optimistic locking with
WATCH/MULTI/EXECwhen a read-modify-write must be atomic. - Move fast-changing data, such as counters, into its own key with atomic commands like
INCR.
Most applications avoid the problem by keeping the session close to read-only after login.
Choosing and configuring the store
| Store | Strengths | Limits |
|---|---|---|
| Redis | Native TTL, rich data types, replication, optional persistence | One more service to run and secure |
| Memcached | Simple, fast, easy to scale out | No persistence, no replication in the core product, a node loss drops its sessions |
| SQL database | Already present, durable | Higher latency, you must delete expired rows yourself |
| Managed cache (for example Amazon ElastiCache or DynamoDB with TTL) | Operated for you | Cost, network distance, vendor features |
For most web applications Redis is the default. Settings that matter:
- Eviction policy. If Redis runs out of memory and uses
allkeys-lru, it can evict live sessions to make room, and users get logged out for no visible reason. For a dedicated session instance, prefervolatile-ttlorvolatile-lruand size memory so that evictions are rare. Alert on theevicted_keysmetric. - Persistence. With no persistence, a Redis restart logs everyone out. With append-only file (AOF) persistence, most sessions survive. Decide whether a mass logout is acceptable.
- Replication. A replica lets you fail over when the primary dies. Replication is asynchronous, so a failover can lose the last few writes, such as a session created a moment before the crash.
- Network security. Put Redis in a private network, require authentication, and enable TLS if traffic crosses hosts. Session data is a high-value target, because anyone who can read the keys can impersonate any user.
Expiry choices
There are two kinds of lifetime, and you usually want both:
- Idle timeout. The session ends after a period of no requests. The sliding
expirecall above implements it. - Absolute timeout. The session ends a fixed time after login, no matter how active the user is. Store a
created_atvalue in the session and check it on each load.
Sliding expiry alone lets a stolen ID live forever as long as it is used regularly. An absolute limit, such as 12 hours, bounds that risk. The next chapters cover rotation and revocation in more detail, but the store gives you two useful abilities already. You can delete one session to log out a device. You can also delete every key that belongs to a user, if you keep an index such as a Redis set user_sessions:42 that lists that user's session IDs.
Costs and trade-offs
A shared store has real advantages:
- Any instance can handle any request, so load balancing needs no affinity.
- Instances can be added, removed, or replaced during a deploy without logging anyone out.
- You can revoke a session immediately, because the server controls the data.
- Session contents never reach the client, so users cannot read or change them.
It also has costs:
- Every authenticated request makes a network call to the store. Typical latency is under a millisecond to a few milliseconds in the same data center, but it adds up.
- The store is a new dependency. If it is down, nobody can use authenticated features.
- You must operate, secure, monitor, and size it.
The failure side of this trade-off gets its own chapter. For now, remember that the store sits on the critical path of every logged-in request.
Common errors
- Using a predictable ID. Sequential numbers or hashes of the user ID can be guessed. Use
secretsor the equivalent in your language. - Reusing the ID across login. If the ID stays the same before and after login, an attacker who planted a known ID in the victim's browser (session fixation) gains the authenticated session. Issue a new ID when the privilege level changes.
- Setting the store TTL but not the cookie lifetime, or the reverse. The two should agree.
- Forgetting to handle
None.load_sessionreturnsNonefor missing or expired sessions. Treat that as "not logged in", not as an error. - Holding a local cache of sessions in each instance. That reintroduces instance-local state, and revocation stops working on instances that still hold a copy.
- Storing too much. Large values slow every request and fill memory.
Summary
A shared store keeps the app instances stateless by putting session data in one place that all of them read. The browser holds a random ID in a hardened cookie. Expiry comes from the key's TTL. The price is an extra network hop per request and a dependency you must keep healthy.
Exercise
Your Redis session store uses the allkeys-lru eviction policy. During a traffic spike, users report being logged out at random while their cookies are still valid. What is the likely cause, and what two changes would you make?
Show answer
Redis ran short of memory and evicted live session keys, because allkeys-lru can remove any key, including sessions that have not expired. The cookie is still valid, but the key it points to is gone, so load_session returns None. Change the policy to volatile-lru or volatile-ttl, so only keys with a TTL are candidates, and increase the memory or reduce the session size so evictions are rare. Also alert on the evicted_keys metric.
Exercise
A user logs in on a shared computer, and the app keeps the same session ID before and after login. Name the attack this allows and how to prevent it.
Show answer
This allows session fixation. An attacker who set a known ID in the browser before login can use that same ID afterwards, once the victim has authenticated. Prevent it by creating a new session ID at login, copying over any data you need, and deleting the old key.