Database replication
Play this lessonThis lesson comes with an interactive animation you can break, a live-code challenge and a chapter quiz.The web tier is now redundant, but we still have one database. The fix is replication, usually in a master/slave setup (also called primary/replica):
- The master handles all writes: insert, update, delete.
- Slaves get copies of the master's data and handle reads.
- Most apps read far more than they write, so there are usually many more slaves than masters.
Why it's worth it
- Better performance: reads are spread across many slaves in parallel.
- Reliability: a server destroyed by a flood or an earthquake doesn't lose your data, because copies live elsewhere.
- High availability: if one database goes offline, the site keeps running from another.
When things fail
- A slave dies: reads go to other slaves (or briefly to the master) until it is replaced.
- The master dies: a slave is promoted to be the new master. In real life this is tricky: the slave may be missing the latest writes, which have to be recovered with data recovery scripts.
Key takeaways
- Writes → master. Reads → slaves.
- Replication gives performance, reliability and availability.
- Copies can lag behind the master for a moment.