Home›Operate›Run it well 9: replicas
Run it well

Build a replica, and fix it when it breaks

A replica is a copy of the data at one moment, plus every change since. Building one takes an afternoon. Keeping it healthy is the real job, because replicas break quietly. Here is both, in all three engines.

The problem

You need a second copy, and then it stops

Reports are slowing down checkout, so you want a read replica. Or the auditors ask what happens if the primary dies, so you want a standby. Either way you need a second server that holds the same data and stays current.

Building it is an afternoon. Keeping it healthy is the real job, because replicas break quietly. They fall behind, they stop on an error at 3 AM, or a dead one fills the primary's disk. This chapter does both: build one, then work through the ways it breaks.

The idea

A copy at one moment, plus the log from that moment

Every engine already writes a log of every change before it touches the data files: the WAL in PostgreSQL, the binary log in MySQL, the oplog in MongoDB. A replica is two things. First, a full copy of the data taken at some moment. Second, every log record written after that moment, replayed in order.

So building a replica is always the same three steps: take a copy, note exactly where in the log the copy was taken, then start streaming from that position. The tools differ in how much of that they do for you.

Why not just copy the data directory?

Because the files change while you copy them. A copy taken file by file from a running server is torn: some pages are from minute 1 and some from minute 9. It only becomes consistent if you also have every log record written during the copy, and replay them on top. That is exactly what pg_basebackup, the MySQL clone plugin and XtraBackup do for you.

PostgreSQL

pg_basebackup and a replication slot

On the primary, create a user with the REPLICATION attribute and allow it in pg_hba.conf. Then, on the new server, one command copies the data, streams the WAL written during the copy, and writes the settings the replica needs to start streaming:

-- on the primary
CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD '...';
# pg_hba.conf on the primary
host  replication  replicator  10.0.0.0/24  scram-sha-256

# on the new replica, with its data directory empty
pg_basebackup -h primary.db -U replicator -D /var/lib/postgresql/data \
  -X stream -R -C -S replica1 -P
# -X stream  also copy the WAL written during the backup
# -R         write standby.signal and primary_conninfo, so it starts as a replica
# -C -S      create a replication slot named replica1 on the primary

Start the server and check from both sides. On the primary, pg_stat_replication shows each replica and how far behind it is, in bytes and in time:

SELECT application_name, state, sync_state, pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS bytes_behind, replay_lag FROM pg_stat_replication;
SELECT slot_name, active, wal_status, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS wal_held FROM pg_replication_slots;
MySQL

Clone, then point it at the source

In MySQL 8, the clone plugin (8.0.17 and later) copies a running server over the network, including the GTID position, so the replica knows exactly where to continue. XtraBackup does the same job and is the usual choice for older versions or very large servers.

-- on the source
CREATE USER 'repl'@'%' IDENTIFIED BY '...';
GRANT REPLICATION SLAVE, BACKUP_ADMIN ON *.* TO 'repl'@'%';
INSTALL PLUGIN clone SONAME 'mysql_clone.so';

-- on the new replica (same plugin installed)
SET GLOBAL clone_valid_donor_list = 'source.db:3306';
CLONE INSTANCE FROM 'repl'@'source.db':3306 IDENTIFIED BY '...';
-- the server restarts with a full copy and the source's GTID set

CHANGE REPLICATION SOURCE TO
  SOURCE_HOST = 'source.db', SOURCE_USER = 'repl', SOURCE_PASSWORD = '...',
  SOURCE_AUTO_POSITION = 1, GET_SOURCE_PUBLIC_KEY = 1;
START REPLICA;
SET PERSIST super_read_only = ON;       -- nobody writes here by accident

With SOURCE_AUTO_POSITION = 1, the replica tells the source which GTIDs it already has, and the source sends the rest. No binlog file names or positions to copy by hand. Then check it:

SHOW REPLICA STATUS\G
-- Replica_IO_Running: Yes      receiving the binlog
-- Replica_SQL_Running: Yes     applying it
-- Seconds_Behind_Source: 0
-- Last_SQL_Error:              empty when healthy
MongoDB

Add a member, and let it sync

In a replica set, adding a member is one command on the primary. The new member runs an initial sync: it copies every collection, then applies the oplog entries written during the copy. Since MongoDB 4.4, a new voting member does not count toward elections until its sync finishes, so adding one does not weaken the set.

rs.add({ host: "mo4:27017" })
rs.status().members.map(m => [m.name, m.stateStr, m.optimeDate])   // STARTUP2 while syncing, then SECONDARY
rs.printSecondaryReplicationInfo()   // how far behind each secondary is
rs.printReplicationInfo()            // the oplog window: how much history the log holds
How it breaks

Five ways a replica goes wrong

It falls behind

The usual cause is one big transaction or one long ALTER. The primary ran it in parallel with everything else, but the replica has to apply it as a unit. MySQL applies transactions in parallel since 8.0.27 (replica_parallel_workers defaults to 4), but one huge transaction is still one transaction. On a PostgreSQL standby, a long report query can also hold back replay: with max_standby_streaming_delay set high, replay waits for the query. Set it low, and the query gets cancelled instead. You choose which one loses.

MySQL stops on error 1062 or 1032

A duplicate key (1062) or a row that is not there (1032) means the replica's data is already different from the source. Someone wrote to the replica directly, or a past skip left it drifted. The tempting fix is to skip the event and move on. Do not make that a habit: every skip makes the drift bigger and invisible. Find out how it drifted (check super_read_only), measure it with pt-table-checksum, and if it is more than one row, rebuild the replica with a clone.

Errant transactions

A write made directly on a MySQL replica gets that replica's own GTID, which the source never had. Nothing breaks until failover. Then the new primary tries to send that transaction to the others, or refuses to join. Check for it before you ever need it, with the query in the next box. An empty result is healthy.

A dead replica fills the primary's disk

A PostgreSQL replication slot promises to keep WAL until the replica reads it. If the replica is gone, the slot keeps that promise forever, and the primary's disk fills with WAL. Set max_slot_wal_keep_size (PostgreSQL 13+) so a dead slot is invalidated instead of taking down the primary. Then alert on inactive slots, and drop slots for replicas you have retired.

The log it needs is already gone

PostgreSQL without a slot or an archive says "requested WAL segment has already been removed". MongoDB says the member is too stale, because it fell off the end of the oplog. Either way the replica cannot catch up from the log any more and must be rebuilt. The prevention is the same in both: keep enough log to cover your worst outage. In PostgreSQL that means a WAL archive. In MongoDB, check the oplog window shown by rs.printReplicationInfo() and grow it with replSetResizeOplog if it is shorter than a long weekend.

-- MySQL, on a replica: transactions the source never had (empty is healthy)
SELECT GTID_SUBTRACT(@@GLOBAL.gtid_executed, '<paste the source gtid_executed here>') AS errant;
Follow one replica

Tuesday, 3 AM

The pager says replica2 is 4 hours behind. SHOW REPLICA STATUS shows Replica_SQL_Running: No and error 1062 on orders, primary key 88231907. The row already exists on the replica.

First question: how did a row get onto a read-only replica? @@super_read_only is OFF. A reporting job was pointed at the replica's address and has been writing scratch rows into the same database. One of its IDs collided with a real order.

Second question: how big is the drift? pt-table-checksum run from the source shows differences in two tables. That settles it. You do not skip events here. You turn super_read_only on, take replica2 out of the read pool, re-clone it from the source, and move the reporting job to its own schema on its own server. The skip would have cleared the alert in one minute and left a replica that silently returns wrong answers. This story is an example, but each step in it is the standard way to handle a 1062.

What to watch

The alerts every replica needs

  • Lag in time and in bytes, on every replica. Alert on a trend, not only on a threshold.
  • Replication thread state in MySQL: both Replica_IO_Running and Replica_SQL_Running must be Yes.
  • Inactive replication slots and the WAL they hold, in PostgreSQL. Set max_slot_wal_keep_size.
  • The oplog window in MongoDB, compared with your longest plausible outage.
  • super_read_only ON on every MySQL replica, checked by monitoring, not by memory.
  • Errant GTIDs, checked weekly and before every planned failover.

Next in this story: a replica is not a backup. It copies a DROP TABLE within milliseconds. That is the next chapter.

Next · chapter 10BackupsRestore time is the number that matters← Chapter 8: Partitioning
Part 4 of 4 · Operate · 21 pagesAll pages

How do I run it in production? What to check when it is slow or broken, where it runs and what it costs, how big it must be, pooling, backups, security, upgrades and other changes made safely.