Sub topic 6
Session persistence and when to avoid it
This chapter assumes you know how HTTP requests and cookies work, how TCP connections and ports behave, and how a load balancer picks a backend (see the earlier chapters on Layer 4 vs Layer 7 and balancing algorithms). You should be able to read a basic NGINX or HAProxy configuration.
The problem session persistence solves
A load balancer normally treats each request, or each new connection, as an independent decision. Round robin sends request one to server A and request two to server B. That works when every server can answer any request equally well.
It breaks when a server keeps state in its own memory. Typical examples:
- A login session stored in the application process.
- A shopping cart held in a local object.
- An uploaded file waiting on local disk for the next step of a wizard.
- A WebSocket or long-polling connection tied to one process.
If the client's second request lands on a different server, that server has no record of the first. The user appears logged out, the cart is empty, or the upload step fails.
Session persistence (also called sticky sessions or session affinity) is a load balancer feature that sends a given client to the same backend for the duration of a session. The balancing algorithm still picks a backend for the first request. After that, the persistence mechanism overrides the algorithm for the same client.
Persistence mechanisms
There are four common ways to identify "the same client". They differ in what the load balancer must be able to see, which determines whether they work at Layer 4 or only at Layer 7.
| Mechanism | Layer | How it identifies the client | Main weakness |
|---|---|---|---|
| Source IP affinity | 4 or 7 | Hash or table entry keyed on the client IP address | Many users behind one NAT share one IP, so load is uneven |
| Load balancer inserted cookie | 7 | The balancer adds a cookie naming the chosen backend | Requires HTTP visibility, so TLS must be terminated or re-encrypted |
| Application cookie | 7 | The balancer reads the application's own session cookie | Needs configuration for each application's cookie name |
| Header or URL parameter | 7 | A value such as a user ID or session token | Must exist on every request, and can be spoofed |
Source IP affinity
The balancer maps the client IP address to a backend, either with a hash or with a stored table. It needs no HTTP parsing, so it works for any TCP or UDP service and with TLS passthrough.
Its problems are practical:
- Corporate networks, universities and mobile carriers often place thousands of users behind a few public addresses. All of them land on one backend.
- A client that changes networks (Wi-Fi to cellular) gets a new IP and loses its session.
- Under IPv6 or carrier-grade NAT, a client's address can change between requests.
Use it when you have no better identifier, for example with a raw TCP service.
Load balancer inserted cookie
The balancer adds its own cookie to the first response. The cookie value identifies the backend. On later requests the balancer reads the cookie and routes accordingly. The application does not need to know.
This is usually the most accurate HTTP method, because it identifies a browser instead of a network address. It works only if the balancer can read and modify HTTP, so HTTPS traffic must be decrypted at the balancer (see the chapter on TLS termination and passthrough).
Application cookie
The application already issues a session cookie such as JSESSIONID or PHPSESSID. The balancer learns which backend issued each value and routes later requests with that value to the same backend. This avoids adding a second cookie, but the balancer must keep a table of session values, which uses memory and is lost if the balancer restarts.
Header or URL based routing
Some systems route on a header such as X-User-Id or on a path segment such as /tenant/42/. This is closer to hash-based balancing than to true stickiness. It is covered in the chapter on consistent hashing.
Configuring persistence
The HAProxy example below inserts a cookie so that a returning client reaches the same server. The cookie names the server, and indirect keeps it from being forwarded to the backend.
frontend web
mode http
bind *:443 ssl crt /etc/haproxy/certs/site.pem
default_backend app
backend app
mode http
balance roundrobin
option httpchk GET /healthz
http-check expect status 200
cookie SRV insert indirect nocache
server app1 10.0.0.11:8080 check cookie app1
server app2 10.0.0.12:8080 check cookie app2What each cookie option does:
insertmakes HAProxy create the cookie itself.indirectstrips the cookie before the request reaches the backend, and prevents it from being sent on responses when the client already has the right value.nocacheadds cache-control headers so a shared cache does not store a response containing the cookie and hand it to other users.
In open source NGINX, the simplest built-in method is IP hash. It uses the client address, so it has the weaknesses listed above.
upstream app {
ip_hash;
server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;
}
server {
listen 80;
location / {
proxy_pass http://app;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}Cookie-based stickiness with the sticky directive is a feature of NGINX Plus, the commercial edition. With open source NGINX you can approximate it using hash $cookie_name consistent;, which hashes an existing cookie value. That requires the application or another layer to set the cookie.
What happens when the chosen backend goes away
Persistence is a preference, not a guarantee. If the pinned backend fails its health check, the balancer must send the client elsewhere. The new backend has no copy of the old session, so the user loses state anyway.
Related edge cases:
- Draining. When you remove a server for a deploy, existing sessions must finish or be moved. Connection draining (covered in a later chapter) lets pinned clients continue while new clients are sent elsewhere.
- Balancer restart. Table-based persistence (source IP tables, application cookie tables) is lost unless the table is replicated. Cookie insertion survives a restart because the state lives in the client.
- Two balancers. If you run a redundant pair, they must share the same cookie scheme or the same table, or a failover will scatter clients.
- Cookie lifetime. A session cookie without an expiry ends when the browser closes. A long-lived cookie can pin a client to a server that is later replaced by a different machine reusing the same label.
Why stickiness has costs
Persistence solves one problem and creates others.
Uneven load
The algorithm only balances new clients. A heavy user stays on one server for as long as the session lasts. Over time, one server can carry most of the heavy sessions while another is idle. Least connections cannot correct this, because it applies only to unpinned requests.
Weaker availability
A server crash destroys every session pinned to it. Without persistence, a stateless application loses only the in-flight requests. With in-memory sessions plus persistence, users lose carts, logins and partially entered forms.
Harder scaling and deploys
When you add a server, existing sessions do not move to it, so it stays underused until old sessions expire. When you remove a server, you must wait for sessions to finish or accept the loss. Rolling deployments take longer.
Security and privacy
A cookie that names a backend in plain text, such as app1, reveals internal structure. Many balancers can hash or encode the value. Set Secure and HttpOnly on the cookie, and SameSite where it fits.
Alternatives that remove the need for stickiness
The more durable fix is to make servers interchangeable. Then any server can handle any request and persistence becomes optional.
- Shared session store. Keep sessions in Redis, Memcached or a database. Every server reads the session using a session ID from the cookie.
- Client-side state. Put the session in a signed, and where needed encrypted, token such as a JWT or an encrypted cookie. The server holds no state. The trade-off is larger requests and difficulty revoking a token before it expires.
- Shared file storage. Send uploads directly to object storage rather than local disk.
- Idempotent, stateless handlers. Design endpoints so any server can complete them.
Some workloads legitimately need affinity: WebSocket connections, in-memory caches that are expensive to rebuild, and legacy applications that cannot be changed. In those cases use persistence deliberately, and keep the shared-state approach as the long-term goal.
Choosing an approach
| Situation | Suggested choice |
|---|---|
| New HTTP application | No persistence. Use a shared session store or signed tokens. |
| Legacy HTTP application with in-memory sessions | Load balancer inserted cookie |
| Raw TCP or TLS passthrough | Source IP affinity or hash on a connection property |
| Many users behind a few NAT addresses | Avoid source IP. Use a cookie. |
| Cache locality is the goal | Consistent hashing on a request key |
Common errors
- Enabling
ip_hashor source persistence behind another proxy or CDN. Every request then appears to come from the proxy's address, so all traffic pins to one backend. Hash on a trusted forwarded header instead, or configure the real client IP module. - Using a cookie method while TLS passes through encrypted. The balancer cannot see HTTP, so no cookie is read or set.
- Forgetting that health checks and persistence interact. A server marked down loses its pinned clients.
- Testing with
curlwithout a cookie jar. Usecurl -c jar.txt -b jar.txtto confirm the cookie keeps you on one server.
Exercise
Your HAProxy backend uses cookie SRV insert indirect nocache. A user is pinned to app1, then app1 fails its health check. What happens to the user's next request, and what does the user experience if sessions are stored in app1's memory?
Show answer
HAProxy ignores the pinned choice because app1 is down and uses the balancing algorithm to pick a healthy server such as app2. It then sets a new SRV cookie for app2. Because the session lived only in app1's memory, app2 has no record of it, so the user is logged out or loses their cart. Moving sessions to a shared store such as Redis would avoid the loss.
Exercise
A company puts 4,000 employees behind one office NAT address. The load balancer uses source IP persistence across four servers. What problem do you expect, and what change fixes it for an HTTP application?
Show answer
All 4,000 users share one public IP, so they are all pinned to one backend while the other three stay mostly idle. Switching to cookie-based persistence identifies each browser separately and spreads the users. This requires the balancer to read HTTP, so TLS must be terminated at the balancer.