Technology Sharing

7. Redis master-slave replication process

2024-07-08

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Redis master-slave replication process

When a Redis node (Slave node) receives a command like slaveof 127.0.0.1 6380 until it can continue to replicate data from the master, it goes through the following process:

1. Save the master address

​ When the slave receives the slaveof command, the slave will immediately save the new master address.

2. Establish a connection

The slave maintains a scheduled task that attempts to establish a socket connection with the master. If the connection cannot be established, it will continue to retry until the connection is successful or the slaveof no one command is received.

3. Slave sends ping command

​ After the connection is established successfully, the slave will send a ping command for the first communication. If the slave does not receive a reply from the master, the slave will actively disconnect and the next scheduled task will try to connect again.

4. Authentication of slaves

If the master receives a ping command from the slave, it will not reply immediately, but will first authenticate. If the authentication fails, it will send a message to reject the connection; if the authentication succeeds, it will send a connection success response to the slave.

5. Master persistence

After the first communication is successful, the slave will send a data synchronization request to the master. When the master receives the request, it will fork a child process and let the child process persist immediately in an asynchronous manner.

6. Data transmission

After the persistence is completed, the master will fork a child process and let the child process send data to the slave asynchronously. The slave will continuously write the received data to the local persistence file.

During the slave data synchronization process, the master's main process is still continuously accepting write operations from the client, and not only writes new data to the master's memory, but also writes it to the synchronization cache. When the data in the master's persistent file is sent, the master will send the new data in the synchronization cache to the slave, and the slave will write it to the local persistent file. Data synchronization is completed

7. Slave restores memory data

When the data synchronization between the slave and the master is completed, the slave will read the local persistent file, restore it to the local memory, and then provide read services to the outside world.

8. Continuous incremental replication

While the slave is providing services externally, the master will continuously send new data to the slave in an incremental manner to ensure the consistency of master-slave data.