Sub topic 16
Replication and read replicas
This chapter assumes you can already install and run either engine, edit postgresql.conf or the MySQL [mysqld] configuration, create roles, open a firewall port, and take and restore a logical backup. It builds on the earlier chapters on listen addresses, authentication, TLS and backups.
What replication does and does not do
Replication keeps one or more continuously updated copies of a database on other servers. The server that accepts writes is the primary (MySQL calls it the source). The copies are replicas.
Replication gives you:
- A warm copy you can promote if the primary host is lost.
- A place to run read-only queries, such as reports, so they do not compete with application writes.
- A source for taking backups without loading the primary.
Replication does not give you a backup. A DROP TABLE or a bad UPDATE on the primary is copied to every replica within moments. Keep the logical backups and tested restores from the previous chapters.
The working model
Both engines record every change in an ordered log on the primary. Replicas fetch that log and apply it.
- PostgreSQL streaming replication ships the write-ahead log (WAL). The replica replays the physical changes, so it is a byte-level copy of the whole cluster. Every database is replicated, and the replica must run the same major version.
- MySQL replication ships the binary log. The replica's I/O thread copies events into a relay log. The SQL thread then re-executes them. Row-based logging, the default, records the changed rows.
Replication is asynchronous by default. The primary confirms a commit to the client without waiting for any replica. This is fast, but a replica can lag behind. If the primary dies, the most recent commits may exist nowhere else. PostgreSQL can wait for a replica with synchronous_standby_names, and MySQL offers semi-synchronous replication through a plugin. Both add commit latency, and a stalled replica can block writes, so use them only when losing recent commits is unacceptable.
| Aspect | PostgreSQL streaming | MySQL replication |
|---|---|---|
| What is shipped | WAL (physical) | Binary log (logical rows) |
| Scope | Whole cluster | Can filter databases or tables |
| Replica seeded with | `pg_basebackup` | Dump or clone, then position or GTID |
| Replica applies changes | Single WAL replay process | SQL thread, optionally parallel workers |
| Lag check | `pg_stat_replication` | `SHOW REPLICA STATUS` |
Setting up PostgreSQL streaming replication
This example uses a primary at 10.0.0.5 and a replica at 10.0.0.6. Start on the primary with a replication role. It needs the REPLICATION attribute and nothing else.
CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'change-me';Allow it in pg_hba.conf. The special database name replication matches replication connections. It does not match a database called replication.
# postgresql.conf on the primary
listen_addresses = 'localhost,10.0.0.5'
wal_level = replica
max_wal_senders = 10
max_replication_slots = 10
max_slot_wal_keep_size = 10GB
# pg_hba.conf on the primary
hostssl replication replicator 10.0.0.6/32 scram-sha-256Reload the configuration with sudo systemctl reload postgresql. Changing listen_addresses, wal_level, max_wal_senders or max_replication_slots needs a full restart. Then open port 5432 to 10.0.0.6 in the firewall.
On the replica, stop the service, empty the data directory, and clone the primary. The paths below are for PostgreSQL 16 on Debian or Ubuntu. Adjust them to your version.
sudo systemctl stop postgresql
sudo -u postgres bash -c 'rm -rf /var/lib/postgresql/16/main/*'
sudo -u postgres pg_basebackup \
-h 10.0.0.5 -U replicator \
-D /var/lib/postgresql/16/main \
-X stream -C -S replica1 -R -P
sudo systemctl start postgresqlThe options do the following:
-X streamincludes the WAL generated during the copy.-C -S replica1creates a replication slot namedreplica1.-Rwritesstandby.signaland aprimary_conninfoline, which put the server into standby mode.
pg_basebackup prompts for the password. For unattended use, put it in ~postgres/.pgpass with mode 0600.
A replication slot makes the primary keep WAL until the replica has received it. This stops a slow replica from falling off the end of the log. It also means an abandoned slot makes WAL pile up until the disk fills. max_slot_wal_keep_size caps that risk by invalidating a slot that falls too far behind.
Verify the setup from both sides:
-- On the primary
SELECT client_addr, state, sync_state, replay_lag FROM pg_stat_replication;
SELECT slot_name, active, restart_lsn FROM pg_replication_slots;
-- On the replica
SELECT pg_is_in_recovery(), now() - pg_last_xact_replay_timestamp() AS lag;The replica accepts read-only queries (hot_standby is on by default) and rejects writes.
Setting up MySQL replication with GTIDs
A global transaction ID (GTID) gives every transaction a cluster-wide identity. A replica can then ask the source for "everything I have not applied" without you tracking log file names and offsets. The primary needs a unique server-id, the binary log and GTIDs:
# [mysqld] on the source, 10.0.0.5
[mysqld]
bind-address = 10.0.0.5
server-id = 1
log_bin = /var/log/mysql/mysql-bin
gtid_mode = ON
enforce_gtid_consistency = ON
binlog_expire_logs_seconds = 604800
# [mysqld] on the replica, 10.0.0.6
[mysqld]
bind-address = 10.0.0.6
server-id = 2
gtid_mode = ON
enforce_gtid_consistency = ON
relay_log = /var/log/mysql/relay-bin
read_only = ON
super_read_only = ONRestart both servers. Then create the replication account on the source. The privilege is still named REPLICATION SLAVE.
CREATE USER 'replicator'@'10.0.0.6' IDENTIFIED BY 'change-me';
GRANT REPLICATION SLAVE ON *.* TO 'replicator'@'10.0.0.6';Seed a new replica from a consistent dump. With GTIDs on, mysqldump records which transactions the dump already contains.
# On the source
mysqldump --all-databases --single-transaction --routines --events > seed.sql
# On the replica, after copying seed.sql over
mysql < seed.sqlLoading the dump on a replica that is already read_only works for the root account. super_read_only blocks even privileged users, so run SET GLOBAL super_read_only = OFF; first and turn it back on afterwards. Then point the replica at the source (MySQL 8.0.23 and later syntax):
CHANGE REPLICATION SOURCE TO
SOURCE_HOST = '10.0.0.5',
SOURCE_USER = 'replicator',
SOURCE_PASSWORD = 'change-me',
SOURCE_AUTO_POSITION = 1,
SOURCE_SSL = 1;
START REPLICA;
SHOW REPLICA STATUS\GIn the output, Replica_IO_Running and Replica_SQL_Running must both be Yes. Seconds_Behind_Source estimates lag. Last_IO_Error and Last_SQL_Error explain failures. SOURCE_SSL = 1 matters because the default caching_sha2_password plugin needs an encrypted connection or an RSA key exchange.
Using replicas safely
- Stale reads. A client can write to the primary and then read an older value from a replica. Send reads that must see the user's own writes to the primary. Route only tolerant queries, such as reports, to replicas.
- Long queries on PostgreSQL standbys. The replay process can conflict with a long-running query. The standby then cancels the query or delays replay, depending on
max_standby_streaming_delay. - Failover is manual unless you add tooling. In PostgreSQL,
pg_ctl promote(orSELECT pg_promote();) ends recovery on the replica. In MySQL you stop replication, clearread_only, and repoint the other replicas. Add a tool such as Patroni or MySQL Orchestrator only when you need automation. Any automation needs a way to stop the old primary from accepting writes, or you get two primaries with diverging data. - Monitor lag and disk. Alert on replication lag, on
active = falseslots, and on free space in the WAL or binary log directory.
Exercise
A PostgreSQL primary's disk is filling up with files in pg_wal, although the database is small. pg_replication_slots shows a slot named replica2 with active = f. What is happening, and what are two ways to fix it?
Show answer
The slot makes the primary retain all WAL that replica2 has not yet received. Because the replica is disconnected, the WAL accumulates. Fix it either by bringing replica2 back so it reconnects and consumes the WAL, or, if the replica is permanently gone, by dropping the slot with SELECT pg_drop_replication_slot('replica2');. To prevent a repeat, set max_slot_wal_keep_size so a lagging slot is invalidated instead of filling the disk.
Exercise
On a MySQL replica, SHOW REPLICA STATUS\G shows Replica_IO_Running: Yes, Replica_SQL_Running: No, and a duplicate-key error in Last_SQL_Error. Which thread has failed, what is the likely cause, and why is skipping the transaction risky?
Show answer
The SQL thread, which applies events, has stopped. The I/O thread is still fetching them. A duplicate-key error usually means the replica holds a row the source never sent, often because someone wrote to the replica directly. Skipping the transaction leaves the replica's data different from the source's, so later events can fail or the replica can silently serve wrong results. The safer fix is to re-seed the replica from a fresh dump or clone.