Course contentsShow
← System Design
Lesson 60 of 1,9192. Scaling FoundationsFree lesson

Sticky Sessions and Load Balancer Affinity

Routing requests from the same client to the same server instance to maintain in-memory state.

Sticky Sessions and Load Balancer Affinity

What You'll Learn

You'll learn how to route repeat requests from the same user to the same server instance, preserving in-memory state without external storage.

The Core Problem

Imagine you walk into a coffee shop with five baristas. You order a complex drink with customizations. Halfway through making it, your barista takes a break and another barista has to restart from scratch—frustrating, right?

This is exactly what happens in distributed systems when different servers handle sequential requests from the same user. If a server stores your shopping cart or login session in its own memory, switching servers means losing that data.

How Sticky Sessions Work

Sticky sessions (also called session affinity) solve this by configuring your load balancer to remember which server initially handled a user's request. All subsequent requests from that same user route back to the same server instance.

The load balancer typically uses a cookie, session ID, or the client's IP address to identify returning users and maintain the binding.

The Trade-off

While sticky sessions let you scale stateful services horizontally (remember lesson 58?), they create new challenges:

  • If the "sticky" server crashes, that user's session is lost
  • Uneven load distribution if some users generate more requests
  • Harder to add/remove servers without disrupting existing sessions

This is why externalizing state (lesson 59) is often preferred—but sticky sessions remain useful for performance optimization or legacy applications that can't easily be refactored.

Key Takeaway: Sticky sessions route a user's requests to the same server instance to preserve in-memory state, trading perfect load distribution for simpler horizontal scaling of stateful services.