Database Replication: Master-Slave Architecture
Database replication is a process where we create a master-slave architecture (original as master and copies as slaves) instead of relying on a single database.
Why use a master-slave setup instead of just a single database?
To answer this, let's first understand the master-slave database architecture:
A master database typically handles only write operations, while a slave database receives copies of data from the master and handles read operations. All data-modifying commands like insert, delete, or update are sent to the master database.
Now, why do we need this architecture?
Let's consider an example:
Imagine you have an application with a much higher ratio of reads to writes. As the system grows, in a single database structure, all the reads and writes will be fulfilled by only one database, which can cause bottleneck issues or database failure.
However, in a master-slave architecture:
- All reads will be directed to slave databases
- Only writes will be directed to the master database, thus reducing the chance of failure
Why use database replication?
Better performance🚀: Instead of all queries hitting a single database, it allows multiple queries to execute in parallel.
Reliability🛡️: If one of your databases is destroyed for any reason, you'll always have a copy of your data in another database. It's suggested to keep replicated databases in different geographical locations.
High availability⏰: Your database remains operational even if some databases go offline due to technical issues.
Earlier, we discussed how load balancers contribute to the high availability of websites—check out the article here👈.
Now, let’s explore how database replication enhances availability
Consider these scenarios:
What if we have only one slave database and it goes offline?
In that case, all read operations will be directed to the master database until the issue is resolved and a new slave is implemented.What if we have multiple slaves and one of them goes offline?
During the downtime of that one slave, all read operations will be directed to the other healthy slaves until the issue is fixed.What if our master database goes down?
In this scenario, a slave database would be promoted to become the new master, and all database operations would temporarily be executed on the new master. A replacement slave would be set up for data replication.
However, in production environments, promoting a new master is more complex. The data in the slave database might not be up to date, so we would need to run data recovery scripts to update the missing information. Other replication methods, like multi-master or circular replication, can help address these issues.
🔮 In the next section, we will focus on improving the load time and response time of our website.
Top comments (0)