Sticky sessions, also known as session affinity, is a load balancing technique that ensures all requests from a specific user are consistently routed to the same backend server throughout that user’s session.
In simpler terms, the load balancer “sticks” a user to one server so that their session data (like login status or shopping cart) remains intact on that server.
Understanding Sticky Sessions (Session Affinity)
In a typical web application deployed on multiple servers, a load balancer distributes incoming requests across the servers for efficiency.
However, HTTP is a stateless protocol, which means each request is independent and does not remember previous interactions. This can lead to problems if user-specific data is stored in a single server’s memory.
For example, if you’re shopping online and adding items to your cart, you might suddenly find yourself logged out or your cart emptied if a new request gets routed to a different server that doesn’t have your session information.
Image scaled to 85%
Sticky sessions solve this problem by binding a user’s session to one server, ensuring continuity of data and experience.
To achieve session affinity, the load balancer needs a way to identify and remember which server a user is tied to.
Typically, this is done by assigning an identifier to the user, often via a cookie in the user’s browser or by tracking the client’s IP address.
On the user’s first request, the load balancer might set a special session cookie that encodes which server handled the request.
Thereafter, the load balancer reads this cookie on each request and routes the user to the same server that served them initially. (IP-based sticky sessions are another method, but are less reliable if multiple users share an IP or if a single user’s IP changes.)
Image scaled to 85%
This way, all session data (like your login state or cart contents) stays on one server, and the application doesn’t need to constantly share session information between servers.
An easy way to understand sticky sessions is by analogy: it’s like having a favorite waiter at a restaurant who always serves you and remembers your order.
Just as that waiter can provide personalized, consistent service because they know you, a specific server can handle all of a user’s requests and “remember” their session data.
This improves user experience by avoiding scenarios where information might get lost due to bouncing between different servers.