Sub topic 9
When the Session Store Fails or Slows Down
A shared session store removes state from your app instances, but it adds a dependency that every authenticated request must call. This chapter covers how that dependency fails and how to limit the damage.
It assumes you have read the chapters on the shared server-side store and on session lifecycle. You should be comfortable with HTTP status codes and with basic Redis operations such as GET, SET and EXPIRE.
The store sits on the critical path
With a shared store, a typical authenticated request does this:
- Read the session ID from the cookie.
- Call the store to load the session.
- Run the business logic.
If step 2 fails, steps 3 and beyond cannot run safely. Your service is only as available as the store, even if you run fifty app instances. Sticky sessions and signed tokens do not have this problem for ordinary requests, which is part of why they remain attractive. Revocation checks reintroduce it for tokens.
The goal is not to make the store never fail. It is to decide in advance what each request does when the store fails, and to stop a store problem from spreading into an outage of the whole service.
How a session store fails
Not all failures look like "the server is down." The table lists the common ones.
| Failure | What the app sees | Typical effect |
|---|---|---|
| Store unreachable (crash, network partition) | Connection errors, fast | Requests that need a session fail |
| Store slow (overload, big keys, disk stalls, a failover in progress) | Requests that hang until a timeout | Worker threads pile up, whole app stalls |
| Store restarted empty | `GET` returns nothing for every key | Every user appears logged out |
| Failover to a replica that was behind | Recent sessions missing | Users who just logged in are logged out |
| Memory full, keys evicted | Random sessions missing | Users logged out early and unpredictably |
| Memory full, writes refused | Errors on `SET` only | Logins fail, existing sessions still work |
Two of these are easy to mistake for normal behavior. A missing key looks the same as an expired session. A store that has evicted keys or lost them in a failover is therefore not "broken" from the app's point of view. Users are simply asked to sign in again. Watch the rate of "session not found" responses on valid-looking cookies. A sudden jump means data loss, not a wave of expirations.
Slow is worse than down
A store that is down returns errors quickly. A store that is slow holds your request open.
Suppose each app instance has 50 worker threads and normal requests take 20 ms. The instance handles about 2,500 requests per second. If the store starts taking 5 seconds per call, each thread is stuck for 5 seconds, so the instance can only finish about 10 requests per second. The 50 threads fill within a fraction of a second, new requests queue, the load balancer's health checks time out, and instances get marked unhealthy and removed. The remaining instances take more traffic and fail faster. A slow dependency has become a full outage, including for endpoints that never needed a session.
The defense is a short timeout on every store call. Most client libraries have no timeout, or a very long one, by default. Set both a connect timeout and a read timeout, based on the store's normal latency. If the normal call takes 1 to 2 ms, a 100 to 200 ms read timeout is generous.
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 size. An unbounded pool turns a slow store into thousands of open connections, which makes the store even slower.
Decide: fail closed or fail open
When the app cannot reach the store, it cannot know who the user is. There are two choices.
- Fail closed. Reject the request, normally with
503 Service Unavailable. Use this for anything that needs identity or authorization: account pages, payments, admin actions. - Fail open. Serve the request as if the user were anonymous, or serve a limited version. This is only safe for content that is the same for everyone, such as a public landing page or a product listing.
Never fail open on an authorization check. "Could not check whether the user is allowed" must mean "no." A bug here can expose other users' data.
Use 503 rather than 401 when the store is down. A 401 tells the browser or client that the credentials are bad, and many clients respond by clearing the cookie and sending the user to the login page. That turns a short outage into a mass logout. A 503 with a Retry-After header says the problem is temporary and the session is still valid.
A circuit breaker for the store
If the store is down, trying it on every request wastes time even with a short timeout, and adds load that slows recovery. A circuit breaker tracks recent failures and, once they pass a threshold, skips the store entirely for a short period.
The following example combines the timeouts, the breaker, and the fail-closed rule. It is a single-process sketch. In a threaded server you would add a lock around the counters, or use a maintained library.
import json
import time
import redis
r = redis.Redis(
host="localhost",
port=6379,
decode_responses=True,
socket_connect_timeout=0.1,
socket_timeout=0.2,
)
class SessionStoreUnavailable(Exception):
pass
class CircuitBreaker:
def __init__(self, max_failures: int = 5, reset_after: float = 10.0):
self.max_failures = max_failures
self.reset_after = reset_after
self.failures = 0
self.opened_at = None
def allow(self) -> bool:
if self.opened_at is None:
return True
# After the wait, let calls through as a trial (half-open).
return time.monotonic() - self.opened_at >= self.reset_after
def record_success(self) -> None:
self.failures = 0
self.opened_at = None
def record_failure(self) -> None:
self.failures += 1
if self.failures >= self.max_failures:
self.opened_at = time.monotonic()
breaker = CircuitBreaker()
def load_session(session_id: str):
"""Return the session dict, None if absent, or raise if the store is unusable."""
if not breaker.allow():
raise SessionStoreUnavailable("circuit open")
try:
data = r.get(f"session:{session_id}")
except (redis.exceptions.TimeoutError, redis.exceptions.ConnectionError) as exc:
breaker.record_failure()
raise SessionStoreUnavailable(str(exc)) from exc
breaker.record_success()
return None if data is None else json.loads(data)
def handle_request(session_id: str, needs_login: bool):
"""Return (status, body, headers)."""
try:
session = load_session(session_id)
except SessionStoreUnavailable:
if needs_login:
return 503, {"error": "try again shortly"}, {"Retry-After": "5"}
return 200, {"page": "public content"}, {} # fail open: same for everyone
if session is None:
if needs_login:
return 401, {"error": "sign in required"}, {}
return 200, {"page": "public content"}, {}
return 200, {"page": "account", "user": session["user_id"]}, {}load_session has three outcomes, and the caller must treat them differently. A dictionary means a valid session. None means the store answered and there is no session. The exception means the store gave no answer. Collapsing the last two into None is the most common bug in this area, because it logs everyone out whenever the store hiccups.
Half-open here is simplified. Once the timer elapses, all calls pass until one result resets or reopens the breaker. A production breaker lets through only one or a few trial calls.
Retries: few and jittered
A retry can hide a single dropped packet. It can also double the load on a store that is already struggling. Keep retries to one or two for reads, add a small random delay (jitter) before each, and never retry without a total time budget per request. If the request has a 500 ms deadline and the store call has used 400 ms, do not retry.
Retry only operations that are safe to repeat. GET and DELETE of a session are safe. Creating a session with a fresh random ID is also safe, because a duplicate attempt just makes an unused key that expires.
Data loss: what survives a restart or failover
Sessions are usually treated as disposable, but losing them has a user-visible cost. Decide how much loss you accept, then configure for it.
- Persistence. Redis with no persistence restarts empty. Append-only file persistence (
appendonly yes) withappendfsync everysecloses at most about a second of writes on a crash. Snapshots alone can lose minutes. - Replication. Redis replication is asynchronous by default. If the primary fails right after a user logs in, the replica may not have that session, and the user is logged out after failover. The
WAITcommand can make a write block until a number of replicas confirm it, at the cost of latency. - Eviction. When memory runs out, the
maxmemory-policysetting decides what happens. Policies such asallkeys-lruandvolatile-lrudelete live sessions, since sessions all have a TTL.noevictioninstead refuses new writes with an error. Evicting means random users are logged out. Refusing means new logins fail while existing sessions keep working. Most teams prefer the second, together with an alert on memory use. Keep sessions in a dedicated instance so a cache workload cannot push them out.
Recovery: the empty-store stampede
When the store returns empty, or after a long outage, many users arrive with cookies that no longer match anything. They all hit the login flow at once. Login is often the most expensive endpoint, since it hashes passwords and may call an identity provider. This can knock the service over again just as the store recovers.
Ways to soften it:
- Rate limit the login endpoint, and queue or reject the excess with
503andRetry-After. - Add jitter to client retry timers so clients do not all return in the same second.
- Keep the breaker's half-open phase gradual, so recovery does not send full load at the store in one step.
- Where the product allows, re-create sessions from a longer-lived remember-me credential instead of a full password check.
Degraded modes and their cost
You can reduce dependence on the store by keeping a short-lived copy of sessions in each instance's memory.
- On a successful
load_session, save the result locally for 30 to 60 seconds. - On later requests, read the local copy first.
- If the store becomes unavailable, keep serving users whose copies are still valid.
This helps during short outages and cuts read traffic. The cost is the revocation delay. A user whose session was deleted (a logout, a password reset, an admin lockout) stays valid on every instance holding a copy until it expires, so a 60 second cache means up to 60 seconds of stale access. Do not use stale copies for sensitive actions. This is the same trade-off as signed tokens with short lifetimes, and it should be a deliberate choice, not an accident.
Comparing the three approaches under failure
| Approach | If the store is down | If the store is slow | Data loss effect |
|---|---|---|---|
| Sticky sessions (in-memory) | No store to fail | Not applicable | Losing an instance loses its users' sessions |
| Shared store | Authenticated requests fail unless degraded | Can stall the whole app without timeouts | Restart or failover logs users out |
| Signed tokens | Requests keep working | Not applicable, unless checking a revocation list | Nothing to lose, but no instant revocation |
Signed tokens fail best for availability and worst for control. A shared store gives you control, since you can delete a session at once. The price is the failure handling in this chapter. Many systems combine them: short-lived signed tokens for most requests, and a store consulted for refresh and revocation, so a store outage degrades slowly instead of immediately.
Test the failure paths
Failure handling that was never exercised usually does not work. Before release, check at least these cases against a staging environment:
- Stop the store. Authenticated pages return
503quickly, public pages still render, and no worker threads are left waiting. - Block the store's port so packets are dropped instead of refused. This simulates slowness, and tests your timeouts, which a clean stop does not.
- Restart the store empty. Users see the login page, and login latency stays within limits under load.
- Restore the store. The breaker closes, and error rates return to normal without a restart of the app.
Alert on store latency at the 99th percentile, connection errors, memory use, evicted key counts, and the rate of "session not found" for cookies that look well-formed.
Exercise
Your app instances report timeouts to the session store, and soon after, health checks for every instance, including those serving only static pages, begin failing. What is the likely cause, and what two changes would you make?
Show answer
Calls to the slow store have no short timeout, so worker threads wait on it until the pool is exhausted and the instances cannot answer health checks. Set short connect and read timeouts on the store client (for example 100 to 200 ms) and add a circuit breaker so requests skip the store while it is failing. Capping the connection pool and returning 503 for session-dependent routes also helps.
Exercise
A deploy of the store's host causes a restart with no persistence. Afterwards, load_session returns None for every request, and users see the login page. Why is this different from the store being unreachable, and why does it matter that the code distinguishes the two?
Show answer
When the store is empty it answers successfully, so the app correctly concludes there is no session and asks for login. When it is unreachable the app has no answer and should return 503 instead of 401, which keeps users' cookies and sessions valid for when the store returns. Treating an unreachable store as "no session" would log out every user at the first network error.
Exercise
You add a 60 second per-instance cache of loaded sessions to survive short store outages. Name one benefit and one risk.
Show answer
Benefit: authenticated requests keep working for up to 60 seconds during a store outage, and read traffic to the store drops. Risk: a session that is deleted for logout, password reset or account lockout stays valid on instances that hold a cached copy until the copy expires, so revocation is delayed by up to 60 seconds.