Sub topic 11
Choosing a strategy for your system
This chapter assumes you know HTTP headers and cookies, have built a web service, and understand what a load balancer does. It also assumes you have read the earlier chapters on sticky sessions, a shared session store, signed tokens, session lifecycle and store failure modes. Here you put those pieces together and make a decision.
The three options in one view
Every approach answers one question: where does the session data live between requests?
| Approach | Where state lives | Main strength | Main cost |
|---|---|---|---|
| Sticky sessions | In one instance's memory | No extra infrastructure | Lost on restart, crash or scale-in. Uneven load. |
| Shared session store | In Redis or a similar store | Instant revocation, small cookie | Extra dependency on every request |
| Signed client-side token | In the token the client holds | No lookup, any instance can verify | Hard to revoke, size limits, secret management |
Decision criteria
Work through these questions in order. Each one removes options.
- Can you lose a session when an instance disappears? If not, rule out sticky sessions as the only mechanism. Rolling deploys, autoscaling and crashes all drop instances.
- Must you end a session immediately? Examples are a stolen device, a fired employee, or a password change. A shared store deletes the key and the session is gone. A signed token stays valid until it expires unless you add a denylist, and a denylist is a shared store again.
- How much data does a session hold? Cookies are limited to about 4 KB. A large session, such as a shopping cart with many items, belongs in a store.
- Does the data change on the server? A token is a snapshot. If permissions change, the token carries the old values until it expires or is reissued.
- Is the data sensitive? A signed token is readable by anyone who holds it, because signing is not encryption. If the client must not see the contents, keep them in a store or encrypt the token.
- How many services verify the session? If many services must check identity and you do not want each one to call a central store, a signed token fits well.
Common combinations
Real systems rarely use one approach in its pure form.
- Session ID cookie plus shared store. This is the default for most web applications. The cookie holds a random ID and nothing else. The store holds the data and applies the TTL. Set
HttpOnly,SecureandSameSite=Laxon the cookie. - Short-lived access token plus refresh token. The access token is signed and lives for about 15 minutes, so services verify it without a lookup. The refresh token is stored server-side, so you can revoke it. Revocation then takes effect within the access token's lifetime.
- Sticky sessions as a bridge. If a legacy application keeps sessions in memory, stickiness lets you scale out now. Plan the move to a store, and do not treat stickiness as the final design.
Planning for failure
Choose the failure behavior before you launch, not during an outage.
- Store unavailable. Decide whether requests fail closed (return an error or force login) or degrade (serve public pages). Authenticated actions should fail closed.
- Store slow. Set a short timeout on session reads, such as 50 to 100 ms. A slow store with no timeout ties up every worker and turns a store problem into a full outage.
- Store restart without persistence. All users are signed out. If that is unacceptable, enable persistence or replication, and test the failover.
- Secret leaked or rotated (tokens). Anyone with the signing secret can forge tokens. Support more than one active key so you can rotate without logging everyone out.
Worked example
Suppose you run an e-commerce site on six instances behind a load balancer. Requirements:
- Deploys happen several times a day.
- Support staff must be able to sign out a compromised account at once.
- A cart can hold dozens of items.
- A separate image-resizing service needs to know who the caller is.
Apply the criteria. Frequent deploys rule out sticky sessions alone. Immediate sign-out rules out a pure signed token. The cart size rules out cookie storage. The result is a shared store holding the session and cart, with a random ID in a secure cookie. For the image service, issue a signed token with a 5-minute expiry that carries only the user ID, so it can verify the caller without calling the store. Set a 100 ms timeout on store reads. Fail closed for checkout, and let anonymous browsing continue if the store is down.
import redis
r = redis.Redis(
host="localhost",
port=6379,
decode_responses=True,
socket_timeout=0.1, # fail fast instead of hanging workers
socket_connect_timeout=0.1,
)
def load_session_or_none(session_id: str):
try:
return r.get(f"session:{session_id}")
except redis.exceptions.RedisError:
return None # caller treats this as "not signed in" and fails closedThe None result here means the caller must not grant access. Returning None for both "missing" and "store down" is acceptable only because every caller fails closed.
Common mistakes
- Using a signed token for everything, then discovering you cannot log out a stolen session.
- Putting roles in a long-lived token. Role changes then take effect only when the token expires.
- Leaving the store with no timeout, so a slow store stalls all workers.
- Keeping sticky sessions "temporarily" for years.
Exercise
A team runs a banking app on eight instances. Compliance requires that a customer's session can be ended within seconds of a fraud alert. Sessions hold a small amount of data. Which strategy fits best, and what would you add if another internal service also needs to verify callers cheaply?
Show answer
Use a shared server-side session store with a random ID in a HttpOnly, Secure, SameSite cookie, because deleting the key ends the session immediately. For the internal service, add a short-lived signed token (a few minutes) carrying only the user ID, so it verifies without a store lookup. A fraud revocation then takes full effect within that token's lifetime, and the store entry is removed at once.
Exercise
Your service stores sessions in Redis with no client timeout. Redis becomes slow, and the whole site stops responding even though the app instances are healthy. Why, and what two changes address it?
Show answer
Each request waits on the slow Redis call, so workers fill up and no capacity remains for other requests. Set a short socket timeout (for example 100 ms) on session reads, and define a fail-closed behavior on timeout, such as treating the user as signed out for protected actions while still serving public pages.