Session Affinity (Sticky Sessions)
What you'll learn: How to ensure requests from the same user keep going back to the same server when your application stores session data.
The Problem with Stateful Applications
Imagine you log into a shopping website and add items to your cart. Your cart data might be stored in memory on Server A. Now imagine the load balancer sends your next request to Server B—suddenly your cart looks empty! This happens because Server B doesn't know about the session data Server A was holding for you.
What is Session Affinity?
Session affinity (also called sticky sessions) is a load balancer feature that "remembers" which backend server handled your first request, then routes all your subsequent requests to that same server for the duration of your session.
Think of it like having a favorite barista at a coffee shop. Instead of going to whoever's free, you always go to the same person who remembers how you like your coffee.
How It Works
The load balancer typically uses a cookie to track which server you're assigned to:
- Your first request arrives → Load balancer picks Server A
- Load balancer sets a cookie in the response (e.g.,
AWSALB=server-a-id) - Your browser sends this cookie with every subsequent request
- Load balancer reads the cookie and routes you back to Server A
Trade-offs
Benefits: Simpler application code—no need to share session state across servers.
Drawbacks: If Server A fails or gets removed, your session is lost. Also, sticky sessions can create uneven load distribution if some users stay logged in much longer than others.
Key Takeaway: Session affinity routes all requests from the same client to the same backend server using cookies, enabling stateful applications but sacrificing some load balancing efficiency and fault tolerance.