Day 6: PostgreSQL with replicas
Goal: Grow the CloudNativePG cluster to three instances, let
kurzread from the read Service, create replication lag and see what it means for “reading what you just wrote”, let a replica fail and measure the price of synchronous replication · Duration: approx. 90 min · Prerequisite: Day 5
Briefing
- In the predecessor course you built a replica by hand:
pg_basebackup, replication slot,primary_conninfo. With CNPG it is a number:instances: 3. The operator clones, starts, connects and adds the replicas to the Servicedb-ro.
| Term | Meaning |
|---|---|
| Streaming replication | the replica continuously receives the change log (WAL) from the primary |
| Lag | the distance between what the primary has written and what a replica has replayed |
| asynchronous | the primary confirms immediately; the default |
| synchronous | the primary waits until a replica has the change |
db-rw / db-ro |
Services pointing to the primary and to all replicas respectively (Day 1) |
local-pathfrom Day 1 stays: each instance has its volume on its own node. So here replication is not only for read load, it is the only copy of the data on another node.
Drill 1: Three instances
# on s1
# Copy the manifest from Day 1 and set it to three instances
mkdir -p ~/sdk/tag06 && cd ~/sdk/tag06 && cp ../tag01/db.yaml . && sed -i 's/instances: 1/instances: 3/' db.yaml
# Start time, apply
date +%T; kubectl apply -f db.yaml
# Wait until three instances are ready (kubectl wait is not enough: the Ready condition is still met from the old state)
until [ "$(kubectl -n kurz get cluster db -o jsonpath='{.status.readyInstances}')" = 3 ]; do sleep 5; done; date +%T
# Instances, roles, nodes
kubectl -n kurz get cluster db
kubectl -n kurz get pods -l cnpg.io/cluster=db -L cnpg.io/instanceRole -o wide | awk '{print $1, $2, $3, $5, $7, $NF}'
# One volume per instance
kubectl -n kurz get pvc | awk '{print $1, $2, $4, $6}'
# Who is behind db-ro?
kubectl -n kurz get endpointslices -l kubernetes.io/service-name=db-ro -o jsonpath='{range .items[*].endpoints[*]}{.targetRef.name} {.conditions.ready}{"\n"}{end}'
# Replication status as seen by the primary
kubectl -n kurz exec db-1 -c postgres -- psql -tAc "select application_name, state, sync_state from pg_stat_replication order by 1"Expected:
08:38:52
cluster.postgresql.cnpg.io/db configured
08:41:58
NAME AGE INSTANCES READY STATUS PRIMARY
db 16h 3 3 Cluster in healthy state db-1
NAME READY STATUS AGE NODE INSTANCEROLE
db-1 1/1 Running 10h s1 primary
db-2 1/1 Running 106s s2 replica
db-3 1/1 Running 16s s3 replica
NAME STATUS CAPACITY MODES
db-1 Bound 5Gi local-path
db-2 Bound 5Gi local-path
db-3 Bound 5Gi local-path
db-2 true
db-3 true
db-2|streaming|async
db-3|streaming|async
A little over three minutes, most of it for the first pull of the
PostgreSQL image on s2 and s3. CNPG creates the replicas one after the
other, each with a short Job db-N-join that clones the data
from the primary. Each instance lands on a different node: by default
CNPG sets a soft anti-affinity
(affinity.enablePodAntiAffinity).
Save your progress? Sign up for free
Drill 2: kurz reads from db-ro
kurz sends reads to KURZ_DB_LESEN if the
variable is set, for at most 300 ms, and asks the primary on an error or
a miss (predecessor course, Day 8):
# on s1
# Manifest, load script and codes from yesterday
cp ../tag05/kurz.yaml ../tag05/schief.js ../tag05/codes.txt .
# After KURZ_DB, insert a second connection for reads via db-ro
python3 - <<'EOF'
s = open("kurz.yaml").read()
alt = " value: postgres://kurz:$(DB_PASSWORT)@db-rw:5432/kurz\n"
neu = alt + " - name: KURZ_DB_LESEN\n value: postgres://kurz:$(DB_PASSWORT)@db-ro:5432/kurz\n"
open("kurz.yaml", "w").write(s.replace(alt, neu, 1))
EOF
# Difference, apply, wait
diff ../tag05/kurz.yaml kurz.yaml
kubectl apply -f kurz.yaml >/dev/null && kubectl -n kurz rollout status deploy/kurz | tail -1Expected:
51a52,53
> - name: KURZ_DB_LESEN
> value: postgres://kurz:$(DB_PASSWORT)@db-ro:5432/kurz
deployment "kurz" successfully rolled out
Where do the reads go now? You flush the cache so that any reads reach the database at all, and count the transactions on each instance separately:
# on s1
# valkey-cli as yesterday; flush the cache on all nodes
V="kubectl -n kurz exec valkey-cache-1-0-0 -c server -- valkey-cli -a lab-valkey-123 --no-auth-warning"
$V --cluster call 127.0.0.1:6379 FLUSHALL >/dev/null
# xact POD: transactions of the database kurz on this instance
xact() { kubectl -n kurz exec $1 -c postgres -- psql -tAc "select xact_commit from pg_stat_database where datname = 'kurz'"; }
# Remember the start values
A1=$(xact db-1); A2=$(xact db-2); A3=$(xact db-3)
# 30 s of skewed load
ZIEL=http://172.16.0.126 RATE=1500 DAUER=30s k6 run --quiet schief.js 2>/dev/null \
| grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.' | sed 's/ */ /g'
# Transactions per second per instance
echo "db-1: $(( ($(xact db-1) - A1) / 30 ))/s db-2: $(( ($(xact db-2) - A2) / 30 ))/s db-3: $(( ($(xact db-3) - A3) / 30 ))/s"Expected:
http_req_duration..............: avg=42.47ms min=1.57ms med=22.26ms max=685.53ms p(90)=96.45ms p(95)=145.19ms
http_req_failed................: 0.00% 0 out of 43892
http_reqs......................: 43892 1460.859114/s
db-1: 100/s db-2: 3/s db-3: 15/s
The replicas are bored. After the first few seconds the cache catches
97 % of reads again (Day 5); only the misses reach the replicas, about
one per code. The primary carries the writes (5 % of 1460/s ≈ 73/s) and
the fallback queries. That db-2 and db-3 get
such uneven shares is due to the connection pool: each kurz
Pod opens only a few connections to db-ro, and kube-proxy
distributes connections, not requests. How many land on
which replica is chance.
So with a cache, replicas do not pay off here for read load. They pay off for the data: each instance is a complete copy on another node, and tomorrow one of them becomes the primary.
Save your progress? Sign up for free
Drill 3: Reading what you just wrote
Asynchronous replicas lag behind, normally by milliseconds. To make the effect visible, you pause replay on both replicas, create a link and call it immediately:
# on s1
# Pause WAL replay on both replicas
for p in db-2 db-3; do kubectl -n kurz exec $p -c postgres -- psql -tAc "select pg_wal_replay_pause()" >/dev/null; done
# Check the state
for p in db-2 db-3; do kubectl -n kurz exec $p -c postgres -- psql -tAc "select pg_get_wal_replay_pause_state()"; done
# Create a link via the Gateway and remember the code
R=$(curl -s -X POST -H "Content-Type: application/json" -d '{"url":"https://example.org/tag06/neu"}' http://172.16.0.126/api/links); echo "$R"
CODE=$(echo "$R" | python3 -c "import json,sys; print(json.load(sys.stdin)['code'])")
# Call it immediately
curl -s -o /dev/null -w "GET /$CODE -> %{http_code} %{redirect_url}\n" http://172.16.0.126/$CODE
# Which instance knows the code?
for p in db-1 db-2 db-3; do
printf "%s kennt %s: %s\n" $p $CODE $(kubectl -n kurz exec $p -c postgres -- psql -d kurz -tAc "select count(*) from links where code = '$CODE'")
done
# Lag as seen by the primary: bytes and time
kubectl -n kurz exec db-1 -c postgres -- psql -tAc "select application_name, pg_wal_lsn_diff(sent_lsn, replay_lsn), replay_lag from pg_stat_replication order by 1"Expected:
paused
paused
{"code":"FSHjxVQ","url":"https://example.org/tag06/neu"}
GET /FSHjxVQ -> 302 https://example.org/tag06/neu
db-1 kennt FSHjxVQ: 1
db-2 kennt FSHjxVQ: 0
db-3 kennt FSHjxVQ: 0
db-2|19880|00:00:02.505283
db-3|19880|00:00:02.505045
Neither replica knows the new link (kennt = knows), yet
kurz answers immediately with 302. The
sequence: cache miss, the replica returns no row, kurz asks
the primary. This fallback helps exactly when “stale” shows up as
“missing”. For data that changes (a changed target link, an account
balance), the replica silently returns the old value. Then you need
other approaches: read from the primary for a while after writing, or
remember the position in the WAL (predecessor course, Day 8, Drill
5).
Half a minute later:
# on s1
# Lag after another 30 s, and what CNPG says about the state
sleep 30
kubectl -n kurz exec db-1 -c postgres -- psql -tAc "select application_name, pg_wal_lsn_diff(sent_lsn, replay_lsn), replay_lag from pg_stat_replication order by 1"
kubectl -n kurz get cluster db -o jsonpath='{.status.phase}{"\n"}'
# Resume replay and measure again right away
for p in db-2 db-3; do kubectl -n kurz exec $p -c postgres -- psql -tAc "select pg_wal_replay_resume()" >/dev/null; done
sleep 3
kubectl -n kurz exec db-1 -c postgres -- psql -tAc "select application_name, pg_wal_lsn_diff(sent_lsn, replay_lsn), replay_lag from pg_stat_replication order by 1"Expected:
db-2|19936|00:00:41.656075
db-3|19936|00:00:41.656572
Cluster in healthy state
db-2|0|
db-3|0|
“Cluster in healthy state” with 41 seconds of lag.
CNPG does not judge lag; a replica that is streaming is healthy as far
as the operator is concerned. If you want to see lag as an error, you
need your own monitoring. CNPG provides metrics for this
(cnpg_pg_replication_lag) that Prometheus can scrape. After
resuming, the lag is gone at once; replay_lag is empty when
there is nothing to replay.
Save your progress? Sign up for free
Drill 4: A replica fails
# on s1
# Flush the cache so that reads reach the replicas
$V --cluster call 127.0.0.1:6379 FLUSHALL >/dev/null
# 40 s of load, delete a replica after 10 s
(ZIEL=http://172.16.0.126 RATE=1500 DAUER=40s k6 run --quiet schief.js > k6-replikat.txt 2>&1 &)
sleep 10; date +%T; kubectl -n kurz delete pod db-3 --wait=false
# Result
sleep 34
grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.' k6-replikat.txt | sed 's/ */ /g'
# Did kurz log anything?
kubectl -n kurz logs -l app=kurz --since=60s --tail=-1 | wc -l
# How long until three instances are ready again?
until [ "$(kubectl -n kurz get cluster db -o jsonpath='{.status.readyInstances}')" = 3 ]; do sleep 3; done; date +%TExpected:
08:44:25
pod "db-3" deleted from kurz namespace
http_req_duration..............: avg=29.05ms min=1.4ms med=18.12ms max=342.84ms p(90)=69.36ms p(95)=93.92ms
http_req_failed................: 0.00% 0 out of 59424
http_reqs......................: 59424 1485.087129/s
0
08:47:44
Zero errors, zero log lines, but more than three
minutes until the replica is back. You know those three minutes
from Day 1: when stopping, CNPG shuts PostgreSQL down “smart” and waits
up to 180 seconds (smartShutdownTimeout) for open sessions
to end. The connections from the kurz pool keep running
during that time and are served. That is also the reason for the zero
errors. A replica that crashes instead of ending in an orderly way would
cut connections; then kurz falls back to the primary after
at most 300 ms.
Save your progress? Sign up for free
Drill 5: Replicating synchronously
Asynchronous means: if the primary dies, the last writes can be missing. Synchronous means: the primary only confirms once a replica has the change. What does that cost? A load script with writes only, asynchronous first:
# on s1
# schreiben.js: 100 % POST
sed 's/Math.random() < 0.95/Math.random() < 0/' schief.js > schreiben.js
# Twice 20 s with 200 writes per second
for n in 1 2; do
echo "== asynchron $n"
ZIEL=http://172.16.0.126 RATE=200 DAUER=20s k6 run --quiet schreiben.js 2>/dev/null \
| grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.' | sed 's/ */ /g'
doneExpected:
== asynchron 1
http_req_duration..............: avg=5.42ms min=2.6ms med=4.81ms max=25.54ms p(90)=8ms p(95)=9.44ms
http_req_failed................: 0.00% 0 out of 4001
http_reqs......................: 4001 199.979876/s
== asynchron 2
http_req_duration..............: avg=5.66ms min=2.52ms med=4.84ms max=42.88ms p(90)=8.32ms p(95)=10.44ms
http_req_failed................: 0.00% 0 out of 4001
http_reqs......................: 4001 199.970397/s
Now synchronous. CNPG takes a block
postgresql.synchronous for this. method: any
with number: 1 means: any replica must confirm, no matter
which (quorum). dataDurability: required means: no
confirmation, no confirmation to the client, even if all replicas are
gone.
# on s1
# db-sync.yaml: db.yaml plus synchronous replication
python3 - <<'EOF'
s = open("db.yaml").read()
s = s.replace(" instances: 3\n", " instances: 3\n postgresql:\n synchronous:\n method: any\n number: 1\n dataDurability: required\n", 1)
open("db-sync.yaml", "w").write(s)
EOF
diff db.yaml db-sync.yaml
# Apply; CNPG changes synchronous_standby_names without a restart
kubectl apply -f db-sync.yaml && sleep 15
kubectl -n kurz exec db-1 -c postgres -- psql -tAc "show synchronous_standby_names"
kubectl -n kurz exec db-1 -c postgres -- psql -tAc "select application_name, sync_state from pg_stat_replication order by 1"
# The same measurement
for n in 1 2; do
echo "== synchron $n"
ZIEL=http://172.16.0.126 RATE=200 DAUER=20s k6 run --quiet schreiben.js 2>/dev/null \
| grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.' | sed 's/ */ /g'
doneExpected:
7a8,12
> postgresql:
> synchronous:
> method: any
> number: 1
> dataDurability: required
cluster.postgresql.cnpg.io/db configured
ANY 1 ("db-2","db-3","db-1")
db-2|quorum
db-3|quorum
== synchron 1
http_req_duration..............: avg=5.58ms min=2.59ms med=4.82ms max=37.69ms p(90)=8.28ms p(95)=10.29ms
http_req_failed................: 0.00% 0 out of 4000
http_reqs......................: 4000 199.962558/s
== synchron 2
http_req_duration..............: avg=5.42ms min=2.18ms med=4.79ms max=35.36ms p(90)=7.91ms p(95)=9.68ms
http_req_failed................: 0.00% 0 out of 4001
http_reqs......................: 4001 199.995676/s
| Writes, 200/s | asynchronous | synchronous |
|---|---|---|
| p95 here (ANY 1 of 2 replicas) | 9.4 / 10.4 ms | 10.3 / 9.7 ms |
| p95 predecessor course (1 replica) | 9.5 ms | 15.3 ms |
No measurable difference. On the VMs there was one replica, and the
primary had to wait for its confirmation every time. Here, with
ANY 1, it only waits for the faster of
two. A quorum smooths out the outliers.
Synchronous gets expensive somewhere else: when no replica answers. With CNPG fencing you stop PostgreSQL on both replicas, while the Pods stay up:
# on s1
# Stop PostgreSQL on db-2 and db-3 (fencing)
kubectl -n kurz annotate cluster db cnpg.io/fencedInstances='["db-2","db-3"]' --overwrite && sleep 20
# Replication connections on the primary
kubectl -n kurz exec db-1 -c postgres -- psql -tAc "select count(*) from pg_stat_replication"
# Create three links, wait at most 5 s
for i in 1 2 3; do
curl -s -m 5 -o /dev/null -w "POST -> %{http_code} nach %{time_total}s\n" -X POST -H "Content-Type: application/json" \
-d "{\"url\":\"https://example.org/tag06/sync-$i\"}" http://172.16.0.126/api/links
done
# One redirect
curl -s -m 5 -o /dev/null -w "GET -> %{http_code} nach %{time_total}s\n" http://172.16.0.126/$(head -1 codes.txt)Expected:
cluster.postgresql.cnpg.io/db annotated
0
POST -> 503 nach 2.009777s
POST -> 503 nach 2.005716s
POST -> 503 nach 2.008281s
GET -> 302 nach 0.004685s
Reading works, writing fails after exactly 2 seconds
(nach = after): the timeout of kurz (Day 1).
And now the actual lesson. Do the three links that failed exist?
# on s1
# The three "failed" links on the primary
kubectl -n kurz exec db-1 -c postgres -- psql -d kurz -tAc "select code, url from links where url like 'https://example.org/tag06/sync-%' order by url"
# What PostgreSQL logged about it (CNPG's JSON log)
kubectl -n kurz logs db-1 -c postgres --since=3m | grep -i "synchronous replication" | head -1 \
| python3 -c "import sys, json; r = json.loads(sys.stdin.read())['record']; print(r['message'], '|', r['detail'])"Expected:
hk4XkBX|https://example.org/tag06/sync-1
Mo7MFCo|https://example.org/tag06/sync-2
2kuseaX|https://example.org/tag06/sync-3
canceling wait for synchronous replication due to user request | The transaction has already committed locally, but might not have been replicated to the standby.
All three exist. The client got 503,
but the database stored them anyway. PostgreSQL commits the transaction
locally first and waits for the replica afterwards. If the client
cancels the wait, the local change stays. Anyone who simply resends on
503 creates the link twice. That is why every write that
can be retried needs an idempotency key (predecessor course, Day 11),
and why retryOn: [5xx] on Day 4 was not a good idea.
Clean-up: lift the fencing, back to asynchronous.
# on s1
# Lift the fencing
kubectl -n kurz annotate cluster db cnpg.io/fencedInstances-
# Apply db.yaml without synchronous; apply removes the block because it came from the last apply
kubectl apply -f db.yaml
# Wait until both replicas are streaming again
until [ "$(kubectl -n kurz exec db-1 -c postgres -- psql -tAc "select count(*) from pg_stat_replication where state = 'streaming'")" = 2 ]; do sleep 3; done
kubectl -n kurz exec db-1 -c postgres -- psql -tAc "select application_name, state, sync_state from pg_stat_replication order by 1"Expected:
cluster.postgresql.cnpg.io/db annotated
cluster.postgresql.cnpg.io/db configured
db-2|streaming|async
db-3|streaming|async
Save your progress? Sign up for free
Exercise: Speed drills
- How large is the lag of each replica right now, in bytes? Target time: 1 min
- On which node is the volume of
db-2, and what does that mean for an outage of that node? Target time: 2 min - Why did
"db-1"appear insynchronous_standby_namesin Drill 5, even thoughdb-1is the primary? Target time: 2 min
Solution
# on s1
# 1: bytes between sent and replayed WAL
kubectl -n kurz exec db-1 -c postgres -- psql -tAc "select application_name, pg_wal_lsn_diff(sent_lsn, replay_lsn) from pg_stat_replication order by 1"
# 2: node binding of the volume of db-2
kubectl get pv $(kubectl -n kurz get pvc db-2 -o jsonpath='{.spec.volumeName}') \
-o jsonpath='{.spec.nodeAffinity.required.nodeSelectorTerms[0].matchExpressions[0].values[0]}{"\n"}'Expected:
db-2|0
db-3|0
s2
On 2: the volume is bound to s2. If s2 fails, db-2
cannot start anywhere else; CNPG has to clone a new replica on another
node. With three instances that is no data loss, just work.
On 3: CNPG writes all instance names into the list, including the
current primary. After a failover (Day 7), db-1 may become
a replica and should then count without a configuration change. A
primary never counts as its own replica.
Save your progress? Sign up for free
Challenge
A colleague wants to set dataDurability: preferred
instead of required: “Then nothing blocks when the replicas
are gone.” What do you gain, what do you lose, and which measurement
from this course would you take before deciding?
Solution
With preferred, CNPG switches off synchronous
replication as long as no replica is available. Writes then continue as
if asynchronous. Gain: availability, no 503 as in Drill 5.
Loss: exactly at the moment when only the primary is alive, there is no
guarantee any more; if it dies afterwards, the last writes are gone.
That is the classic trade between consistency and availability
(predecessor course, Day 14).
Measure before deciding: how often and for how long are all replicas
gone at the same time in your operations? With three instances on three
nodes that is rare. And: how expensive is a lost link compared with five
minutes without new links? For a URL shortener a lot speaks for
preferred; for payments, for required and more
replicas.
Save your progress? Sign up for free
Checkpoint
# on s1
# Three instances, healthy, primary db-1
kubectl -n kurz get cluster db --no-headers | awk '{print $3, $4, $5, $6, $7, $8, $9}'
# Both replicas streaming asynchronously
kubectl -n kurz exec db-1 -c postgres -- psql -tAc "select count(*) from pg_stat_replication where state = 'streaming' and sync_state = 'async'"
# kurz reads from db-ro
kubectl -n kurz get deploy kurz -o jsonpath='{.spec.template.spec.containers[0].env[?(@.name=="KURZ_DB_LESEN")].value}{"\n"}'
# No more fencing
kubectl -n kurz get cluster db -o jsonpath='{.metadata.annotations.cnpg\.io/fencedInstances}{"<-leer\n"}'Expected:
3 3 Cluster in healthy state db-1
2
postgres://kurz:$(DB_PASSWORT)@db-ro:5432/kurz
<-leer
Interview note
- Read replicas: help with read load only if the reads actually reach the database; behind a cache with 97 % hits they add little. Their main value is often the second and third copy of the data.
- Read-your-writes: asynchronous replicas are “eventually” current. Falling back to the primary on misses only helps if stale equals missing. Otherwise: read from the primary after your own write, or wait based on the LSN.
- Synchronous is not “safe instead of fast”: with a
quorum (
ANY 1of 2) it costs hardly any latency within the same data center. The real price is availability when no replica answers, and a client that gets503even though the data was stored.
Enterprise note
local-pathis for labs. In production, CNPG uses local NVMe disks via a local PV provisioner (performance) or distributed storage (Longhorn, Ceph), and always backups to object storage with WAL archiving (Barman Cloud Plugin), so that even a total loss of all instances can be recovered.- Lag belongs in monitoring: CNPG provides a
PodMonitorand metrics such ascnpg_pg_replication_lag; an alert from a few seconds on is common. - If you replicate across data centers, use
method: anyfor synchronous replication with replicas in at least two zones, so that a zone outage does not stop writes.