Sub topic 6
Keeping compute stateless and handling sessions
This chapter assumes you know how load balancers and cookies work. It also assumes you have read the earlier chapters on global traffic routing and failover.
Why state breaks failover
In an active-active design, any region can receive any user's next request. Failover, DNS changes and load shifts can all move a user mid-session. If a server keeps session data in its own memory or on its local disk, the next request lands on a server that knows nothing about the user. The user is logged out, the cart is empty, or a half-finished workflow is lost.
Stateless compute means a server holds no data between requests that another server could not rebuild. Each request carries or points to everything it needs. Then any instance in any region can handle it.
Where state can live
You have three common options for session data.
| Option | How it works | Trade-off |
|---|---|---|
| Signed token in the client | The server puts the session in a signed cookie or JWT | No lookup needed. Tokens are hard to revoke and grow in size. |
| Regional session store | A cache such as Redis in each region | Fast, but the session is lost or unreachable if that region fails. |
| Replicated session store | A globally replicated table | Survives region loss, but replication lag means a stale read right after a move. |
Signed tokens fit active-active best because they need no cross-region replication. Every region only needs the same verification key.
A signed session token
The sketch below issues and verifies a session token. Both regions run the same code and share the same key.
import base64, hashlib, hmac, json, time
SECRET = b"load-this-from-a-secrets-manager"
def _sign(body: str) -> str:
return hmac.new(SECRET, body.encode(), hashlib.sha256).hexdigest()
def issue(session: dict, ttl: int = 3600) -> str:
payload = dict(session, exp=int(time.time()) + ttl)
body = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode()
return f"{body}.{_sign(body)}"
def verify(token: str):
body, _, sig = token.rpartition(".")
if not hmac.compare_digest(sig, _sign(body)):
return None
payload = json.loads(base64.urlsafe_b64decode(body))
return payload if payload["exp"] > time.time() else None
token = issue({"user": "ana", "cart": ["sku-1"]})
print(verify(token)) # works in any region that has the key
print(verify(token + "x")) # None: signature check failsThe token is signed, not encrypted. Anyone holding it can read its contents, so never put secrets in it.
Common errors
- Sticky sessions as a crutch. Pinning a user to one server hides the problem until that server or region fails. Use stickiness only as a cache optimization, never as the source of truth.
- Local files and in-memory caches treated as storage. Uploads written to an instance's disk disappear on failover. Use object storage with cross-region replication instead.
- Different signing keys per region. A token issued in one region then fails verification in another. Distribute and rotate keys to all regions together, and accept both old and new keys during rotation.
- Reading your own write from a lagging store. If a session is updated in Region A and the user moves to Region B before replication finishes, B reads stale data. Keep rarely changing session fields in the token. Keep fast-changing state in a store with a single write owner.
- Clock skew on expiry. Region clocks differ slightly. Allow a small tolerance when checking
exp.
Exercise
A user logs in through Region A, which stores the session in a Redis cache local to Region A. Region A then fails and the user is routed to Region B. What happens, and name two ways to fix it?
Show answer
Region B has no copy of the session, so the user appears logged out. Fixes: (1) put the session in a signed token held by the client, with the verification key shared across regions; (2) store sessions in a replicated store that both regions can read, accepting some replication lag.