Course contentsShow
← Cloud and Infrastructure
Lesson 2467 of 2,98953. High Availability PatternsFree lesson

Sticky Sessions and Affinity

Learn how session affinity directs requests to specific instances and its impact on availability.

Sticky Sessions and Affinity

What You'll Learn

You'll understand how session affinity routes users to specific backend instances and why this impacts high availability design.

The Core Idea

Sticky sessions (also called session affinity) ensure that requests from the same client are consistently routed to the same backend server instance. The load balancer "remembers" which server handled your first request and sends all subsequent requests there.

Think of it like having a favorite cashier at your grocery store. Instead of going to any available checkout lane, you always wait for the same person because they already know your preferences and have your loyalty card info pulled up.

How It Works

Load balancers typically use one of these methods:

  • Cookie-based affinity: The load balancer inserts a cookie identifying the backend instance
  • IP-based affinity: Routes based on the client's source IP address
  • Application-controlled: The app explicitly tells the load balancer where to route

The Availability Trade-off

Here's the critical insight: sticky sessions reduce availability in exchange for simpler state management.

Why? If the instance handling your session fails, your session data is lost. The load balancer can route you to a healthy instance, but you'll need to start over (re-login, lost shopping cart, etc.). You've created a single point of failure for that user's session.

With stateless services, any healthy instance can handle any request—you lose no session data during failover because the state lives externally (like in a distributed cache or database).

When to Use Sticky Sessions

Use them sparingly:

  • Legacy apps that can't be refactored to stateless
  • Short-lived sessions where restart is acceptable
  • Non-critical user experiences

Key Takeaway: Sticky sessions sacrifice high availability by tying user sessions to specific instances, making failover lossy. Prefer stateless designs with external session storage for truly resilient systems.