Sub topic 4
Sticky Sessions and Their Limits
Sticky sessions let you run several instances of an app that keeps session data in its own memory. The load balancer sends each client back to the same instance, so the data is still there. This chapter explains how that works, how to configure it, and where it fails. It assumes you know how HTTP cookies work, you have built a web service in some language, and you know what a load balancer does. Earlier chapters defined stateless services and session state, and later chapters cover the alternatives.
What sticky sessions are
Sticky sessions are also called session affinity. The load balancer remembers or recomputes which backend instance served a client, then routes that client's later requests to the same instance.
The application code stays simple. It can keep a login or a shopping cart in a process-local dictionary, and each user will usually see their own data. The cost is that the instance is no longer interchangeable with the others. It holds state that exists nowhere else, so the service is not stateless in the sense defined earlier in this tutorial.
Stickiness is a routing hint, not a guarantee. The load balancer will break it when the pinned instance is unhealthy, removed, or overloaded. Anything that depends on stickiness for correctness will eventually fail.
How the balancer pins a client
There are three common ways to tie a client to an instance.
| Method | How it works | Main weakness |
|---|---|---|
| Balancer-issued cookie | The balancer sets its own cookie naming the chosen backend and reads it on later requests. | Clients that reject cookies are never pinned. |
| Hash of an application cookie | The balancer hashes the session cookie and maps the hash to a backend. | Requests with no cookie yet all hash to the same value. |
| Hash of the client IP | The balancer hashes the source address. | Many users behind one NAT or proxy land on one instance. |
Balancer-issued cookie
HAProxy can insert an affinity cookie on the first response. The cookie value is a label you choose for each server, not its address.
backend app
balance roundrobin
option redispatch
cookie SRV insert indirect nocache httponly secure
server app1 10.0.0.11:8000 check cookie app1
server app2 10.0.0.12:8000 check cookie app2
server app3 10.0.0.13:8000 check cookie app3insert makes HAProxy create the cookie. indirect stops HAProxy from passing the cookie on to your application. option redispatch lets HAProxy choose another server when the pinned one is down. Without it, the client's requests fail while the server is unavailable. The secure flag requires HTTPS, so remove it for plain-HTTP tests.
Use opaque labels such as app1. A cookie holding an internal IP address tells outsiders about your network layout.
Hash of the session cookie
nginx can hash a cookie value that your application already sets.
upstream app {
hash $cookie_sid consistent;
server 10.0.0.11:8000;
server 10.0.0.12:8000;
server 10.0.0.13:8000;
}
server {
listen 80;
location / {
proxy_pass http://app;
proxy_set_header Host $host;
}
}The consistent keyword selects consistent hashing, which limits how many clients move when the pool changes. A client without a sid cookie hashes an empty string, so every first-time visitor goes to the same server until the app sets the cookie. During a traffic spike of new visitors, that server takes all of the load.
Hash of the client IP
The ip_hash directive in nginx, or balance source in HAProxy, needs no cookie at all. That makes it work for non-browser clients. It also has the worst distribution. A corporate office or mobile carrier can put thousands of users behind a few addresses. A client that changes network, such as a phone moving from Wi-Fi to cellular, loses its pin.
What a failure looks like
The diagram shows a cookie-pinned session surviving normal requests and then losing its data when the instance goes away.
The balancer did its job correctly. Instance B is healthy, and the request was served. The user still lost their login and cart, because the data lived only in Instance A's memory.
The limits of sticky sessions
Instance loss destroys sessions
Any event that removes an instance also removes the sessions on it. That includes a crash, a hardware failure, an out-of-memory kill, and a cloud provider reclaiming a spot instance. These events are not rare at scale, and each one logs out a share of your users. With N instances, one failure affects roughly 1/N of active sessions.
Deploys become disruptive
A rolling deploy replaces instances one at a time. Every replaced instance takes its sessions with it. Users get logged out in waves for the whole rollout.
You can soften this with connection draining. The balancer stops sending new clients to an instance and waits for existing sessions to end. Sessions can last hours, so draining either makes deploys very slow or cuts sessions off at a timeout anyway. This is the reason many teams adopt stateless services: they want to deploy during the day without anyone noticing.
Scaling in has the same cost
Autoscaling adds instances when load rises and removes them when it falls. Removing an instance that still holds active sessions is the same as a failure. Sticky sessions therefore work against scale-in, which is half the point of autoscaling.
Load becomes uneven
Round-robin spreads new clients evenly, but sessions differ in length and weight. One instance may collect several heavy, long-lived users while another idles. The balancer cannot move a pinned user to the quiet instance without breaking the session.
Scaling out has a related problem. A new instance starts empty and only receives new clients, while old instances keep their existing pinned clients. Load shifts to the new instance slowly, as old sessions expire.
Pool changes reshuffle hash-based pinning
Hash-based methods compute the instance from the key and the pool size. If the mapping is a simple modulo, changing the pool size remaps most clients. This script measures it:
import hashlib
def bucket(key: str, n: int) -> int:
return int(hashlib.sha256(key.encode()).hexdigest(), 16) % n
session_ids = [f"sid-{i}" for i in range(1000)]
before = {s: bucket(s, 3) for s in session_ids}
after = {s: bucket(s, 4) for s in session_ids}
moved = sum(1 for s in session_ids if before[s] != after[s])
print(f"{moved} of {len(session_ids)} sessions moved to a different instance")Going from 3 instances to 4, you should see roughly three quarters of the sessions move. A system with in-memory sessions loses all of those at once, just from adding capacity. Consistent hashing, as in the nginx consistent option, moves only about 1/N of the keys, which reduces the damage. It does not remove it, because the moved clients still arrive at an instance without their data.
The pin is bypassed in several ways
- The balancer ignores the pin when the instance fails its health check and
redispatchis on. - Some clients drop cookies, so cookie-based pinning never starts.
- Proxies and CDNs may strip or cache the affinity cookie.
- Affinity cookies expire. A short expiry on the cookie ends the pin even though the session is still valid.
- A second balancer tier, or a different region, can lose the mapping.
Other costs
- Memory pressure. Sessions pile up in each process's heap. A traffic surge raises memory on the pinned instances, and an out-of-memory kill then deletes the sessions.
- Testing. Bugs that depend on which instance handled which request are hard to reproduce, and tests that run against a single instance never see them.
- Hidden coupling. Teams often add more local state later, such as upload buffers or rate-limit counters. Each addition makes the instance harder to replace.
When sticky sessions are a reasonable choice
Stickiness is not always wrong. It fits in these cases:
- A legacy application you cannot change soon. If the app stores sessions in memory and a rewrite is out of scope, affinity gets you to more than one instance. Accept the logout-on-failure behavior and communicate it.
- Long-lived connections. A WebSocket or server-sent-events connection is bound to one instance for its whole life, whatever the balancer policy. The connection state is local by nature, and your design should assume a client reconnects after a loss.
- Cache locality. If an instance keeps a warm per-user cache, routing the same user back to it saves work. This is safe only if the cache can be rebuilt from a shared source.
- A layered design. Keep the real session data in a shared store and use affinity only as an optimization. A pin miss then costs a cache refill instead of a logout.
The last case shows the distinction that matters. Stickiness is safe as a performance hint and unsafe as the only place where the data lives.
Reducing the damage if you must use it
- Make the cookie opaque,
HttpOnly, andSecure, and give it a lifetime at least as long as the session. - Enable redispatch so a dead instance leads to a retry on a live one, and make that path show a clear "please sign in again" message instead of an error.
- Use connection draining with a time limit during deploys and scale-in.
- Prefer consistent hashing over modulo hashing.
- Alert on uneven load across instances and on memory growth.
- Write down which data would be lost on instance failure, so the risk is a decision and not a surprise.
Where this leads
Sticky sessions trade simplicity in the code for fragility in operations. The next chapters cover how session identifiers and cookies work, and then the two ways to remove the dependency on one instance: a shared server-side store and signed client-side tokens. Both let any instance serve any request, and both can still use affinity as a cache hint.
Exercise
A team runs four instances behind nginx using ip_hash, with sessions held in process memory. They add a fifth instance to handle a traffic peak, and support tickets about unexpected logouts follow. Give two reasons the logouts happened, and say what change would stop logouts when instances are added.
Show answer
First, ip_hash maps each client address to an instance using the pool size. Changing the pool from four to five remaps a large share of clients to different instances, and those instances do not have the clients' in-memory sessions. Second, any instance replaced or restarted during the change would also lose its own sessions, because nothing outside the process stores them. Using consistent hashing would reduce the number of clients that move, but would not stop all logouts. The change that stops them is moving session data out of instance memory into a shared store (or a signed token), so any instance can serve any client. Affinity can then stay as an optional cache hint.
Exercise
Your nginx config uses hash $cookie_sid consistent;. After a marketing campaign, one backend runs at 95% CPU while the others are near idle, although the app sets the sid cookie correctly on first response. What is the likely cause, and what are two ways to address it?
Show answer
Many visitors arrive without a sid cookie on their first request. The variable is empty for all of them, so they all hash to the same backend. The load concentrates there until the cookie is set. Options: fall back to another key for cookie-less requests (for example, use a map to choose $remote_addr when $cookie_sid is empty), or use a balancer-issued affinity cookie so the first request is balanced by round-robin and only later requests are pinned. Moving to a shared session store removes the need for the hash entirely.