Skip to content
Optimal Lab

Databases · interactive

Read replicas and replication lag

Writes go to the primary; reads are spread across replicas that copy its log a moment later. Ada renames herself and the page reloads straight away. Does she see her new name?

primary

takes the write at 0 ms

name = "Ada Lovelace"

replica 1

lags 800 ms

name = "Ada"

replica 2

lags 300 ms

name = "Ada"

profile page, read at 200 ms · served by replica 1 in 3 ms

Hello, Ada

Replica 1 hasn't applied the write yet: the user sees their old name.

Route reads to

Step 2 of 4

  1. 1

    Replicas scale reads

    Each replica streams the primary's write-ahead log and applies it. Add more for more read capacity.

    Writes still all go to one primary.

  2. 2

    They're always a little behind

    Usually milliseconds; under load or a long query, seconds or more. Reads can go back in time between replicas.

    Monitor replication lag.

  3. 3

    Read your own writes

    After a user writes, send their reads to the primary for a short time, or wait until the replica has applied their write's log position.

    pg_last_wal_replay_lsn() ≥ write LSN

  4. 4

    Pick per query

    Dashboards, search and other users' content tolerate a little lag. Balances, permissions and “did my edit save?” don't.

    Synchronous replicas trade write latency for zero lag.

In production

Tools and technologies

Managed databases make replicas one click; lag is still yours.

Not tied to one language — use these names when you search docs or design a system.