Day 8: Read Replicas and Replication Lag
Goal: Set up a read replica on s2, measure the replication lag, let
kurzread from the replica, fail on freshly created links and fix the problem · Duration: approx. 90 min · Prerequisite: Day 7
Briefing
- Since Day 7, everything hangs on one database on s3. The cache intercepts most reads, but every miss, every new feature and every cold start lands there.
- A read replica is a second PostgreSQL instance that replays all changes of the primary. Anyone may read there; only the primary may write.
- The catch: replaying takes time. Whoever has just written and immediately reads from the replica sometimes doesn’t find their own change. That is exactly what you reproduce and fix today.
| Term | Meaning |
|---|---|
| WAL | Write-Ahead Log, PostgreSQL’s change log. The replica receives it as a stream |
| Replication slot | remembers on the primary how far the replica has gotten, so that no WAL still needed is deleted |
| Lag | distance between what the primary has written and what the replica has replayed |
| asynchronous | the primary confirms immediately, the replica follows later (default) |
| synchronous | the primary waits until the replica has the change |
PostgreSQL 18 has been installed on s2 since Day 0, but switched off. Today it becomes the replica.
Drill 1: Setting Up the Replica
On s3, the replica needs a role with replication privilege, a line in
pg_hba.conf and a slot:
# on s1
mkdir -p ~/sd/tag08 && cd ~/sd/tag08
ssh s3 "sudo -u postgres psql -c \"CREATE ROLE replikat WITH REPLICATION LOGIN PASSWORD 'lab-repl-123'\""
ssh s3 "echo 'host replication replikat 172.16.0.0/24 scram-sha-256' \
| sudo tee -a /etc/postgresql/18/main/pg_hba.conf"
ssh s3 "sudo systemctl reload postgresql"
ssh s3 "sudo -u postgres psql -c \"SELECT pg_create_physical_replication_slot('s2')\""Expected:
CREATE ROLE
host replication replikat 172.16.0.0/24 scram-sha-256
pg_create_physical_replication_slot
-------------------------------------
(s2,)
(1 row)
Now on s2, replace the empty data directory with a copy from s3.
pg_basebackup fetches all files and also streams the WAL
that is generated in the meantime:
# on s1
ssh s2 "sudo systemctl stop postgresql && sudo rm -rf /var/lib/postgresql/18/main"
ssh s2 "time sudo -u postgres env PGPASSWORD=lab-repl-123 pg_basebackup -h s3 -U replikat \
-D /var/lib/postgresql/18/main -R -X stream -S s2 -P" 2>&1 | tr '\r' '\n' | tail -5
ssh s2 "sudo cat /var/lib/postgresql/18/main/postgresql.auto.conf | cut -c1-60"
ssh s2 "sudo ls /var/lib/postgresql/18/main/standby.signal"Expected:
403019/403019 kB (100%), 1/1 tablespace
real 0m3.865s
user 0m1.314s
sys 0m1.820s
# Do not edit this file manually!
# It will be overwritten by the ALTER SYSTEM command.
listen_addresses = '*'
primary_conninfo = 'user=replikat password=''lab-repl-123''
primary_slot_name = 's2'
/var/lib/postgresql/18/main/standby.signal
400 MB in four seconds. The -R switch did two things:
primary_conninfo and primary_slot_name are in
postgresql.auto.conf, and the empty file
standby.signal tells PostgreSQL at startup: you are a
replica. listen_addresses came along because you set it on
s3 via ALTER SYSTEM on Day 0. Only pg_hba.conf
lives under /etc on Debian and Ubuntu and is not
copied:
# on s1
ssh s2 "echo 'host all all 172.16.0.0/24 scram-sha-256' | sudo tee -a /etc/postgresql/18/main/pg_hba.conf"
ssh s2 "sudo systemctl enable --now postgresql"
sleep 2
ssh s3 "sudo -u postgres psql -x -c 'select client_addr, state, sync_state, sent_lsn,
replay_lsn, replay_lag from pg_stat_replication'"
export PGPASSWORD=lab-kurz-123
psql -h s2 -U kurz -d kurz -c "select pg_is_in_recovery(), count(*) from links"
psql -h s2 -U kurz -d kurz -c "insert into links (code, url) values ('test123', 'https://example.org')"Expected:
host all all 172.16.0.0/24 scram-sha-256
-[ RECORD 1 ]----------------
client_addr | 172.16.0.228
state | streaming
sync_state | async
sent_lsn | 0/33000060
replay_lsn | 0/33000060
replay_lag | 00:00:00.053385
pg_is_in_recovery | count
-------------------+---------
t | 2211033
(1 row)
ERROR: cannot execute INSERT in a read-only transaction
s2 is streaming, is in recovery mode (t), knows all
links and refuses writes. sent_lsn and
replay_lsn are positions in the WAL. If they are equal, the
replica is up to date.
Save your progress? Sign up for free
Drill 2: Making the Lag Visible
When idle, the lag is in the milliseconds. It gets interesting when the primary writes a lot. A ballast table with two million rows generates around 700 MB of WAL, and every few seconds you check how far s2 lags behind:
# on s1
psql -h s3 -U kurz -d kurz -c "create table ballast (id bigint, text text)"
( psql -h s3 -U kurz -d kurz -c "insert into ballast select i, repeat('x', 200)
from generate_series(1, 2000000) i" ) &
for i in $(seq 1 16); do
ssh s3 "sudo -u postgres psql -tAc \"select now()::time(0),
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)), replay_lag
from pg_stat_replication\""
sleep 1
done
waitExpected (your numbers will differ):
CREATE TABLE
06:55:08|7582 kB|00:00:00.012341
06:55:10|118 MB|00:00:00.012341
06:55:12|240 MB|00:00:00.012341
06:55:14|302 MB|00:00:00.712297
06:55:16|271 MB|00:00:02.990366
INSERT 0 2000000
06:55:18|175 MB|00:00:03.983617
06:55:20|175 MB|00:00:03.983617
06:55:22|0 bytes|00:00:02.419318
06:55:23|0 bytes|00:00:02.419318
06:55:25|0 bytes|00:00:02.419318
06:55:27|979 kB|00:00:00.052236
06:55:29|0 bytes|00:00:00.017506
06:55:31|1436 kB|00:00:00.014119
06:55:34|984 bytes|00:00:00.048895
06:55:35|0 bytes|00:00:00.020593
Up to 302 MB and almost four seconds behind, even though both machines are on the same network. The replica replays the WAL in a single process; the primary writes with any number of them.
Look at the lines around 06:55:22: 0 bytes behind, but
replay_lag still shows 2.4 seconds. The column is only
updated when new WAL arrives, and shows the last measured value in
between. For alerts, the byte distance is more reliable.
How long is a fresh link invisible on s2? You create it in the middle of the write load on s3 and query s2 every 100 ms:
# on s1
( psql -h s3 -U kurz -d kurz -qc "insert into ballast select i, repeat('x', 200)
from generate_series(1, 2000000) i" ) &
sleep 7
psql -h s3 -U kurz -d kurz -qc "insert into links (code, url) values ('frisch2', 'https://example.org/frisch')"
start=$(date +%s%N)
until [ "$(psql -h s2 -U kurz -d kurz -tAc "select count(*) from links where code = 'frisch2'")" = 1 ]
do sleep 0.1; done
echo "auf s2 sichtbar nach $(( ($(date +%s%N) - start) / 1000000 )) ms"
waitExpected:
auf s2 sichtbar nach 1846 ms
For almost two seconds, the link exists on s3 but not on s2. An
attempt with sleep 4, that is, earlier in the write load,
gave me 552 ms.
Save your progress? Sign up for free
Drill 3: kurz Reads from the Replica
Before you change anything, a test that will show the difference later: each iteration creates a link and calls it immediately, like a user who tries out their new short link right away.
# on s1
cd ~/sd/tag08
cat > sofort.js <<'EOF'
import http from "k6/http";
import { check } from "k6";
const ZIEL = __ENV.ZIEL || "http://localhost";
export const options = {
scenarios: { sofort: { executor: "constant-arrival-rate", rate: Number(__ENV.RATE || 50),
timeUnit: "1s", duration: __ENV.DAUER || "20s", preAllocatedVUs: 20, maxVUs: 200 } },
};
// Anlegen und sofort aufrufen, wie ein Nutzer, der seinen neuen Link gleich testet
export default function () {
const url = `https://example.org/sofort/${__VU}-${__ITER}-${Date.now()}`;
const r = http.post(`${ZIEL}/api/links`, JSON.stringify({ url }),
{ headers: { "Content-Type": "application/json" } });
if (!check(r, { "201": (x) => x.status === 201 })) return;
const g = http.get(`${ZIEL}/${r.json().code}`, { redirects: 0 });
check(g, { "302 statt 404": (x) => x.status === 302 });
}
EOF
k6 run -q sofort.js | grep -E 'checks_failed|↳'Expected:
checks_failed......: 0.00% 0 out of 2000
Everything reads from the primary, so every call finds its link. Now
kurz gets a second connection pool. Without
KURZ_DB_LESEN it points to the same database as
db, so that nothing changes without a replica:
# on s1
cd ~/kurz && cp main.go /tmp/main.go.alt && cp cache.go /tmp/cache.go.alt
perl -0pi -e 's/\tdb \*pgxpool.Pool\n/\tdb *pgxpool.Pool\n\tlesen *pgxpool.Pool \/\/ Lese-Replikat, ohne KURZ_DB_LESEN dieselbe Datenbank wie db\n/' main.go
perl -0pi -e 's/(\t\tlog.Fatal\(err\)\n\t\}\n)(\tif _, err := db.Exec)/$1\tlesen = db\n\tif dsnLesen := env("KURZ_DB_LESEN", ""); dsnLesen != "" {\n\t\tif lesen, err = pgxpool.New(context.Background(), dsnLesen); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n$2/' main.go
sed -i 's/err := db.QueryRow(ctx, "SELECT url FROM links WHERE code = \$1", code)/err := lesen.QueryRow(ctx, "SELECT url FROM links WHERE code = $1", code)/' cache.go
diff /tmp/main.go.alt main.go; diff /tmp/cache.go.alt cache.go
go vet . && go build -o kurz . && echo gebautExpected:
23a24
> lesen *pgxpool.Pool // Lese-Replikat, ohne KURZ_DB_LESEN dieselbe Datenbank wie db
116a118,123
> }
> lesen = db
> if dsnLesen := env("KURZ_DB_LESEN", ""); dsnLesen != "" {
> if lesen, err = pgxpool.New(context.Background(), dsnLesen); err != nil {
> log.Fatal(err)
> }
57c57
< err := db.QueryRow(ctx, "SELECT url FROM links WHERE code = $1", code).Scan(&ziel)
---
> err := lesen.QueryRow(ctx, "SELECT url FROM links WHERE code = $1", code).Scan(&ziel)
gebaut
Only redirecting reads from the replica. The check from Day 7 whether a URL already exists stays on the primary: it belongs to writing, and an outdated replica would create duplicate links there.
One drop-in per instance and the deploy loop from Day 4. The replica gets direct connections without PgBouncer; two times 16 easily fit into the 100 of s2:
# on s1
for s in s1 s2; do
ssh $s "printf '[Service]\nEnvironment=KURZ_DB_LESEN=postgres://kurz:lab-kurz-123@s2:5432/kurz?pool_max_conns=16\n' \
| sudo tee /etc/systemd/system/kurz.service.d/lesen.conf >/dev/null && sudo systemctl daemon-reload"
done
for s in s1 s2; do
echo "set server kurz/$s state drain" | sudo nc -U /run/haproxy/admin.sock >/dev/null; sleep 2
scp -q kurz $s:/tmp/kurz
ssh $s "sudo install /tmp/kurz /usr/local/bin/kurz && sudo systemctl restart kurz"
until curl -sf http://$s:8080/readyz >/dev/null; do sleep 0.5; done
echo "set server kurz/$s state ready" | sudo nc -U /run/haproxy/admin.sock >/dev/null
doneSave your progress? Sign up for free
Drill 4: Reading What You Just Wrote
The same test as in Drill 3, now with the replica:
# on s1
cd ~/sd/tag08 && k6 run -q sofort.js | grep -E 'checks_failed|↳'Expected:
checks_failed......: 1.54% 31 out of 2002
↳ 96% — ✓ 970 / ✗ 31
31 of 1001 users get a 404 for their own, just-created link, without any extra load. The create goes to s3, the call a millisecond later to s2, and sometimes the WAL is still on its way. The cache doesn’t help: the link was never read, so it isn’t in there yet.
With write load as in Drill 2:
# on s1
psql -h s3 -U kurz -d kurz -qc "truncate ballast"
( psql -h s3 -U kurz -d kurz -qc "insert into ballast select i, repeat('x', 200)
from generate_series(1, 4000000) i" ) &
k6 run -q sofort.js | grep -E 'checks_failed|↳'
waitExpected:
checks_failed......: 41.50% 831 out of 2002
↳ 16% — ✓ 170 / ✗ 831
83% of the fresh links are “not found” on the first call. The problem is called read-your-writes: whoever writes expects to see what they wrote immediately. Asynchronous replication doesn’t guarantee that.
Save your progress? Sign up for free
Drill 5: Back to the Primary
For kurz there is a simple solution, because a link
never changes: if the replica doesn’t find a code, it can only be too
new (or it really doesn’t exist). Then kurz asks the
primary. The same applies if the replica doesn’t answer at all:
# on s1
cd ~/kurz && cp cache.go /tmp/cache.go.alt
perl -0pi -e 's/(\t\terr := lesen.QueryRow\(ctx, "SELECT url FROM links WHERE code = \$1", code\).Scan\(&ziel\)\n)/$1\t\tif err != nil && lesen != db {\n\t\t\t\/\/ Replikat kennt den Code (noch) nicht oder ist weg: Primärserver fragen\n\t\t\terr = db.QueryRow(ctx, "SELECT url FROM links WHERE code = \$1", code).Scan(&ziel)\n\t\t}\n/' cache.go
diff /tmp/cache.go.alt cache.go
go vet . && go build -o kurz . && echo gebautExpected:
57a58,61
> if err != nil && lesen != db {
> // Replikat kennt den Code (noch) nicht oder ist weg: Primärserver fragen
> err = db.QueryRow(ctx, "SELECT url FROM links WHERE code = $1", code).Scan(&ziel)
> }
gebaut
Roll out with the loop from Drill 3 and repeat the test with write load:
# on s1
for s in s1 s2; do
echo "set server kurz/$s state drain" | sudo nc -U /run/haproxy/admin.sock >/dev/null; sleep 2
scp -q kurz $s:/tmp/kurz
ssh $s "sudo install /tmp/kurz /usr/local/bin/kurz && sudo systemctl restart kurz"
until curl -sf http://$s:8080/readyz >/dev/null; do sleep 0.5; done
echo "set server kurz/$s state ready" | sudo nc -U /run/haproxy/admin.sock >/dev/null
done
cd ~/sd/tag08
psql -h s3 -U kurz -d kurz -qc "truncate ballast"
( psql -h s3 -U kurz -d kurz -qc "insert into ballast select i, repeat('x', 200)
from generate_series(1, 4000000) i" ) &
k6 run -q sofort.js | grep -E 'checks_failed|↳|http_req_duration'
waitExpected:
checks_failed......: 0.00% 0 out of 2002
http_req_duration..............: avg=12.36ms min=2.76ms med=9.3ms max=259.48ms p(90)=17.15ms p(95)=23.48ms
0 out of 2002. The price: codes that really don’t exist now cost two queries instead of one. Whoever calls made-up codes en masse hits the primary again. That is a topic for Day 12.
Other routes to read-your-writes, in case your data changes:
| Approach | How | Catch |
|---|---|---|
| Fallback on miss | as here | only helps if “outdated” can be recognized as “missing” |
| Primary after writing | a cookie makes the same user read from the primary for a few seconds | the seconds are a guess |
| Remember the position | after writing, remember pg_current_wal_lsn(); on the
replica, only read once pg_last_wal_replay_lsn() has gotten
that far |
more code, but exact |
| Fill the cache when writing | anlegen puts the link into Valkey immediately |
doesn’t help if the cache fails or evicts |
| synchronous replication | Drill 8 | costs every write |
Save your progress? Sign up for free
Drill 6: Who Carries the Load?
The load profile from Day 5 with 1500 requests per second. You count the committed transactions on both databases:
# on s1
cd ~/sd/tag08 && cp ~/sd/tag05/schief.js ~/sd/tag05/codes.txt .
tx() { psql -h $1 -U kurz -d kurz -tAc "select xact_commit from pg_stat_database where datname = 'kurz'"; }
a3=$(tx s3); a2=$(tx s2)
k6 run -q -e ZIEL=http://localhost -e RATE=1500 schief.js | grep -E 'http_req_failed\.|http_req_duration\.'
echo "s3 Tx/s: $(( ($(tx s3) - a3) / 30 )) s2 Tx/s: $(( ($(tx s2) - a2) / 30 ))"Expected:
http_req_duration..............: avg=9.72ms min=776.65µs med=4.35ms max=754.15ms p(90)=17.51ms p(95)=28.37ms
http_req_failed................: 0.00% 0 out of 44382
s3 Tx/s: 145 s2 Tx/s: 36
The replica is bored. The cache intercepts almost all reads, and what remains on s3 are the roughly 75 new links per second with two queries each (the check from Day 7 and the insert). For comparison, without the cache:
# on s1
for s in s1 s2; do
ssh $s "sudo mv /etc/systemd/system/kurz.service.d/cache.conf /tmp/ \
&& sudo systemctl daemon-reload && sudo systemctl restart kurz"
done
sleep 3
a3=$(tx s3); a2=$(tx s2)
k6 run -q -e ZIEL=http://localhost -e RATE=1500 schief.js | grep -E 'http_req_failed\.|http_req_duration\.'
echo "s3 Tx/s: $(( ($(tx s3) - a3) / 30 )) s2 Tx/s: $(( ($(tx s2) - a2) / 30 ))"
for s in s1 s2; do
ssh $s "sudo mv /tmp/cache.conf /etc/systemd/system/kurz.service.d/ \
&& sudo systemctl daemon-reload && sudo systemctl restart kurz"
doneExpected:
http_req_duration..............: avg=13.43ms min=1.03ms med=6.37ms max=828.71ms p(90)=28.06ms p(95)=41.29ms
http_req_failed................: 0.00% 0 out of 44345
s3 Tx/s: 145 s2 Tx/s: 1339
Now s2 carries all 1339 reads per second, and s3 still sees only the writes. On Day 5, without the cache, around 1470 transactions per second landed on s3. Cache and replica solve the same problem on two levels: the cache for the popular links, the replica for everything that bypasses the cache.
Save your progress? Sign up for free
Drill 7: The Replica Fails
Load at 500 requests per second; after 10 seconds you stop PostgreSQL on s2, keep writing on s3 and start s2 again after 10 seconds:
# on s1
cd ~/sd/tag08
(k6 run -q -e ZIEL=http://localhost -e RATE=500 -e DAUER=40s schief.js > ausfall.log 2>&1 &)
sleep 10; ssh s2 "sudo systemctl stop postgresql"; echo "s2-PG gestoppt $(date +%T)"
psql -h s3 -U kurz -d kurz -qc "insert into ballast select i, repeat('x', 200)
from generate_series(1, 300000) i"
ssh s3 "sudo -u postgres psql -tAc \"select slot_name, active,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) from pg_replication_slots\""
sleep 10; ssh s2 "sudo systemctl start postgresql"; echo "s2-PG gestartet $(date +%T)"
sleep 22; grep -E 'http_req_failed\.|http_req_duration\.' ausfall.log
ssh s3 "sudo -u postgres psql -tAc \"select slot_name, active,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) from pg_replication_slots\""Expected:
s2-PG gestoppt 07:01:47
s2|f|78 MB
s2-PG gestartet 07:02:11
http_req_duration..............: avg=2.98ms min=941.82µs med=2.26ms max=60.66ms p(90)=5.2ms p(95)=6.82ms
http_req_failed................: 0.00% 0 out of 20001
s2|t|0 bytes
Two things happened:
- No errors. The fallback from Drill 5 also kicks in
when the replica refuses connections.
/readyzstill checks only the cache and the primary, so both instances stay in the load balancer. - The slot held on to 78 MB of WAL. Without a slot, s3 would have deleted the WAL after the next checkpoint, and s2 would have had to be copied again. With the slot, s2 catches up on everything after starting. The price is in the Challenge.
Save your progress? Sign up for free
Drill 8: Replicating Synchronously
Synchronous replication solves read-your-writes at the root: with
synchronous_commit = remote_apply, s3 confirms a write only
once s2 has replayed it. First the write latency without it:
# on s1
cd ~/sd/tag08 && cp ~/sd/tag07/anlegen.js .
k6 run -q -e RATE=300 anlegen.js | grep -E 'http_req_duration\.|http_req_failed\.'Expected:
http_req_duration..............: avg=4.99ms min=1.32ms med=4.52ms max=41.23ms p(90)=7.87ms p(95)=9.46ms
http_req_failed................: 0.00% 0 out of 9001
The replica registers with s3 under the name 18/main
(Debian sets cluster_name). You enter this name as the
synchronous replica:
# on s1
ssh s3 "sudo -u postgres psql -c \"ALTER SYSTEM SET synchronous_standby_names = '\\\"18/main\\\"'\" \
-c \"ALTER SYSTEM SET synchronous_commit = 'remote_apply'\" -c 'select pg_reload_conf()'"
sleep 1
ssh s3 "sudo -u postgres psql -tAc 'select application_name, sync_state from pg_stat_replication'"
k6 run -q -e RATE=300 anlegen.js | grep -E 'http_req_duration\.|http_req_failed\.'Expected:
ALTER SYSTEM
ALTER SYSTEM
pg_reload_conf
----------------
t
(1 row)
18/main|sync
http_req_duration..............: avg=8.43ms min=1.73ms med=6.44ms max=373.79ms p(90)=12.37ms p(95)=15.26ms
http_req_failed................: 0.00% 0 out of 8962
p95 rises from 9.5 to 15.3 ms, and k6 could no longer start 39 iterations in time. Every write now waits for a network round trip and the replay on s2. What happens when s2 is gone?
# on s1
ssh s2 "sudo systemctl stop postgresql"
time timeout 5 psql -h s3 -U kurz -d kurz -c "insert into links (code, url) values ('haengt1', 'https://example.org/haengt')"
echo "exit: $?"
curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" -m 8 -X POST -H 'Content-Type: application/json' \
-d '{"url":"https://example.org/haengt2"}' http://localhost/api/links
psql -h s3 -U kurz -d kurz -tAc "select count(*) from links where code = 'haengt1'"Expected:
real 0m5.052s
user 0m0.175s
sys 0m0.035s
exit: 124
000 8.001154s
0
Every write hangs until timeout and curl
give up. The final query counts 0: other sessions don’t see the hanging
insert. A synchronous replica turns the outage of s2 into an outage of
all writes. With a single replica, you have halved availability instead
of doubling it.
Back to asynchronous and start s2. Then the surprise:
# on s1
ssh s3 "sudo -u postgres psql -c 'ALTER SYSTEM RESET synchronous_standby_names' \
-c 'ALTER SYSTEM RESET synchronous_commit' -c 'select pg_reload_conf()'" >/dev/null
ssh s2 "sudo systemctl start postgresql"; sleep 2
ssh s3 "sudo -u postgres psql -tAc 'select application_name, sync_state from pg_stat_replication'"
psql -h s3 -U kurz -d kurz -tAc "select code from links where url like 'https://example.org/haengt%'"Expected (the second code is random):
18/main|async
tomoWyA
haengt1
Both links are there, even though both clients got an error. PostgreSQL had already committed the transactions locally and was only waiting for the confirmation from s2. To the client it looked like a failure, but it was stored anyway. A client that simply retries after such an error creates duplicate records. That is the topic of Day 11.
Save your progress? Sign up for free
Exercise: Speed drills
- Show on s3 which replicas are connected and in which state. Target time: 1 min
- Check on s2 whether it is a replica and up to which WAL position it has replayed. Target time: 1 min
- Show the replication slots on s3 and whether they are in use. Target time: 1 min
Solution
# on s1
ssh s3 "sudo -u postgres psql -c 'select client_addr, state, replay_lag from pg_stat_replication'"
psql -h s2 -U kurz -d kurz -c "select pg_is_in_recovery(), pg_last_wal_replay_lsn()"
ssh s3 "sudo -u postgres psql -c 'select slot_name, active, wal_status from pg_replication_slots'"Expected:
client_addr | state | replay_lag
--------------+-----------+------------
172.16.0.228 | streaming |
(1 row)
pg_is_in_recovery | pg_last_wal_replay_lsn
-------------------+------------------------
t | 1/B43587C8
(1 row)
slot_name | active | wal_status
-----------+--------+------------
s2 | t | reserved
(1 row)
replay_lag is empty if nothing has been written for a
while. There is a trap on the replica as well:
now() - pg_last_xact_replay_timestamp() measures the time
since the last replayed transaction. If nobody writes, the value grows
even though s2 is up to date. For me it showed 17.8 seconds after a
quiet minute.
Save your progress? Sign up for free
Checkpoint
# on s1
psql -h s2 -U kurz -d kurz -tAc "select pg_is_in_recovery()"Expected: t
# on s1
ssh s2 systemctl show kurz -p Environment | grep -o 's2:5432[^ "]*'Expected:
s2:5432/kurz?pool_max_conns=16
# on s1
ssh s3 "sudo -u postgres psql -tAc 'select application_name, sync_state from pg_stat_replication'"Expected: 18/main|async
Challenge
The slot protects the WAL as long as s2 is gone. What happens on s3 if s2 fails over a long weekend and someone imports a lot of data on Monday? How do you limit the damage, and what does the limit cost?
Hint: Search the PostgreSQL documentation for
max_slot_wal_keep_size.
Solution
Without a limit, s3 holds on to all WAL since the outage until the disk is full. Then the primary stops, and with it all writes. s3 has 23 GB free; the import from Drill 2 generated 700 MB in ten seconds. With a limit:
# on s1
ssh s3 "sudo -u postgres psql -c \"ALTER SYSTEM SET max_slot_wal_keep_size = '2GB'\" -c 'select pg_reload_conf()'"
ssh s3 "sudo -u postgres psql -c 'select slot_name, wal_status,
pg_size_pretty(safe_wal_size) as noch_frei from pg_replication_slots'"Expected:
ALTER SYSTEM
pg_reload_conf
----------------
t
(1 row)
slot_name | wal_status | noch_frei
-----------+------------+-----------
s2 | reserved | 2061 MB
(1 row)
safe_wal_size shows how much more WAL may be generated
before the slot is given up. After that, wal_status
switches to lost, s3 deletes the WAL, and s2 has to be set
up again via pg_basebackup as in Drill 1. So the limit
trades “primary stops” for “replica has to be copied again”. That is
almost always the better trade. The limit stays in place.
Save your progress? Sign up for free
Clean-up
# on s1
psql -h s3 -U kurz -d kurz -c "drop table ballast"
rm -f ~/sd/tag08/ausfall.logExpected: DROP TABLE
The replica on s2, lesen.conf and the fallback in the
code stay. On Day 14, s2 becomes the new primary.
Interview note
- When do read replicas help? When the load consists mostly of reads that don’t end up in the cache. They don’t scale writes; every replica has to replay all changes.
- What is read-your-writes, and how do you ensure it? A user sees their own change immediately. Not guaranteed with asynchronous replication. Solutions: read from the primary after writing, fallback on miss, wait for the WAL position, or replicate synchronously.
- Synchronous or asynchronous? Synchronous loses no
confirmed data when the primary fails, but costs latency on every write
and blocks when the only synchronous replica is missing. That’s why you
use at least two replicas (
ANY 1 (a, b)) or stay asynchronous.
Enterprise note
- In production, the app itself rarely distributes between primary and
replicas. More common are two addresses via a proxy (HAProxy checking
pg_is_in_recovery(), Pgpool-II) or an operator such as CloudNativePG, which creates-rwand-roservices. - Lag belongs in monitoring: byte distance from
pg_stat_replicationon the primary, plus thewal_statusof the slots. A replica that lags minutes behind serves outdated data and, with slots, eventually slows down the primary.