Skip to content

9. Replication

9.1 Master-Replica Configuration

Analogy: Replication is like "headquarters plus branches." The master handles writes, replicas handle reads, and data is synchronized from the master to the replicas.

bash
# Replica configuration (redis.conf)
replicaof 192.168.1.100 6379    # Master IP and port
masterauth your_master_password  # Master password

# Or configure at runtime
REPLICAOF 192.168.1.100 6379

# View replication information
INFO replication
bash
# Replication
role:slave
master_host:192.168.1.100
master_port:6379
master_link_status:up
master_last_io_seconds_ago:1
master_sync_in_progress:0
slave_read_repl_offset:123456
slave_repl_offset:123456

9.2 How Replication Works

  1. Full synchronization: when a replica connects to the master for the first time, the master creates an RDB snapshot and sends it to the replica.
  2. Incremental synchronization: after the full sync completes, the master sends new write commands to the replica in real time.
  3. Reconnection: Redis 2.8+ supports partial resynchronization (PSYNC), using repl_backlog to replay the incremental data missed during a disconnection.

Note: In production, the master should also use a suitable persistence strategy, such as AOF or regular RDB snapshots. Do not simply leave persistence entirely to replicas. If a master restarts without persistence and comes back with an empty dataset, replicas may synchronize that empty dataset and cause data loss.

9.3 Sentinel: Automatic Failover

Analogy: Sentinel is like a security guard on duty. It constantly checks whether the master is healthy. If the master goes down, Sentinel nodes vote on a new master and switch over automatically.

bash
# sentinel.conf
sentinel monitor mymaster 192.168.1.100 6379 2
sentinel auth-pass mymaster your_password
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
sentinel parallel-syncs mymaster 1
bash
# Start Sentinel (use at least 3 nodes)
redis-sentinel /etc/redis/sentinel.conf

# View master information
redis-cli -p 26379 SENTINEL master mymaster

# View replica information
redis-cli -p 26379 SENTINEL replicas mymaster

# Trigger a manual failover
redis-cli -p 26379 SENTINEL failover mymaster
bash
1) "name"
2) "mymaster"
3) "ip"
4) "192.168.1.100"
5) "port"
6) "6379"
7) "runid"
8) "abc123def456"
9) "flags"
10) "master"
11) "num-slaves"
12) "2"
13) "num-other-sentinels"
14) "2"

Tip: Use an odd number of Sentinel nodes, at least 3, and distribute them across different machines to reduce split-brain risk.