Data Engineering/Database Engineering · Part 9 of 14
·14 min read
Replication and CAP: Copies, Lag and What You Give Up
A real primary and standby in two containers: reading your own writes from a lagging replica, what each level of synchronous commit costs, a write that hangs when the network is cut, and 200 acknowledged orders lost in a failover. CAP stops being abstract.
Keeping a second copy of your data sounds simple. It gives you more read capacity, a server close to your users, and something to fail over to. The trouble is the gap between the copies. Everything hard about replication comes from that gap, and from what you do when the network between them breaks.
The course sets up streaming replication between two Postgres containers, then discusses the CAP theorem. I joined the two up: I built a real primary and standby, and made the things CAP talks about really happen. I cut the network, watched a write hang, read stale data, and failed over and lost orders that clients had been told were saved.
#What replication is
One server takes all the writes, and copies follow it.
Request or acknowledgmentData
The primary (or master) accepts writes. Each standby (or replica) connects over TCP, receives the write-ahead log, and replays it. That's why this is often called physical or streaming replication: the same bytes that protect the primary from a crash also build the copy.
There's another model, multi-primary, where several servers accept writes. It brings conflicts that have to be resolved, and the course's advice is to avoid it unless you really need it.
#Setting it up
The course's demo copies a data directory by hand, edits pg_hba.conf, and adds primary_conninfo and a standby.signal file. pg_basebackup -R does that in one step, so that's what I used:
# on the primary: a role for replication, as the course says, not the superuser
CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD '...';
# pg_hba.conf: host replication replicator all scram-sha-256
# for the standby: copy the data and write the connection settings
pg_basebackup -h primary -U replicator -D "$PGDATA" -R -X stream -c fast
It works on the first try, and the standby behaves as promised:
-- on the primary
SELECT application_name, state, sync_state FROM pg_stat_replication;
connected | application_name | state | sync_state
-----------+------------------+-----------+------------
t | walreceiver | streaming | async
(1 row)
-- on the standby
SELECT count(*) FROM t;
SELECT pg_is_in_recovery();
count
-------
10000
(1 row)
pg_is_in_recovery
-------------------
t
(1 row)
-- writing to the standby
CREATE TABLE nope (id int);
INSERT INTO t (v) VALUES ('nope');
ERROR: cannot execute CREATE TABLE in a read-only transaction
ERROR: cannot execute INSERT in a read-only transaction
-- ALTER TABLE t ADD COLUMN extra int on the primary, then on the standby:
\d t
Table "public.t"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+-------------------------------
id | integer | | not null | nextval('t_id_seq'::regclass)
v | text | | |
extra | integer | | |
Indexes:
"t_pkey" PRIMARY KEY, btree (id)
Rows and schema changes both arrive, because both are in the log, and writes on the standby are refused.
#Synchronous or asynchronous
The key question is when the client gets its reply:
Postgres has several levels of this, set by synchronous_commit once synchronous_standby_names names a standby. Each waits for something more:
-- one client, single-row commits, for each setting
synchronous_commit=local 552 commits/s waits for the primary's own disk
synchronous_commit=remote_write 513 commits/s waits for the standby to receive it
synchronous_commit=on 362 commits/s waits for the standby's disk
synchronous_commit=remote_apply 351 commits/s waits until a read there would see it
These two containers share a laptop, so the network is nearly free. Between regions, each synchronous commit would pay a real round trip, tens of milliseconds, which is what makes it such a hard choice. FIRST 1 (...) waits for one named standby, and ANY 2 (...) for any two, so a quorum is possible too.
#Reading your own writes
Here's the most common way replication bites an application. A user updates their profile, the page reloads, and the read goes to a replica that hasn't caught up. Their change seems to have vanished.
I set the standby to apply changes two seconds late, updated a row on the primary, then read both every quarter of a second:
-- recovery_min_apply_delay = '2s' on the standby
UPDATE profile SET bio = 'new bio' WHERE id = 1; -- on the primary
-- then read both, every 250 ms
4 ms primary: new bio standby: old bio
529 ms primary: new bio standby: old bio
1057 ms primary: new bio standby: old bio
1587 ms primary: new bio standby: old bio
2116 ms primary: new bio standby: new bio
2643 ms primary: new bio standby: new bio
3164 ms primary: new bio standby: new bio
For two seconds, the two servers gave different answers, for a committed change. Play with it here. Write a value, then read it back from the replica straight away:
🎓 The course mentions an early YouTube bug like this, from 2006: profile updates seemed to disappear, because reads came from a replica.
There are several ways round it:
- Read from the primary for a short time after a user's own write.
- Pin a user's session to one server.
- Use
synchronous_commit = remote_apply, so the commit waits until a read on the standby would see it. - Accept it, if the data allows.
The course's example is that a like count of 3.2 million against 3.1 million doesn't matter, and a bank balance does.
#CAP, made real
The CAP theorem is usually stated as "pick two of three". It's easier to understand as a question about what your system does during a network failure.
| Letter | Means here | Not to be confused with |
|---|---|---|
| C Consistency | A read sees the latest write | The C in ACID, which is about rules |
| A Availability | Every request gets an answer | Being fast |
| P Partition tolerance | The system keeps working when the network between nodes fails | Table partitioning |
Networks do fail, so if you have more than one node, P isn't optional. The real choice is between C and A, and only during a partition.
#Choosing consistency
With synchronous replication on, I cut the network between the two servers and tried a write:
-- synchronous replication on
application_name | sync_state
------------------+------------
walreceiver | sync
(1 row)
$ docker network disconnect dbe-net dbe-standby
INSERT INTO t (v) VALUES ('during the partition');
after 3.0 s the client is still waiting
pg_stat_activity: wait_event=SyncRep, query="INSERT INTO t (v) VALUES ('during the pa"
SELECT pg_cancel_backend(pid); -- give up on the wait
WARNING: canceling wait for synchronous replication due to user request
SELECT count(*) FROM t WHERE v = 'during the partition';
1
The client just waits: the server shows wait_event=SyncRep. That's consistency over availability. No client can be told "saved" for something the standby doesn't have.
Then something subtle. I cancelled the wait, and the warning says it plainly, but the last line is the part to look at: the row is there. The transaction had already committed locally. It was only the acknowledgement that was being held back. So a cancelled synchronous commit is not a rollback. An application that treats it as one will be wrong.
#Choosing availability
Now the same cut with asynchronous replication:
-- asynchronous, network still cut: 500 more rows on the primary
primary: 10501 rows, and every write was accepted
standby: 10000 rows, still answering reads, now stale
$ docker network connect dbe-net dbe-standby
standby caught up to 10501 rows after 2.2 s
Every write was accepted, and the standby kept answering reads, with data 501 rows behind. That's availability over consistency. When the network returned, it caught up by itself.
#The price of availability
Staleness is the mild cost. The severe one comes if the primary dies during the gap, and you promote a standby:
-- asynchronous: the primary acknowledges 200 orders the standby never received, then dies
SELECT pg_promote();
promoted: t, pg_is_in_recovery: f
orders acknowledged to clients: 200
orders on the new primary: 0
lost in the failover: 200
All 200 orders had been acknowledged, and all were gone. The new primary has no idea they ever existed. That's what async really means, and it's a decision to make deliberately. Those orders are also a trap for later: if the old primary comes back, its history has diverged from the new one, and it can't simply rejoin.
#The third option
The course adds a useful twist: a single large server doesn't face the partition question, so it's consistent and available, until it fails. Where you apply CAP depends on where you draw the line. Zoom out and a system with a cache is available and not consistent. Zoom in and a single node inside it is both.
The course also dislikes the word "eventual". Anything can be called eventually correct if you wait long enough. It quotes Brewer's later point that latency is really a form of unavailability: a system that answers after a minute might as well not have answered.
#Pros and cons
| Pros | Cons |
|---|---|
| Read capacity scales out | Reads can be stale |
| Replicas near users, as in the course's "keep your app close, and the database closer" | Synchronous writes are slower |
| A copy for failover | Failover can lose data, or need care |
| Reporting can run off the primary | Multi-primary needs conflict handling |
Note what replication doesn't scale: writes. Every standby replays every write, which is why write-heavy systems end up at sharding.
You can see what travels by watching the log move:
#Things that can trip you up
- Reading from a replica straight after a write. It may not be there yet.
- Assuming a failover is lossless. Under async it isn't.
- A cancelled synchronous commit isn't a rollback. The warning says it's already committed locally.
- One synchronous standby is a single point of failure. If it dies, writes stop, so use
ANY 1over several. - Using the superuser for replication. Create a role with only
REPLICATION. - Long queries on a standby can conflict with replay, and be cancelled.
- Old primaries. Don't let one rejoin as if nothing happened.
pg_rewindexists for this. - Believing "CA" systems exist at scale. With more than one node, partitions happen.
#Reproduce this yourself
- ✅ Create a network and a primary:
docker network create net1 docker run -d --name primary --network net1 -e POSTGRES_PASSWORD=postgres postgres:18 - ✅ Create the
replicatorrole, add thepg_hba.confline, and runSELECT pg_reload_conf();. - ✅ Run
pg_basebackup -Rinto a volume, then start a second container on that volume. Withpostgres:18the data directory is/var/lib/postgresql/18/docker. - ✅ Check with
SELECT * FROM pg_stat_replication;on the primary. - ✅ For synchronous mode:
ALTER SYSTEM SET synchronous_standby_names = 'first 1 (walreceiver)';and reload. - ✅ To cut the link:
docker network disconnect net1 standby. Note that this also breaks its published port until a restart, so reach it withdocker exec. - ✅ For the delay, add
recovery_min_apply_delay = '2s'on the standby and restart it. - ✅ To fail over, run
SELECT pg_promote();on the standby. - 🎓 The course's manual setup, copying directories and writing
standby.signalby hand, on Postgres 13, does the same thing.
#Glossary
| Term | Meaning |
|---|---|
| Primary, standby | The server taking writes, and a read-only copy |
| Streaming replication | Shipping WAL to standbys over TCP |
| Synchronous, asynchronous | Waiting for the standby before replying, or not |
| Replication lag | How far behind a standby is |
| Read your own writes | A user sees their own change straight away |
| Failover, promotion | Turning a standby into the new primary |
| CAP theorem | During a network partition, choose consistency or availability |
| Partition (network) | Nodes that can't reach each other |
| Eventual consistency | Copies agree if you wait |
#Summary
Replication ships the log to read-only copies, and that buys read capacity, locality and a spare. The cost is the gap between copies. Asynchronous replication keeps the gap and accepts stale reads, and lost commits on failover, which a real test confirmed. Synchronous replication closes the gap and makes writes slower, and when the network fails, it makes them wait. That's CAP in practice: not a choice of two letters out of three, but what your system does when a network splits.
#Concepts at a glance
| Concept | In one line | Why it matters |
|---|---|---|
| WAL shipping | Standbys replay the primary's log | Why schema changes replicate too |
| Read-only standby | Writes are refused | Only reads scale out |
synchronous_commit | How much to wait for | A sliding scale of cost and safety |
remote_apply | Wait until a read would see it | Gives read-your-writes |
| Replication lag | The gap between copies | Causes stale reads |
| Hung synchronous write | Waits for an unreachable standby | Consistency over availability |
| Lost commits on failover | Acknowledged, and never shipped | The real price of async |
| CAP's C | Reads see the latest write | Not ACID's C |
| CAP's P | A network split | Not table partitioning |
#Test yourself
A user saves their profile, the page reloads, and the old value appears. The save succeeded. What happened, and what are two fixes?
The read went to a replica that hadn't caught up. Fixes: read from the primary for a while after a user's own write, or commit with remote_apply, so that the change is visible on the standby before the reply.
With synchronous replication on, the standby becomes unreachable. What happens to a client's commit?
It waits, potentially forever, because the reply needs the standby's confirmation. If it's cancelled, the transaction has already committed locally, so the row stays, even though the client never got a success.
The primary dies under asynchronous replication, and you promote a standby. What can be lost, and how much?
Anything acknowledged that hadn't reached the standby. In the test that was all 200 orders written during a network cut. It depends on the lag at the moment of failure.
What do C and P mean in CAP, and how do they differ from ACID's C and from table partitioning?
C means a read sees the latest write, while ACID's C means the data obeys your rules. P means tolerating a network split between nodes, while table partitioning is splitting a table.
Why doesn't adding replicas help a write-heavy system?
Every standby replays every write, so writes aren't spread out. It helps reads. To spread writes, you need sharding.
#Open questions and gaps
- Both servers ran on one laptop, so the commit rates show relative cost and not real network latency.
- I didn't test
ANYquorums, cascading replication, orpg_rewindon an old primary. - 🎓 The YouTube story and Brewer's remark are reported from the course. I didn't check primary sources.
- The course doesn't go into logical replication, and neither does this post.
#Sources
- Hussein Nasser, Fundamentals of Database Engineering
- PostgreSQL docs: High Availability and Replication, Log-Shipping Standby Servers, Write-Ahead Log settings, pg_basebackup, pg_rewind
- Eric Brewer, CAP Twelve Years Later