Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 25 min · revision 1

Observing replication lag with a read replica

Run a PostgreSQL 17 primary and a streaming read replica in Docker, freeze replay to make lag visible on demand, reproduce a stale read, a lost read-your-writes and a non-monotonic read, and fix read-your-writes with a WAL position token.

Contentsand lesson path

What you will learn

  • Explain replication-lag anomalies on read replicas (stale reads, non-monotonic reads, lost read-your-writes) and choose mitigations.

01. Goal and setup

While writes are flowing, an asynchronous replica is usually a little behind its primary. In this lab you will measure that gap in bytes and in time, and watch what it does to users. Real lag comes and goes in milliseconds, so you will pause replay on the replica: it keeps receiving the primary's write-ahead log (WAL) but stops applying it until you resume.

You need Docker, a bash shell (on Windows, use WSL 2) and Python 3.10 or later. The lab was tested with Docker 29.8.0, the postgres:17-alpine image (PostgreSQL 17.11; a newer 17.x image prints its own minor version in step 1), Python 3.12.13 and psycopg 3.3.9. Both servers listen on 127.0.0.1 only, on ports 18541 (primary) and 18542 (replica). Data directories live in memory (--tmpfs), so removing the containers removes the data; real deployments use persistent volumes.

Create a folder for the lab and work inside it:

Terminal
mkdir repl-lab && cd repl-lab

You will reproduce three replication-lag anomalies:

  • A stale read: a read from a replica returns data that the primary has already changed.
  • A read-your-writes violation: a user saves something, reloads, and their own change is missing. Read-your-writes is a guarantee for one user's session: after a write succeeds, that user's later reads include it.
  • A non-monotonic read: a user sees a newer state and then an older one, as if time went backwards. This happens when successive reads go to copies with different lag.

Read-your-writes can be provided in several ways: send the user's reads to the primary for a while, read from a replica only once it has caught up with the user's last write, or keep the user on one up-to-date copy. "For a while" is a product decision with a measured lag behind it, not a fixed number of seconds. In step 7 you will build the second option.

02. Step 1: Start the primary

Create a Docker network so that the replica can find the primary by name, then start the primary. The loop waits until the server accepts TCP connections. The two shell functions run psql inside each container.

Terminal
docker network create dbscale-net
docker run -d --name dbscale-primary --network dbscale-net -e POSTGRES_PASSWORD=lab \
  -p 127.0.0.1:18541:5432 --tmpfs /var/lib/postgresql/data postgres:17-alpine
for i in $(seq 30); do
  docker exec dbscale-primary pg_isready -h 127.0.0.1 -U postgres -q && break
  sleep 1
done
pg_primary() { docker exec -i dbscale-primary psql -X -U postgres "$@"; }
pg_replica() { docker exec -i dbscale-replica psql -X -U postgres "$@"; }
docker exec dbscale-primary postgres --version
Expected output (after the two IDs that docker prints; your 17.x minor version may be newer)
postgres (PostgreSQL) 17.11

Save the following as primary-setup.sql. It creates a role that may stream the WAL (REPLICATION) and a comments table with one row. Load it, allow the role to connect for replication in pg_hba.conf (the database name all does not cover replication connections), and reload the configuration.

SQL · primary-setup.sql
CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'replpass';
CREATE TABLE comments (
  id      bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id integer NOT NULL,
  body    text NOT NULL
);
INSERT INTO comments (user_id, body) VALUES (1, 'Welcome to the thread');
Terminal
pg_primary < primary-setup.sql
docker exec dbscale-primary sh -c \
  'echo "host replication replicator all scram-sha-256" >> "$PGDATA/pg_hba.conf"'
pg_primary -c 'SELECT pg_reload_conf();'
Expected output
CREATE ROLE
CREATE TABLE
INSERT 0 1
 pg_reload_conf 
----------------
 t
(1 row)

03. Step 2: Clone the replica

A streaming replica starts as a byte-for-byte copy of the primary, taken by pg_basebackup. -X stream streams the WAL written during the copy, -C -S replica1 creates a replication slot so that the primary keeps any WAL the replica has not received yet, and -R writes a standby.signal file plus the connection settings, so the copy starts as a standby. The container runs the backup as the postgres user, then starts the server through the image's normal entrypoint.

Terminal
docker run -d --name dbscale-replica --network dbscale-net -e PGPASSWORD=replpass \
  -p 127.0.0.1:18542:5432 --tmpfs /var/lib/postgresql/data postgres:17-alpine \
  sh -c 'gosu postgres pg_basebackup -h dbscale-primary -U replicator \
           -D /var/lib/postgresql/data -R -X stream -C -S replica1 &&
         exec docker-entrypoint.sh postgres'
for i in $(seq 30); do
  docker exec dbscale-replica pg_isready -h 127.0.0.1 -U postgres -q && break
  sleep 1
done
docker exec dbscale-replica sh -c 'cd "$PGDATA" && ls standby.signal &&
  grep -oE "(user|password|host)=[^ ]*|primary_slot_name.*" postgresql.auto.conf'
Expected output (after the ID that docker prints)
standby.signal
user=replicator
password=replpass
host=''dbscale-primary''
primary_slot_name = 'replica1'

The replica connects to dbscale-primary as replicator through the slot replica1. Note that -R stored the password in plain text: fine for a lab, but in production keep it in a protected password file or a secrets manager.

04. Step 3: Check that replication works

Check which standbys stream from the primary and that the replica is in recovery (replaying WAL). Then write on the primary, read on the replica, and try to write on the replica.

Terminal
pg_primary -c 'SELECT application_name, state, sync_state FROM pg_stat_replication;'
pg_replica -At -c 'SELECT pg_is_in_recovery();'
pg_primary -c "INSERT INTO comments (user_id, body) VALUES (5, 'Replication works');"
sleep 1
pg_replica -c 'SELECT id, user_id, body FROM comments ORDER BY id;'
pg_replica -c "INSERT INTO comments (user_id, body) VALUES (5, 'Write here?');"
Expected output
 application_name |   state   | sync_state 
------------------+-----------+------------
 walreceiver      | streaming | async
(1 row)

t
INSERT 0 1
 id | user_id |         body          
----+---------+-----------------------
  1 |       1 | Welcome to the thread
  2 |       5 | Replication works
(2 rows)

ERROR:  cannot execute INSERT in a read-only transaction

The standby streams asynchronously (async), so commits on the primary do not wait for it. The new row arrived within a second, and the replica refuses writes.

05. Step 4: Measure lag while the replica keeps up

Every WAL record has a position, the log sequence number (LSN), such as 0/3000210, and pg_wal_lsn_diff(a, b) turns two positions into bytes. On the primary, pg_stat_replication shows how far each standby has replayed (replay_lsn) and a time estimate (replay_lag). On the replica, pg_last_wal_receive_lsn() is the last position received and flushed to disk, pg_last_wal_replay_lsn() the last one applied, and pg_last_xact_replay_timestamp() the primary's commit time of the last replayed transaction.

Run both queries, wait ten seconds without writing anything, and run the replica query again:

Terminal
pg_primary -c "SELECT application_name,
  pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS bytes_not_replayed,
  replay_lag
FROM pg_stat_replication;"
pg_replica -c "SELECT pg_last_wal_receive_lsn() AS received,
  pg_last_wal_replay_lsn() AS replayed,
  now() - pg_last_xact_replay_timestamp() AS since_last_commit;"
sleep 10
pg_replica -c "SELECT pg_last_wal_receive_lsn() AS received,
  pg_last_wal_replay_lsn() AS replayed,
  now() - pg_last_xact_replay_timestamp() AS since_last_commit;"
Illustrative output (positions and times differ on every run)
 application_name | bytes_not_replayed |   replay_lag    
------------------+--------------------+-----------------
 walreceiver      |                  0 | 00:00:00.010096
(1 row)

 received  | replayed  | since_last_commit 
-----------+-----------+-------------------
 0/3000210 | 0/3000210 | 00:00:01.343581
(1 row)

 received  | replayed  | since_last_commit 
-----------+-----------+-------------------
 0/3000248 | 0/3000248 | 00:00:11.427718
(1 row)

Zero bytes are waiting and the replica has applied everything it received, yet since_last_commit grew from about 1 s to about 11 s. Nothing is wrong: no transaction has committed since step 3, so the last replayed commit simply gets older. A lag alert built on this timestamp fires on every quiet night. Byte distances between LSNs, or a heartbeat row that the primary updates every few seconds, measure lag without that blind spot.

06. Step 5: Freeze replay and read stale data

Pause replay on the replica and check that it paused. Then user 42 posts a comment on the primary, and both servers run the same query. The last two queries show where the WAL is stuck.

Terminal
pg_replica -c 'SELECT pg_wal_replay_pause();'
sleep 1
pg_replica -At -c 'SELECT pg_get_wal_replay_pause_state();'
pg_primary -c "INSERT INTO comments (user_id, body)
  VALUES (42, 'Is the 18:05 on time?');"
pg_primary -At -c 'SELECT count(*) FROM comments WHERE user_id = 42;'
sleep 1
pg_replica -At -c 'SELECT count(*) FROM comments WHERE user_id = 42;'
Expected output
 pg_wal_replay_pause 
---------------------
 
(1 row)

paused
INSERT 0 1
1
0
Terminal
pg_replica -c "SELECT
  pg_last_wal_receive_lsn() > pg_last_wal_replay_lsn() AS wal_waiting,
  pg_wal_lsn_diff(pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn())
    AS bytes_waiting;"
pg_primary -c "SELECT
  pg_wal_lsn_diff(pg_current_wal_lsn(), flush_lsn) AS bytes_not_flushed,
  pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS bytes_not_replayed,
  replay_lag
FROM pg_stat_replication;"
Illustrative output (byte counts and times vary)
 wal_waiting | bytes_waiting 
-------------+---------------
 t           |           200
(1 row)

 bytes_not_flushed | bytes_not_replayed |   replay_lag    
-------------------+--------------------+-----------------
                 0 |                200 | 00:00:00.000306
(1 row)

The primary has user 42's comment and the replica does not: a stale read. If user 42's page reloads from this replica, it is also a read-your-writes violation. The WAL is not lost: bytes_not_flushed is 0, so the replica already holds the comment in its WAL (on disk in a real deployment, in memory here), and wal_waiting shows that it has simply not applied it. Received but not replayed means "safe, but invisible".

Do not trust replay_lag here. It is measured when the standby reports progress, so right after replay stops it can still show an old, tiny value, as in this run, and it starts to grow only later. The byte count is exact at once.

07. Step 6: Watch time go backwards

Many setups send reads to any server, primary included. Simulate four page loads that alternate between the two:

Terminal
for node in primary replica primary replica; do
  echo "$node: $(pg_$node -At -c 'SELECT count(*) FROM comments')"
done
Expected output
primary: 3
replica: 2
primary: 3
replica: 2

A reader sees three comments, then two, then three: a non-monotonic read. No single copy is wrong; mixing copies with different lag is. Keeping each user on one copy, or never serving a user from a copy older than the one they last read, keeps time moving forwards.

08. Step 7: Read your own writes with a WAL position token

The fix need not send every read to the primary. After a write, the application asks the primary for its WAL insert position, which is at or past the write's commit record, and keeps it with the user's session, for example in a cookie. That position is the token. A later read for that user goes to the replica only once pg_last_wal_replay_lsn() there has reached the token. If it has not got there within a short wait, the read goes to the primary.

Install psycopg in a virtual environment and save the script as ryw.py:

Terminal
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -q --disable-pip-version-check "psycopg[binary]"
python -c "import psycopg; print(psycopg.__version__)"
Expected output (a newer version is fine)
3.3.9
Python · ryw.py
"""Read-your-writes with a WAL position token.

python ryw.py post USER TEXT    write on the primary and print the token
python ryw.py read USER         read from the replica, whatever its lag
python ryw.py read USER TOKEN   read from the replica once it has replayed TOKEN
"""

import sys
import time

import psycopg

PRIMARY = 'postgresql://postgres:[email protected]:18541/postgres'
REPLICA = 'postgresql://postgres:[email protected]:18542/postgres'
WAIT_MS = 1000  # the longest a read may wait for the replica
COUNT = 'SELECT count(*) FROM comments WHERE user_id = %s'


def post(user_id: int, body: str) -> str:
    with psycopg.connect(PRIMARY, autocommit=True) as conn:
        conn.execute(
            'INSERT INTO comments (user_id, body) VALUES (%s, %s)', (user_id, body)
        )
        # The insert position is at or past this commit's record, even when
        # synchronous_commit = off lets COMMIT return before its WAL is written.
        return conn.execute('SELECT pg_current_wal_insert_lsn()::text').fetchone()[0]


def wait_for(replica: psycopg.Connection, token: str | None) -> bool:
    """True once the replica has replayed the token; False after WAIT_MS."""
    deadline = time.monotonic() + WAIT_MS / 1000
    sql = 'SELECT pg_last_wal_replay_lsn() >= %s::pg_lsn'
    while token and not replica.execute(sql, (token,)).fetchone()[0]:
        if time.monotonic() >= deadline:
            return False
        time.sleep(0.05)
    return True


def read(user_id: int, token: str | None) -> None:
    with psycopg.connect(REPLICA, autocommit=True) as replica:
        if wait_for(replica, token):
            n = replica.execute(COUNT, (user_id,)).fetchone()[0]
            print(f'replica: user {user_id} has {n} comment(s)')
            return
    print(f'replica is behind the token after {WAIT_MS} ms: reading the primary')
    with psycopg.connect(PRIMARY) as primary:
        n = primary.execute(COUNT, (user_id,)).fetchone()[0]
    print(f'primary: user {user_id} has {n} comment(s)')


if __name__ == '__main__':
    if sys.argv[1] == 'post':
        print(post(int(sys.argv[2]), sys.argv[3]))
    else:
        read(int(sys.argv[2]), sys.argv[3] if len(sys.argv) > 3 else None)

Replay is still paused. User 7 posts a comment, and the shell variable TOKEN plays the part of the session cookie. Then read once without the token and once with it:

Terminal
TOKEN=$(python ryw.py post 7 'Platform 2 is closed today')
echo "$TOKEN"
python ryw.py read 7
python ryw.py read 7 "$TOKEN"
Expected output (the token may differ on your machine)
0/30424B0
replica: user 7 has 0 comment(s)
replica is behind the token after 1000 ms: reading the primary
primary: user 7 has 1 comment(s)

Without the token, user 7 sees no comment. With it, the read sees that the replica is behind the user's write and uses the primary. Users without a token read the replica.

09. Step 8: Resume replay and catch up

Terminal
pg_replica -c 'SELECT pg_wal_replay_resume();'
python ryw.py read 7 "$TOKEN"
sleep 1
pg_primary -c "SELECT
  pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS bytes_not_replayed
FROM pg_stat_replication;"
for node in primary replica; do
  echo "$node: $(pg_$node -At -c 'SELECT count(*) FROM comments')"
done
Expected output
 pg_wal_replay_resume 
----------------------
 
(1 row)

replica: user 7 has 1 comment(s)
 bytes_not_replayed 
--------------------
                  0
(1 row)

primary: 4
replica: 4

Once replay resumed, the replica applied the waiting WAL within the one-second wait, so the token read was served by the replica, and both servers hold four comments. Clean up:

Terminal
deactivate
docker rm -f -v dbscale-primary dbscale-replica
docker network rm dbscale-net

10. Check your understanding

Practice check · 3 questions

Reading the replica

Three questions about what you measured in this lab.

Q1. A monitor pages when `now() - pg_last_xact_replay_timestamp()` on a replica exceeds 60 s. It pages most nights around 03:00, when nobody writes, though the replica is healthy. Which change fixes the alert?
Q2. In step 5, replay was paused while WAL kept arriving. Suppose the primary had died at that moment and you had promoted this replica. Would user 42's comment survive?
Q3. `ryw.py` reads `pg_current_wal_insert_lsn()` after the INSERT has committed. A teammate moves that call to just before the INSERT, to save a round trip. What breaks?
Practice only: not graded, not saved, not evidence.

11. Apply it

Take the lab towards the skill's practice task:

  1. Build the practice task's other mitigation: store the time of each user's last write in the session and send that user's reads to the primary while it is recent. Base the window on measured lag plus a margin. Compared with the token, which sends more reads to the primary, and which fails when lag exceeds the window?
  2. Add a second replica (port 18543, slot replica2), pause only one, and make each user read from the same replica every time. Show that the non-monotonic read disappears.
  3. Run ALTER SYSTEM SET synchronous_standby_names = '*' on the primary and reload. Pause replay, then insert once under the default synchronous_commit = on and once under remote_apply. The second insert waits; cancel it from another terminal with pg_cancel_backend() (its wait_event is SyncRep) and read the warning.

12. Review prompt

Without looking back, explain: how a streaming replica is created and what its slot costs; received versus replayed WAL, for durability and for reads; why now() - pg_last_xact_replay_timestamp() misleads on a quiet system; how each of the three anomalies arises; and how the token restores read-your-writes.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check