Sticky Sessions and Replica Affinity
You'll learn: How to ensure users always read their own writes by binding their session to a single database replica.
The Problem Recap
When you have multiple read replicas, a user might write data to the primary, then immediately read from a different replica that hasn't caught up yet—causing them to see stale data. Session-based routing (from our previous lesson) solves this for writes, but what about subsequent reads?
The Sticky Solution
Sticky sessions (also called replica affinity) mean that once a user is assigned to a specific read replica, all their subsequent reads go to that same replica for the duration of their session.
Why this works:
- Even if that replica is slightly behind the primary, it will always show data in the order it received it
- The user sees monotonic reads—time never goes backward from their perspective
- No complex coordination needed; the load balancer just routes consistently
Real-World Analogy
Imagine a library with multiple clerks checking in returned books at different speeds. If you return a book and then immediately ask different clerks if it's available, you might get inconsistent answers. But if you always ask the same clerk, they'll never tell you the book is unavailable after telling you it was checked in—their view of reality stays consistent, even if it's slightly delayed.
Implementation
The load balancer uses a session cookie or connection hash to map each user to one replica. That user's reads stay pinned there until their session ends or the replica fails.
Key Takeaway: Sticky sessions provide monotonic reads by routing each user's requests to a single replica, ensuring they never see data go backward in time without needing complex database coordination.