DAT-46Recommended
Read from replicas only what may lag
Send reads to a replica only when a few seconds of delay is acceptable. Read your own writes from the primary.
How to do it
After a user changes something, read it back from the primary for that user, or wait until the replica has caught up. In PostgreSQL, keep the primary's log position after each write, from pg_current_wal_lsn(), in the user's session. Send that user's reads to a replica only once its pg_last_wal_replay_lsn() has reached that position, and to the primary until then. Monitor replica lag and stop routing reads to a replica that falls behind. Set the allowed delay per read as Decide how stale a cache may be does for caches.
Examples
JavaScript example
export async function saveAndRemember(session, work) {
const result = await primary.tx(async tx => {
const value = await work(tx);
session.lastWriteLsn = (await tx.one('SELECT pg_current_wal_lsn()::text AS lsn')).lsn;
return value;
});
return result;
}
export async function readerFor(session) {
if (!session.lastWriteLsn) return replica;
const { caught_up } = await replica.one(
'SELECT pg_last_wal_replay_lsn() >= $1::pg_lsn AS caught_up', [session.lastWriteLsn]);
return caught_up ? replica : primary;
}
Python example
def save_and_remember(session, work):
with primary.transaction() as tx:
value = work(tx)
session["last_write_lsn"] = tx.execute("SELECT pg_current_wal_lsn()::text").fetchone()[0]
return value
def reader_for(session):
lsn = session.get("last_write_lsn")
if lsn is None:
return replica
caught_up = replica.execute(
"SELECT pg_last_wal_replay_lsn() >= %s::pg_lsn", (lsn,)).fetchone()[0]
return replica if caught_up else primary
How to check
A test saves a change and reads it back at once, 100 times in a row, while replica lag is simulated. Every read shows the change.
Sources
Related rules
- ARC-89 Choose how fresh each piece of shared data must be in Clean code and architecture
- DAT-29 Test what a failover loses in Data and databases
- SCL-35 Decide how stale a cache may be in Scaling
- DEN-1 Keep heavy reads off the production database in Data engineering
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/data/caches-and-copies/replica-lag">Agent Wranglers data and databases playbook</a>. In code you write, add a comment next to it with the same link.