Sub topic 9
When the Session Store Fails or Slows Down
This chapter assumes you know how a shared session store works (see the earlier chapter on keeping sessions in a shared store), how session cookies carry an ID, and what a load balancer does. Here you will look at what happens when the store is unavailable or slow, and how to design for it.
Why the store is a critical dependency
With a shared store, every request that needs a session reads from it. The app instances are stateless, but the store is not. If it fails, every instance fails together. Adding more app instances does not help.
Failure shows up in two forms:
- Down: connections are refused or time out. Requests that need a session cannot be served.
- Slow: the store still answers, but late. This is often worse. Request threads wait on the store, the worker pool fills up, and the whole service stalls, even routes that barely use sessions.
Set timeouts first
Most outages begin with a client that waits forever. Set a short connect timeout and a short read timeout on the store client. A session lookup is a single key read, so it normally takes a few milliseconds. A limit of 50 to 200 ms is a reasonable starting point. Tune it against your measured p99 latency.
import redis
r = redis.Redis(
host="localhost",
port=6379,
decode_responses=True,
socket_connect_timeout=0.1, # seconds to open a connection
socket_timeout=0.2, # seconds to wait for a reply
)Also cap the connection pool so a slow store cannot make your app open unlimited connections.
Decide what happens on failure
When a lookup fails, you must pick a behavior. There are two basic choices.
| Policy | Behavior | Risk |
|---|---|---|
| Fail closed | Treat the user as not authenticated, or return an error | Users are locked out during the outage |
| Fail open | Let the request through without checking the session | Anyone can reach protected data |
For authentication, fail closed. Never treat "I could not check" as "the session is valid". You can still degrade gracefully in a narrow way:
- Serve public pages as an anonymous user.
- Return
503 Service Unavailablewith aRetry-Afterheader for routes that need a login. - Do not clear the user's cookie on a store error. The session may still exist in the store, and deleting the cookie would log out users who did nothing wrong.
The code below separates "no session" from "store unavailable". The caller can then respond differently to each.
import json
import redis
class StoreUnavailable(Exception):
pass
def load_session(r: redis.Redis, session_id: str):
try:
data = r.get(f"session:{session_id}")
except (redis.ConnectionError, redis.TimeoutError) as exc:
raise StoreUnavailable from exc
if data is None:
return None # session does not exist or has expired
return json.loads(data)A handler catches StoreUnavailable and returns 503. It treats a None result as a normal logged-out user. Mixing the two cases is a common bug. It either logs everyone out during a blip or lets everyone in.
Contain the damage
Several techniques limit how far a store problem spreads.
- Circuit breaker. After a number of consecutive failures, stop calling the store for a short period and fail immediately. This frees request threads and gives the store room to recover. Probe it again after the pause.
- Short local cache. Cache a validated session in the instance's memory for a few seconds. This absorbs brief outages and reduces load. The cost is that a revoked session may stay valid for those few seconds, so keep the time short and use it only if that is acceptable.
- Retry with limits. Retry once, with a small random delay. Unbounded retries during an outage multiply the load on a store that is already struggling.
- Avoid needless lookups. Do not load sessions for routes that do not need them, such as static files and health checks.
Make the store itself resilient
On the store side, you can reduce the chance and impact of failure.
- Replication with automatic failover. Run a replica and promote it if the primary fails. Failover takes seconds, and writes made just before the failure may be lost, because replication is usually asynchronous.
- Persistence settings. An in-memory store that restarts empty logs everyone out. Decide whether that is acceptable. If not, enable persistence, and accept the extra write cost.
- Capacity and eviction. If memory fills up and the store evicts keys, active sessions can disappear. Size the store for peak sessions and watch memory use.
- Monitoring. Track lookup latency (p50 and p99), error rate, connection count, and memory use. Alert on rising latency before it becomes an outage.
How the other approaches compare
Client-side signed tokens do not depend on a store for verification, so a store outage does not break them. The trade-off is that revocation usually needs a lookup, such as a denylist. If you add a denylist, you reintroduce the same failure question: fail open (accept a possibly revoked token) or fail closed. Sticky sessions keep data in instance memory, so there is no store to fail. The failure there is an instance dying and taking its sessions with it.
Exercise
Your session store becomes slow, and the app's request threads begin to pile up. Name two changes that would limit the damage, and say what the app should do for a route that requires login when the lookup times out.
Show answer
Set short connect and read timeouts on the store client, and add a circuit breaker (a small retry limit or a short local cache also helps). For a route that requires login, fail closed: return 503 with a Retry-After header. Do not treat the user as authenticated, and do not delete their cookie.
Exercise
Why is it a mistake to have the load balancer health check call an endpoint that reads from the session store?
Show answer
When the store fails, every instance fails the check and the load balancer removes all of them. The service stays down even after the store recovers, and instances that could have served public pages are taken out as well.