Sub topic 11
Choosing a Strategy for Your System
This chapter pulls the earlier material together into a decision. It assumes you know HTTP headers and cookies, have built a web service, and understand what a load balancer does. It also assumes you have seen the three places to keep session state: sticky sessions, a shared server-side store, and signed client-side tokens. The goal here is not to crown a winner. It is to give you a repeatable way to pick one for a given system and to know what you are giving up.
Start with the requirements, not the technology
Teams often pick a session strategy by habit ("we always use JWTs" or "just put it in Redis"). A better start is to answer a short list of questions about the system.
- How fast must a session be revocable? If a stolen session must die within seconds, you need a server-side check on each request, or a very short token lifetime.
- How much data does the session hold? A user ID and a role fit in a token. A shopping cart with 200 items or a multi-step form does not.
- How sensitive is that data? A signed token is readable by the client unless you also encrypt it. Anything the user must not see belongs on the server.
- What is the request rate, and what does one extra network hop cost? A store lookup adds a round trip to every request. At very high rates or across regions, that cost matters.
- What happens when state is lost? Losing a session may mean one extra login, or it may mean a lost payment flow.
- How often do you deploy and scale? Frequent rolling deploys and autoscaling punish instance-local state.
- Who calls the service? Browsers work well with cookies. Mobile apps, other services and third parties often use bearer tokens in a header.
The answers usually point to one approach quickly. The rest of the chapter explains why.
The three approaches side by side
| Property | Sticky sessions | Shared server-side store | Signed client-side token |
|---|---|---|---|
| Where state lives | In one instance's memory | In Redis or a database | In the token held by the client |
| Extra work per request | None | One store lookup | Signature check (CPU only) |
| Instance can be killed freely | No, its sessions are lost | Yes | Yes |
| Revoke one session now | Easy, if you can reach that instance | Easy, delete the key | Hard, needs a denylist or short lifetime |
| Session size limit | Instance memory | Store memory, practical limits per key | Cookie and header limits, roughly 4 KB for a cookie |
| New moving part | Load balancer affinity setting | A highly available store | Key management and rotation |
| Main failure mode | Instance loss or uneven load | Store outage or latency | Stolen or stale tokens stay valid until expiry |
Sticky sessions
Sticky sessions (session affinity) make the load balancer send a client to the same instance every time, usually by hashing the client IP or by setting its own cookie. The application keeps sessions in local memory and needs no other change.
Use them when you have a legacy application that you cannot change in the near term, a small fixed fleet, and users who can tolerate an occasional forced re-login. Treat them as a bridge, not a destination.
Their limits are concrete:
- When an instance dies or is replaced in a deploy, every session on it is gone.
- Load becomes uneven. A few heavy users, or many users behind one corporate NAT address, can pin one instance while others idle.
- Autoscaling adds capacity, but existing users stay on their old instances, so new instances stay underused until new sessions arrive.
- Failover is not transparent. The service looks stateless to the load balancer but is not.
Shared server-side store
Here the cookie holds only a random session ID, and the data lives in a store such as Redis. Any instance can serve any request. This is the default choice for most browser-based applications because it keeps the server in control.
Its strengths are immediate revocation, small cookies, and the ability to keep sensitive data off the client. Its costs are an extra dependency in the request path and a lookup on every request. Because the store sits on the critical path, its availability becomes your availability. Plan for that explicitly (see the failure section below).
Signed client-side token
The server signs the session data and gives it to the client, which sends it back each time. Any instance holding the key can verify it with no lookup. This removes the store from the request path and suits APIs, microservices that pass identity between each other, and systems spread over several regions.
The cost is revocation. A valid token stays valid until it expires, because no server remembers it. You also cannot change the contents without issuing a new token, and the payload is visible to the client unless encrypted. Signing proves the data was not altered. It does not hide it.
Decision flow
The flow below captures the questions that usually decide the outcome. Real systems add exceptions, but this order is a good default.
Worked scenarios
Scenario 1: A browser-based admin dashboard
Users log in with a password and MFA. Sessions hold the user ID, roles and a CSRF token. Security staff must be able to end a session immediately when an account is compromised. Traffic is modest.
The shared store fits. The cookie carries only an opaque ID, and revocation is a single DELETE. The extra lookup is cheap at this volume. Set the cookie with HttpOnly, Secure and SameSite=Lax, and rotate the ID at login.
Scenario 2: A public API consumed by mobile apps and partners
Clients are not browsers, so cookies are awkward. Each request carries an Authorization header. The service runs in three regions, and a central store would add cross-region latency.
Short-lived signed tokens fit. Make access tokens live 5 to 15 minutes. Pair them with a refresh token that is stored server-side, so the refresh step can check whether the account is still in good standing. This limits the damage window without a lookup on every call.
Scenario 3: A legacy monolith with in-memory sessions
The application keeps a large object graph in memory and is hard to change. The team wants rolling deploys.
Start with sticky sessions to unblock scaling. Plan the migration in parallel: move session data into a store behind the framework's session interface, if it has one. Many frameworks let you swap the session backend through configuration. Then remove affinity.
Scenario 4: An e-commerce site
Login state is small, but the cart is large and valuable, and losing it costs sales. A hybrid fits. Use a store-backed session for login. Persist the cart in a database keyed by user or session ID, since it has to outlive a session anyway. Do not put the cart in a token.
Hybrids are normal
Real systems mix approaches. Common combinations:
- Short access token plus server-side refresh token. Most requests verify a signature only. Every few minutes the client refreshes, and that step consults the server, where you can deny it.
- Signed token plus small denylist. Store only the IDs of revoked tokens, and only until their natural expiry. The denylist is tiny compared with a full session store, but it puts a lookup back on the request path, so keep it fast, for example with a local cache refreshed every few seconds.
- Store with a local cache. Cache decoded sessions in the instance for a few seconds to cut lookups. This trades revocation speed for load: a revoked session may live as long as the cache TTL.
- Opaque ID at the edge, token inside. A gateway looks up the session once and passes a short-lived signed internal token to downstream services, so they never touch the store.
Each hybrid buys back one weakness of a pure approach and adds complexity somewhere else. Add one only when a requirement forces it.
Plan for failure before you choose
The strategy decides what a failure looks like, so evaluate it at selection time.
For a shared store, decide what the application does when a lookup fails or times out. The choices are:
- Fail closed: treat the user as logged out or return an error. This is safe and is the right default for anything sensitive.
- Fail open: serve limited, read-only or public content without a session. Do this only for features where no identity is needed.
Never treat a store error as "valid session". Also set short client timeouts on the store, so a slow store does not tie up every worker thread. Add a circuit breaker so requests fail fast during an outage, and run the store with replication and automatic failover. Decide whether sessions may be lost on failover. Redis replication is asynchronous by default, so a failover can drop the most recent writes, and persistence settings affect what survives a restart.
For tokens, the risk is on the other side. The store cannot fail, but the signing key can leak or be lost. Support more than one active key, identified by a key ID in the token, so you can rotate keys without logging everyone out. Have a plan for emergency rotation, which invalidates all tokens at once.
For sticky sessions, the failure is the loss of an instance. Accept that the users on it must log in again, and make sure the application handles the missing session gracefully with a redirect to login instead of an exception.
Common mistakes
- Choosing tokens to avoid running a store, then needing revocation. Teams discover the gap after an incident. If you need "log out everywhere" or "ban this user now", decide how before launch.
- Putting sensitive data in an unencrypted token. Anyone can base64-decode the payload. Keep secrets on the server.
- Storing large or fast-changing data in a token. Every change needs a new token, and the whole token travels with every request.
- Sticky sessions with no fallback. The load balancer may route elsewhere during failover, and the application then breaks instead of asking the user to sign in.
- Skipping expiry on the store side. Sessions without a TTL accumulate until memory runs out. Set a TTL on every key, as in the earlier
create_sessionexample. - Trusting the token's own claims about the algorithm. Verify with a fixed algorithm and key chosen by the server, as the earlier
verifyfunction does with HMAC-SHA256. - Forgetting session ID rotation. Issue a new ID at login and at privilege changes, which prevents session fixation.
A quick checklist
Before you commit to a design, check that you can answer each of these in one sentence:
- What happens to a user's session when one instance is killed during a deploy?
- How long does it take to end a stolen session?
- What is the largest session, and where does it live?
- What does the application do if the session store, or the signing key, is unavailable?
- How do we rotate secrets without logging everyone out?
- What is the cookie or header carrying, and who can read it?
If any answer is "we haven't decided", that is the next piece of design work, and it is usually cheaper to settle it now than after an incident.
Exercise
A team runs a banking web application used from browsers. Security requires that a compromised account's sessions be terminated within seconds. Sessions hold a user ID and a CSRF token. Traffic is a few hundred requests per second in one region. Which strategy do you pick, and what do you do when the session store is unreachable?
Show answer
Use a shared server-side store (for example Redis) with an opaque session ID in a cookie marked HttpOnly, Secure and SameSite=Lax. Revocation is a key deletion, so it takes effect on the next request, which meets the "within seconds" requirement. A few hundred requests per second makes one lookup per request affordable in a single region. When the store is unreachable, fail closed: treat the request as unauthenticated or return an error, never as a valid session. Use short store timeouts and a circuit breaker so slow lookups do not exhaust workers, and run the store with replication and automatic failover.
Exercise
A public API is served from three regions to mobile clients. The team wants no per-request store lookup, but also wants to be able to cut off a misbehaving client within about ten minutes. Describe a design that satisfies both.
Show answer
Issue short-lived signed access tokens that expire in about 10 minutes or less, and pair them with a refresh token stored server-side. Requests verify only the signature and expiry, so there is no lookup on each call. To cut off a client, revoke its refresh token. The client can then not obtain a new access token, and the existing one expires within the 10-minute window. If faster cutoff is needed for specific cases, add a small denylist of revoked token IDs that expires entries at the token's natural expiry.
Exercise
A legacy application keeps sessions in instance memory behind sticky sessions. During each rolling deploy, users are logged out. Name two reasons sticky sessions cause this, and one migration step that fixes it.
Show answer
First, each session exists only in the memory of one instance, so when that instance is stopped and replaced, its sessions are lost. Second, the load balancer's affinity cannot move a session to another instance, because the other instances never had its data. The fix is to move session data into a shared store, for example by switching the framework's session backend to Redis, and then remove affinity.