SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
  • What are Load Balancers?
  • Load Balancing Algorithms
  • DNS Load Balancing
  • Anycast Routing
  • Layer 4 vs Layer 7 Load Balancers
  • Health Checks
  • Sticky Sessions
  • Global Load Balancing
  • Nginx and HAProxy
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Foundations/Load Balancing

Sticky Sessions

Send the same user to the same server every time, and why that is a trade-off.

⏱ 11 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Sticky sessions (also called session affinity) means the load balancer sends a user to the same server every time, instead of picking a new one for each request.

  • It is needed when a server keeps the user's data (like a login or a cart) in its own memory.
  • The balancer remembers the choice with a cookie or by hashing the user's IP address.
  • The price: load can become uneven, and if that server dies, the user loses the session.
  • The cleaner fix is to keep sessions in a shared store so any server can serve anyone.

02Concept: What is it?

A normal load balancer treats every request on its own. Request 1 may go to Server A, and request 2 from the same user may go to Server B. That is fine when servers keep no memory of the user (they are stateless).

But some apps keep session data inside the server: who is logged in, what is in the cart. If request 2 lands on Server B, Server B has never heard of this user. The user is asked to log in again. Sticky sessions fix this by pinning a user to one server.

Without and with sticky sessions
No stickiness
🧑User
→↓1st request
🖥️Server Aknows you
🧑User
→↓2nd request
🖥️Server Bwho are you?
Sticky
🧑User
→↓1st request
🖥️Server Aknows you
🧑User
→↓2nd request
🖥️Server Astill knows you
Without stickiness the second request can land on a server that does not know you. With stickiness it always returns to the server that does.

How the balancer remembers

🍪Load balancer cookie
The balancer adds its own cookie on the first response. It names the chosen server. Later requests carry it back.
🔖Application cookie
The app sets a session cookie (like a session ID). The balancer reads it and keeps a table of which server owns that ID.
#️⃣Source IP hash
The balancer hashes the client IP address. The same IP always gives the same server. No cookie is needed.

03Real-Life Example

🍵The Personal Waiter
In a big restaurant you sit down and your waiter writes your order on a notepad. The notepad stays in the waiter's pocket. If a different waiter comes to refill your water, they know nothing about your order. So the restaurant uses a rule: you always get the same waiter. It works well. But if that waiter goes home sick, your order is lost. And if three tables with big families all get the same waiter, that waiter is overloaded while the others stand around.
Restaurant
Sticky sessions
Customer
User or browser
Waiter
Application server
Notepad in the waiter's pocket
Session data in server memory
Host who assigns tables
Load balancer
Always the same waiter
Session affinity
A wristband showing the waiter's name
Affinity cookie
Waiter goes home sick
Server fails, sessions lost
One waiter gets all the big tables
Uneven load
A shared order screen for the whole staff
Shared session store (Redis)
What a sticky request looks like
🧑BrowserCookie: srv=app2
→↓request
⚖️Load balancerreads cookie
→↓app2
🖥️Server app2has the session

04Why Do We Need It?

🧠Local state keeps working
Apps that keep sessions in memory run correctly behind a load balancer without being rewritten.
⚡Fast local data
A session in the same server's memory is read in microseconds, with no network call to a store.
🔌Long connections
Some protocols (WebSockets, streaming uploads) keep a connection open. Stickiness keeps all its messages on one server.
🗃️Warm local caches
A user who keeps hitting the same server benefits from data that server already cached for them.
🧱Legacy apps
Old apps built for a single server can scale to a few servers quickly with just a balancer setting.
🧾Multi-step flows
A checkout or upload wizard that holds partial data in one server can finish without a shared store.
Stickiness lets servers that remember users work behind a load balancer. It is a fix for state, not a way to make a system scale.

05Where Do We Use It?

🛒Older web apps
Frameworks that store the login or cart in memory by default, such as many classic server-side apps.
💬WebSocket and chat servers
Once a socket is open it stays on one server. A reconnect should go back to the same one if state is local.
🎮Game and live servers
A match or room lives on one server, so all players in it must be routed there.
🔐Apps with in-memory login
Where logins are kept in a server's memory instead of a database or token.
☁️Cloud load balancers
Most have a setting for it (often called session affinity or stickiness), using a cookie or the client IP.
📦Upload and download sessions
A multi-part upload whose pieces are stored on one server until the end.

06Types / Parts / How It Works

Ways to make a user stick

MethodHow it worksGood and bad
Load balancer cookieThe balancer creates a cookie that names the serverWorks at layer 7, precise per browser. Needs HTTP cookies, so a plain TCP balancer cannot do it.
Application cookieThe balancer reuses the app's own session cookieMatches the real session life time. The balancer must know the cookie name and keep a table.
Source IP hashHash of the client IP picks the serverWorks at layer 4, no cookie. Many users behind one office or mobile network share an IP and pile onto one server.
Consistent hash on a keyHash a header, user ID or URL, using consistent hashingFew users move when servers change. Needs the key to be in every request.
Connection stickinessKeep all requests of one TCP connection on one serverNatural for WebSockets. Does not help the next connection.

What happens when the server goes away

Failure of a sticky server
🖥️Server Ahas sessions
→↓dies
⚖️Load balancerpicks a new server
→↓moves users
🖥️Server Bno session
→↓login again
🧑Userstarts over
Lost Rerouted Client
The user is moved to a new server, but the session data is not moved with them.

The better design: stateless servers

Move the session out of the server into a shared store such as Redis, a database, or into a signed token held by the client (see Session vs Token Based Auth). Then every server can serve every request, and you do not need stickiness at all.

VisualizerSticky vs spread, memory vs shared store, and a failing serverStart with sticky + memory and kill Server 1. Then switch to spread + memory to see sessions go missing. Finally move the session to a shared store.
How does the load balancer route?
Where is the session kept?
What fails?
12 users send requests (44 per minute, illustrative). U4 and U10 are heavy users (12 per minute each). Bar = share of all traffic.
🖥️ Server 164%
U1U4U7U10
🖥️ Server 218%
U2U5U8U11
🖥️ Server 318%
U3U6U9U12
Requests that find their session
100%
the rest force a new login
Busiest server
64%
fair share 33%
Users logged out
0
by the failure
Everyone keeps their session (100% of requests find it). But the busiest server carries 64% of the load, while a fair share is 33%. Two heavy users happened to stick to Server 1, and sticky routing cannot move them.

A simplified model with expected values and no random numbers. User loads are illustrative. With spread routing and sessions in memory, a request finds its session only if it lands on the one server that holds it.

07How to Use It / Steps / Implementation

Using stickiness safely

  1. 1
    Try to be stateless first
    Ask if the session really must live in server memory. A shared store or a signed token usually removes the need for stickiness.
  2. 2
    If you need it, use a cookie
    A balancer cookie sticks each browser, not each IP address. This avoids many users sharing one server because they share one office address.
  3. 3
    Set an expiry
    Let the stickiness cookie expire with the session, so users are not pinned for ever.
  4. 4
    Plan for the server dying
    Decide what the app does when its sessions vanish: ask the user to log in again, or rebuild the session from a database.
  5. 5
    Drain, do not kill
    When removing a server, stop sending it new users and let existing sessions finish (connection draining) before shutting down.
  6. 6
    Watch the balance
    Track requests per server. If one server is always hotter, stickiness may be the reason.
  7. 7
    Test failover
    Stop a server on purpose in a test environment and see what users experience.
A sticky cookie setting (illustrative, differs by product)
# Typical idea, shown generically
affinity: cookie
cookie_name: LB_SERVER
cookie_lifetime: session   # or e.g. 30 minutes
# Always check the docs for the exact names in your load balancer.
💡Sticky is a patch, not a design
If you find yourself relying on stickiness for correctness (not just for speed), treat it as a warning sign. A failing server should cost you a little speed, not your users' data.

08Key Terms to Know

TermMeaning in easy words
SessionThe data a server keeps about one user between requests (login, cart)
Session affinityAnother name for sticky sessions: the same user goes to the same server
Sticky cookieA cookie the load balancer sets to remember the chosen server
Source IP hashChoosing a server by hashing the client IP address
Stateless serverA server that keeps no user data between requests, so any server can serve any request
Stateful serverA server that remembers user data between requests
Session storeA shared place (Redis, database) where all servers keep sessions
Connection drainingLetting existing sessions finish before a server is taken out of rotation
Hot serverA server that gets much more load than its peers
Session replicationCopying each session to other servers so one failure does not lose it
FailoverMoving traffic to another server when one fails

09Pros, Cons and Trade-offs

✅ Pros
  • Apps with in-memory sessions work behind a balancer
  • Very fast access to local session data
  • Simple to turn on with a balancer setting
  • Keeps long-lived connections on one server
  • Warm per-user caches stay useful
⚠️ Cons
  • Uneven load: heavy users stick to one server
  • Server failure loses its sessions
  • Harder to scale in and out, because users are pinned
  • Many users behind one IP can overload one server (IP hash)
  • Hides state problems that should be fixed
  • Rolling deployments need careful draining

Trade-offs

ChoiceWe gainWe lose
Sticky sessionsLocal session memory just worksEven load and easy failover
Shared session storeAny server can serve any user, failures are invisibleOne more system to run, and a network call per request
Signed token in the clientNo server-side session at allHarder to revoke early, larger requests
Session replication between serversSurvives one server failingExtra network traffic and complexity, grows with the cluster
Cookie stickinessFair per browserNeeds layer 7 and HTTP cookies
IP hash stickinessWorks at layer 4 without cookiesShared IPs create hot servers

10Common Problems and Mistakes

Common mistakes

  1. Using stickiness to avoid fixing state. It works until the first server dies.
  2. IP hash behind a big NAT. An entire company or mobile carrier looks like one IP, and one server gets all of them.
  3. Forgetting that scaling out does not help old users. New servers only get new users, because the old ones are pinned.
  4. Pinning for too long. A cookie that never expires keeps users on a server that you want to retire.
  5. No plan for failure. The app crashes or shows errors when the session is missing, instead of asking the user to log in again.
  6. Relying on stickiness with autoscaling. Scale-in kills servers with live sessions.

Things to watch

🔥Hot servers
Compare requests per server. A steady gap means stickiness is skewing the load.
🧯Deployments
A rolling update can log out everyone on the servers being replaced.
📉Scale-in
Removing a server drops its sessions. Drain first.
🏢Shared addresses
Offices, schools and mobile networks put many people behind one IP.

11Real-World Examples

☁️Cloud load balancers
Major clouds offer a cookie-based stickiness setting on their HTTP load balancers, usually with a configurable duration.
🧰Nginx and HAProxy
Both can stick users by cookie or by IP hash (ip_hash in Nginx, balance source or a stick table in HAProxy).
🕸️Service meshes and ingress
Kubernetes ingress controllers and meshes can pin requests by header, cookie or hash.
💬Chat and live apps
Real-time servers often keep a connection and rooms in memory, so reconnects return to the same node when possible.
🗄️Redis-backed sessions
Many web frameworks can keep sessions in Redis or a database, so stickiness is no longer needed.
🧾Token-based login
Signed tokens (like JWT) carry the login with each request, so servers keep no session at all.
📝Note
Setting names and defaults differ between products and versions. Check your own load balancer's documentation.
Mini case: from sticky to stateless
⚖️Balancersticky cookie
→↓pinned
🖥️Serverssessions in memory
→↓then
⚖️Balancerspread freely
→↓any
🖥️Serversstateless
→↓
🧠Redisshared sessions
The same app, before and after. The shared store lets any server answer, so the balancer can spread freely.

12Related Topics to Read Next

Stateless vs Stateful→

The idea that decides whether you need stickiness at all.

What are Load Balancers?→

The component that makes the sticky choice.

Load Balancing Algorithms→

IP hash and consistent hashing are algorithms used for stickiness.

Session vs Token Based Auth→

The two ways to remember a logged-in user.

Health Checks→

How the balancer finds out that a sticky server died.

Consistent Hashing→

Pin users to servers while moving few of them when servers change.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: the balancer sends the same user to the same server every time.
  • ✔Why: the server keeps session data in its own memory.
  • ✔How: balancer cookie, app cookie, or hash of the client IP.
  • ✔Cost: uneven load, lost sessions on failure, harder scaling.
  • ✔IP hash trap: one NAT or office can look like one user.
  • ✔Better: stateless servers plus a shared session store or a signed token.
  • ✔Operations: expire the stickiness, drain before removing a server.
  • ✔One line: “Sticky sessions fix a state problem with a routing trick. Fix the state if you can.”
← Previous
Health Checks
Next →
Global Load Balancing