Session Affinity (Sticky Sessions)
What you'll learn: How load balancers can route a user's requests to the same server consistently to maintain session state.
The Core Idea
Session affinity, often called sticky sessions, is a load balancing strategy that ensures all requests from a specific client always go to the same backend server. Instead of distributing requests freely across all servers, the load balancer "remembers" which server handled a client's first request and routes all subsequent requests from that client to the same server.
Why This Matters
Remember from earlier lessons that stateful services store information about each user's session (like shopping cart contents or login state) directly on the server. Without session affinity, consecutive requests from the same user might hit different servers—and each server wouldn't know about the user's previous interactions.
Session affinity solves this by binding the client to one server, typically using:
- Cookies: The load balancer sets a cookie containing the server identifier
- IP address: Routes based on the client's IP (similar to IP Hash algorithm we covered earlier)
A Restaurant Analogy
Imagine a restaurant where each waiter maintains a mental note of what you've ordered. If you had a different waiter every time you spoke, you'd have to repeat your entire order. Sticky sessions ensure you get the same waiter throughout your meal—they remember your previous requests.
The Trade-off
While sticky sessions enable stateful applications to work across multiple servers, they reduce the benefits of load balancing. If one server fails, all its "sticky" users lose their session data. They also prevent truly even distribution of load.
Key Takeaway: Session affinity binds clients to specific servers using cookies or IP addresses, enabling stateful applications to scale horizontally while maintaining user session continuity—at the cost of reduced flexibility and fault tolerance.