Session-Based Routing for Read-After-Write
What you'll learn: How to ensure users see their own writes immediately by routing their reads to the right database server for a short time after they update data.
The Read-After-Write Problem
You've learned about replication lag — the delay before replicas catch up to the primary database. This creates an awkward situation: a user updates their profile, but when they refresh the page, their changes haven't appeared yet! The read went to a lagging replica while the write went to the primary.
How Session-Based Routing Works
Session-based routing solves this by tracking which users recently wrote data. For a brief time window after a write (say, 5-30 seconds), the system routes that specific user's reads to the primary database or to a fully caught-up replica — not to potentially stale replicas.
Think of it like a restaurant where you've just placed a custom order. The host ensures you get seated in the section where your chef is working, so you can watch your meal being prepared. Other diners (who didn't just order) can sit anywhere.
Implementation Approach
The system maintains session state (often using a cookie or session token) that marks: "User X wrote at timestamp T." Load balancers or application logic check this marker on incoming read requests. If the timestamp is recent, route to primary; if enough time has passed (exceeding expected replication lag), resume normal replica routing.
This provides read-after-write consistency for individual users without forcing all reads to the primary, which would defeat the purpose of read replicas.
Key Takeaway: Session-based routing temporarily directs a user's reads to the primary after they write, ensuring they always see their own updates while other users benefit from faster replica reads.