Sub topic 4
Sticky Sessions and Their Limits
This chapter assumes you know how HTTP cookies work and what a load balancer does. It covers the simplest way to keep session state on app instances, and where that approach breaks down.
The idea
A service that keeps session data in its own memory has a problem once you run more than one instance. A user logs in on instance A, and A stores the session. The next request goes to instance B, which has no record of it. The user appears logged out.
Sticky sessions (also called session affinity) fix this at the load balancer. The balancer sends every request from one client to the same instance. The instance keeps session data in local memory, and the app code does not change.
How the balancer pins a client
There are three common methods:
- Cookie-based affinity. The balancer sets its own cookie on the first response, naming the chosen instance. Later requests carry the cookie and are routed to that instance.
- Source IP hashing. The balancer hashes the client IP address and maps it to an instance.
- Application cookie affinity. The balancer reads the app's own session cookie and routes by its value.
Source IP hashing is the weakest option. Many users behind one corporate proxy or mobile carrier gateway share an IP address, so they all land on one instance. A user whose IP changes, for example when moving from Wi-Fi to mobile data, loses the pin.
Limits
Stickiness works until something changes. These are the failure modes to plan for.
Instance loss loses sessions
Session data lives only in one instance's memory. If that instance crashes, is replaced, or is stopped during a deploy, every session on it is gone. Users are logged out, and carts or in-progress forms are lost. A rolling deploy therefore logs out users in waves.
Uneven load
Pinning ignores current load. Long-lived or heavy users keep hitting the same instance while others sit idle. When you add an instance, existing clients stay where they are, so the new instance receives only new sessions and takes a long time to share the load.
Scaling in is disruptive
Removing an instance during scale-in drops its sessions. To avoid that, you must drain connections and wait for sessions to end, which slows down autoscaling.
Affinity is a hint, not a guarantee
The balancer may ignore the pin when the target instance fails health checks. Clients may also drop or block the affinity cookie. Code that assumes the same instance will always answer is fragile.
It hides the real problem
The service still holds state locally, so it is not stateless. Any task that needs a different instance, such as a background job or a request from another client of the same user, cannot see the session.
When sticky sessions are acceptable
Stickiness is a reasonable choice in a few cases:
- A legacy app that you cannot change quickly, as a stopgap.
- Data that is cheap to lose, such as a local cache that can be rebuilt.
- Long-lived connections such as WebSockets, where the connection itself is pinned anyway.
Even in these cases, treat the pin as an optimization and not as the place where the truth lives. The app should still work, perhaps more slowly, if a request lands on the wrong instance.
A quick check you can run
This small Flask app shows the symptom. Run two copies on different ports and call them alternately, and the counter resets depending on which instance answers.
from flask import Flask, session
app = Flask(__name__)
app.secret_key = "dev-only"
local_counts = {} # lives in this process only
@app.route("/hit")
def hit():
sid = session.setdefault("sid", str(id(session)))
local_counts[sid] = local_counts.get(sid, 0) + 1
return {"hits": local_counts[sid]}
if __name__ == "__main__":
import sys
app.run(port=int(sys.argv[1]))Start it with python app.py 5001 and python app.py 5002. The session cookie is signed with the same key, so both instances accept it. The count, though, sits in each process's local_counts dictionary, so the number you see depends on which port answers. A sticky balancer would hide this. Removing the dependency on process memory is what the next chapters do.
Summary of trade-offs
| Aspect | Sticky sessions |
|---|---|
| Code change needed | None or very little |
| Survives instance failure | No |
| Load distribution | Uneven over time |
| Rolling deploys | Disrupt pinned users |
| Scaling in and out | Slow, needs draining |
Exercise
A team runs four instances behind a sticky load balancer. They deploy a new version by replacing one instance at a time. Users report being logged out during deploys. Explain why, and name one change that stops it without removing the load balancer.
Show answer
Each user's session exists only in the memory of the instance they are pinned to. Replacing an instance destroys the sessions stored on it, so the users pinned there are logged out. Moving sessions into a shared store such as Redis, or into signed client-side tokens, makes the sessions independent of any one instance, so replacing an instance no longer affects them.