How does MySQL replication work
· Category: SQL & Databases
Short answer
MySQL replication copies data from a source (master) server to one or more replica (slave) servers using the binary log.
How it works
The source writes changes to its binary log. Replicas connect to the source, read the log, and apply the events to their own data. Replication can be asynchronous, semi-synchronous, or group-based.
Steps
- Enable binary logging on the source.
- Create a replication user with
REPLICATION SLAVEprivileges. - Take a snapshot of the source data and load it onto the replica.
- Configure the replica with
CHANGE MASTER TOpointing to the source. - Start the replica threads and monitor
Seconds_Behind_Master.
Tips
- Use replicas for read scaling and backups to reduce source load.
- Monitor replication lag and network health to prevent stale reads.
Common issues
- Statement-based replication can produce different results for nondeterministic functions like
NOW(). - Large transactions cause significant replication lag.r