Architecture
Sticky Sessions: Pros, Cons and How to Configure Them Safely
By NileVPS Team · Published · 5 min read
اقرأ المقال بالعربيYou add a second application server behind a load balancer, and suddenly users complain that they are logged out at random or their cart empties between pages. The cause is almost always the same: the app keeps session data in the memory or local disk of one server, and the load balancer just sent the next request to the other one. Sticky sessions, also called session affinity, fix this by routing each client to the same backend every time. It is a quick fix and sometimes the right one, but it comes with trade-offs that are worth understanding before you rely on it.
How sticky sessions work
The load balancer needs some way to recognise a returning client and remember which backend served them. There are three common methods:
- Source IP hashing. The balancer hashes the client IP address and maps it to a backend. No cookies are involved, but many users behind one carrier-grade NAT or office network all land on the same server, and a user whose IP changes (mobile switching towers, VPN) jumps to another backend.
- Load balancer cookie. The balancer inserts its own cookie naming the backend on the first response. Later requests carry the cookie and go to the same server. This is the most precise method.
- Application cookie hashing. The balancer hashes an existing cookie, such as the session ID your framework already sets, to pick a backend.
Configuration examples
Nginx (open source)
The free version of Nginx supports IP-based affinity and hashing on any variable, including a cookie:
upstream app {
ip_hash;
server 10.0.0.11:8080;
server 10.0.0.12:8080;
}Or hash on the application's session cookie, using consistent hashing so adding a server only moves a portion of clients:
upstream app {
hash $cookie_sessionid consistent;
server 10.0.0.11:8080;
server 10.0.0.12:8080;
}Replace sessionid with the real cookie name, for example laravel_session or PHPSESSID. Note that a first request without the cookie still has to land somewhere, and the sticky directive with inserted cookies is part of the commercial NGINX Plus, not the open source build.
HAProxy
HAProxy supports cookie insertion out of the box:
backend app
balance roundrobin
cookie SERVERID insert indirect nocache
server app1 10.0.0.11:8080 check cookie app1
server app2 10.0.0.12:8080 check cookie app2insert adds the cookie, indirect stops it being passed to the application, and nocache keeps shared caches from storing a response that carries it. The check keyword enables health checks so a dead server is skipped even for sticky clients.
The advantages
- Zero application changes. A legacy app with in-memory sessions can scale out today.
- Better local cache hits. If each server caches per-user data, sending the same user to the same server reuses that cache.
- Required by some protocols and tools. Long-polling fallbacks for WebSocket libraries, some admin panels, and file uploads that are chunked across several requests often need affinity.
The disadvantages
- Uneven load. Affinity overrides balancing. A handful of heavy users, or one large NAT, can pin a lot of traffic onto one server while another sits idle.
- Lost sessions on failure. If a server crashes or is rebooted for updates, every session stored on it disappears. Users are logged out mid-checkout.
- Harder deployments. Draining a server for a rolling update takes as long as its longest-lived session, or you accept dropping users.
- Weaker autoscaling. New servers only receive new clients, so adding capacity does little for existing load until sessions expire.
- IP hashing surprises. Users behind shared IPs cluster together; users with changing IPs lose their session.
The better long-term option: stateless app servers
The cleaner solution is to stop storing session state on individual servers. Move it to a shared store and let any backend handle any request:
- Redis or Memcached for sessions. Most frameworks support this with one setting, for example
SESSION_DRIVER=redisin Laravel orsession.save_handler = rediswith the phpredis extension in PHP. - The database for low-traffic apps where an extra query per request is fine.
- Signed tokens (such as JWTs or encrypted cookies) carrying the state on the client, keeping them small and short-lived.
Uploaded files should go to shared or object storage rather than a server's local disk, for the same reason. Our article on stateful vs stateless apps goes deeper into this design choice.
Decision table
| Situation | Recommendation |
|---|---|
| Legacy app, in-memory sessions, need to scale this week | Sticky sessions with cookie insertion and health checks |
| WebSocket app with long-polling fallback | Affinity, at least for the handshake phase |
| New app you control | Shared session store, no stickiness |
| Frequent rolling deployments or autoscaling | Avoid stickiness or keep session TTLs short |
| Many users behind carrier NAT | Avoid IP hash; use cookies |
If you are building your first load-balanced setup, our guide to load balancers covers the algorithms and health checks that sit underneath all of this.
FAQ
Are sticky sessions bad practice?
Not inherently. They are a reasonable tool for legacy apps or protocols that genuinely need affinity. The problem is relying on them as the only place your session data lives, because a server failure or deployment then logs users out. Pair them with a shared store when you can.
Why does ip_hash send most of my traffic to one server?
Because many clients share the same public IP. Mobile carriers and offices often place large numbers of users behind a few addresses, so the hash maps them all to one backend. Hashing on a session cookie spreads the load far more evenly.
Do I need sticky sessions for WebSockets?
An established WebSocket connection stays on the server it opened on, so it does not need affinity by itself. You need it when the library falls back to HTTP long-polling, or when the handshake spans several requests, because those requests must reach the same backend.