Sub topic 6
Keeping compute stateless and handling sessions
This chapter assumes you know how load balancers and DNS route traffic, what a web session cookie is, and the basics of a key-value store or relational database. It covers why compute in an active-active design must hold no durable state, and where session data goes instead.
Why stateless compute matters across regions
In an active-active design, any region may receive any request. A user can land in eu-west-1 now and us-east-1 a minute later, because latency-based routing shifted, a health check failed, or a regional outage forced a failover. If the first region kept the user's session in process memory, the second region has no record of it. The user is logged out, loses a shopping cart, or sees an error.
Stateless compute means a request handler keeps no information between requests that it cannot rebuild from the request itself or from a shared store. Any instance in any region can then serve any request. This gives you three properties:
- Failover without recovery steps. Traffic moves to another region and instances keep serving.
- Simple scaling. You add or remove instances without migrating data.
- Simple deployment. You can replace instances at any time, since they hold nothing worth keeping.
"Stateless" does not mean the application has no state. It means the state lives somewhere other than the compute tier. The design question becomes where that state goes and how far it must travel.
What counts as hidden state
Teams often believe a service is stateless while it still depends on local state. Check for these:
| Hidden state | Problem in multi-region | Fix |
|---|---|---|
| In-memory session objects | Lost when the user lands in another region or instance | Signed token or shared session store |
| Files written to local disk | Not visible to other instances or regions | Object storage with cross-region replication |
| In-process caches holding authoritative data | Stale or missing after failover | Treat as a cache only, with a TTL, and reload from the data tier |
| Local scheduled jobs | Run once per region, or twice | Leader election or a job that is safe to run twice |
| Sticky sessions at the load balancer | Pin users to one instance, which blocks clean failover | Remove stickiness or treat it as an optimization only |
| Locally generated sequence numbers | Collide across regions | UUIDs, or ID ranges assigned per region |
A useful test is to kill any instance at random, then send the next request from the same user to a different region. If the user notices, some state was hidden in compute.
Three ways to handle sessions
A session is the server's memory of who a user is and what they are doing. There are three common places to keep it, and each has a different cross-region cost.
Client-side sessions with signed tokens
The server puts the session data in a token and gives it to the client. The client sends it back on every request. The server signs it, so the client cannot change it. JSON Web Tokens (JWTs) are the usual format.
Every region verifies the token with the same signing key, so no cross-region lookup happens. This is the cheapest option for latency and for failover. The costs are:
- Revocation is hard. A valid token stays valid until it expires. To log a user out everywhere, you need a short expiry plus a revocation list, and that list is state again.
- Size limits. Tokens travel with every request, so they must stay small. Cookies are typically limited to about 4 KB.
- Key management. All regions need the signing key, and key rotation must reach every region before the old key is retired. Otherwise one region rejects tokens another region issued.
The sketch below shows signing and verification with a shared key and an expiry, using only the Python standard library.
import base64
import hashlib
import hmac
import json
import time
SECRET = b"shared-signing-key-distributed-to-every-region"
def _b64(data: bytes) -> str:
return base64.urlsafe_b64encode(data).decode().rstrip("=")
def _unb64(text: str) -> bytes:
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
def issue(user_id: str, ttl_seconds: int = 900) -> str:
payload = json.dumps({"sub": user_id, "exp": time.time() + ttl_seconds}).encode()
body = _b64(payload)
sig = _b64(hmac.new(SECRET, body.encode(), hashlib.sha256).digest())
return f"{body}.{sig}"
def verify(token: str):
"""Return the claims if the token is valid and unexpired, else None."""
try:
body, sig = token.split(".")
except ValueError:
return None
expected = _b64(hmac.new(SECRET, body.encode(), hashlib.sha256).digest())
if not hmac.compare_digest(sig, expected):
return None
claims = json.loads(_unb64(body))
return claims if claims["exp"] > time.time() else None
token = issue("user-17")
print(verify(token)) # {'sub': 'user-17', 'exp': ...}
print(verify(token + "x")) # None, signature does not matchIn production, keep the key in a secrets manager and replicate it to each region. Do not hard-code it as this example does.
A shared session store replicated across regions
The server keeps only a random session ID in a cookie. The session data lives in a store such as DynamoDB global tables, or a replicated Redis-compatible cache. Any region looks up the ID.
This allows instant revocation, because you delete the record. It also keeps sensitive data off the client. The cost is replication. Sessions are written often, and replication between regions is usually asynchronous, so a region may read an older copy of the session than the one just written elsewhere. Two failure patterns follow:
- Stale reads after a switch. A user logs in at region A and the next request reaches region B before the session record arrives. B finds no session and asks the user to log in again.
- Lost updates. Two regions update the same session at nearly the same time, and a conflict rule such as last-writer-wins drops one update.
Mitigations are to keep session records small and mostly write-once, to store only what you need, and to avoid updating a session on every request. If you track "last seen", write it at most every few minutes.
Region-local sessions with a home region
Each session is created in one region and stored only there. Routing keeps a user in their home region while it is healthy. This avoids cross-region writes for sessions. The cost is that a regional failure ends every session homed there, so users must authenticate again after failover. For some products, such as internal tools, that is acceptable. For checkout flows, it usually is not.
Choosing among them
| Approach | Failover experience | Revocation | Cross-region cost |
|---|---|---|---|
| Signed token | Seamless | Weak, relies on expiry | None at request time |
| Replicated store | Mostly seamless, brief stale reads | Strong | Replication traffic and lag |
| Home region only | Users must log in again | Strong | None |
Many systems combine these. A short-lived signed access token (for example 10 minutes) handles most requests with no lookup. A longer-lived refresh credential lives in a replicated store, which lets you revoke it. A revoked user loses access within one token lifetime.
Request flow during a failover
The diagram shows a user whose first request goes to region A. After region A fails, the second request lands in region B, which validates the token without contacting A.
Other stateless concerns
Configuration and secrets. Each region reads the same configuration, but a rollout should not be all-or-nothing. Deploy region by region, so a bad configuration affects one region first.
Uploads and temporary files. Write them to object storage, not to local disk. For multi-step uploads, store the upload state in the data tier so that another region can finish the upload.
Local caches. Caching is fine when a stale value is tolerable and the cache can be rebuilt. After failover, the surviving region's caches are cold for the new traffic. That produces a burst of load on the database, which Chapter 13 on capacity planning covers.
Background workers. Workers that pull from a queue are stateless if they are safe to run twice. This links to idempotency, covered later in this tutorial.
Time and ordering. Do not rely on the instance clock for ordering across regions. Clocks drift, which matters for token expiry too. Allow a small tolerance, such as 30 to 60 seconds, when validating expiry and issue times.
Common errors
- Enabling sticky sessions as a fix. Stickiness hides in-memory state until the day an instance or region fails.
- Rotating the signing key in one region first. Tokens issued by a region with the new key fail in regions that lack it. Distribute the new key everywhere as a verification key before using it to sign.
- Putting large objects in the session. Large sessions slow replication and exceed cookie limits.
- Treating the replicated session store as strongly consistent. Code that reads its own write from another region must handle a missing or older record.
- Forgetting that logout must reach every region. With tokens, logout only clears the cookie unless you also record a revocation.
Exercise
A service runs in two regions with latency-based routing. Sessions are stored in a replicated store with asynchronous replication. Users report being asked to log in again right after signing in, but only sometimes. What is the likely cause, and name two ways to fix it?
Show answer
The login request wrote the session in one region, and the next request was routed to the other region before replication delivered the record, so that region found no session. Fixes: issue a signed token at login so any region can accept the user without a lookup; keep the user pinned to the region that created the session for a short period after login; or on a miss, retry the read after a short delay or fall back to reading from the writing region.
Exercise
Why does a signed token make revocation harder, and how can you limit the damage without giving up stateless validation?
Show answer
A region validates the token from its signature and expiry alone, so it cannot know the account was disabled. Limit the damage with a short token lifetime, such as 10 to 15 minutes, and a revocable refresh credential stored in a replicated store. A revoked user then loses access when the current token expires. For urgent cases, also keep a small replicated revocation list that regions check.