Course contentsShow
← System Design
Lesson 225 of 1,9196. Database Scaling: Read ReplicasFree lesson

Sticky Sessions and Primary Reads

Temporarily routing all requests to primary after a write to guarantee immediate consistency for that session.

Sticky Sessions and Primary Reads

What you'll learn: How to route a user's requests to the primary database temporarily after they perform a write, ensuring they always see their own updates.

The Read-After-Write Challenge

You've split reads and writes across primary and replicas. A user submits a form (writes to primary), but their next request might hit a lagging replica that hasn't received the update yet. They refresh and their change is "gone" — frustrating and confusing.

How Sticky Sessions Solve This

Sticky sessions create a temporary affinity between a user's session and the primary database after any write operation. For a short window (say, 5-10 seconds), all subsequent reads from that user route to the primary instead of replicas.

Think of it like a VIP pass: after you make a change, you get temporary "backstage access" to the primary database where your changes are guaranteed to be visible.

Implementation Flow

  1. User performs a write → application writes to primary
  2. Application sets a session marker (cookie, session variable, timestamp)
  3. For the next N seconds, that user's reads route to primary
  4. After the window expires, reads return to replicas (presumably caught up by then)

This is different from full sticky sessions (always same replica) — here you're sticky to the primary, temporarily.

Why This Works

Replication lag is usually under a second. By routing to primary for a few seconds post-write, you guarantee the user sees their own changes while still benefiting from replica read scaling for everyone else.

Key Takeaway: Sticky sessions with primary reads temporarily route a user to the primary after writes, guaranteeing read-after-write consistency for that session without sacrificing overall read scalability.