Replication
In one line
Replication copies data to multiple servers — read scaling, failover, and disaster recovery.
In simple words
Replication copies data from a primary (master) database to one or more replica (slave) databases. Writes go to the primary; reads can go to any replica.
Types:
- Synchronous — primary waits for replicas to confirm before committing (strong consistency, slower writes)
- Asynchronous — primary commits immediately, replicas follow (faster, but may lag)
- Semi-synchronous — primary waits for at least one replica
Topologies:
- Master-slave — one primary, multiple read replicas
- Master-master — multiple primaries (complex conflict resolution)
- Cascading — replicas of replicas
Benefits: read scaling, high availability (failover), disaster recovery, geographic distribution. Challenges: replication lag, conflict resolution, split-brain.
Example
// Application with read/write splitting
const primaryDb = connect('primary.db.example.com');
const replicaDb = connect('replica.db.example.com');
// Writes always go to primary
async function createUser(name) {
return primaryDb.query('INSERT INTO users (name) VALUES (?)', [name]);
}
// Reads go to replica (scales read capacity)
async function getUser(id) {
return replicaDb.query('SELECT * FROM users WHERE id = ?', [id]);
}
// If primary fails, promote a replica
// replicaDb becomes the new primary
// Application reconnects automaticallyWrites go to primary, reads go to replicas. This scales read capacity. If primary fails, a replica is promoted to become the new primary.
Common confusions
Confused with: sharding
The difference: Replication copies the same data to multiple servers — each server has all the data. Sharding splits different data across servers — each has a subset. Replication is for availability/read scaling; sharding is for write scaling/storage capacity.
Related terms
Related Resources
Related Lessons
- Database Scaling
Replication.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.