Redis Replication Basics
Understand how Redis replication works: master-slave architecture, data consistency, read scaling, and failover. Hands-on exercise included.
Focus: understand redis replication basics
Your Redis instance is a single point of failure. If it crashes, your cache is cold, your queues are gone, and your application suffers a full reload storm. Worse, even if it stays up, a single server can only handle so many read requests before latency spikes. Understanding Redis replication basics is the first step to building a resilient, scalable data layer that survives server failures and handles traffic spikes without breaking a sweat.
The problem this lesson solves
Running Redis on a single node is simple — until something goes wrong. A server crash, a network partition, or even a routine restart can wipe out your in-memory data if persistence isn't configured. Even with AOF or RDB snapshots, recovery takes time during which your app is offline or degraded.
Beyond availability, a single Redis server has a fixed read throughput. As your application grows — serving more users, more API requests, more background jobs — read traffic can overwhelm the primary instance. You need a way to distribute read operations across multiple servers without sacrificing data freshness.
Redis replication solves both problems. It creates exact copies of your dataset on one or more replica nodes. These replicas can handle read queries, act as hot standbys, and even become the new primary if the original fails.
Core concept / mental model
Think of Redis replication as a master–slave (or primary–replica) relationship:
- Master: The authoritative source of all write operations. Every
SET,LPUSH,SADD, etc., happens here. The master maintains a replication backlog — a fixed-size buffer of recent commands. - Replica: A read-only copy that connects to the master and receives a stream of all write commands. It applies those commands to its own in-memory dataset, staying in sync.
The replica never accepts write commands (by default). It stays synchronised by:
- Full resynchronisation (first time or after a long disconnect): The master forks a child process, creates an RDB snapshot of its current data, sends it to the replica, and then streams all subsequent write commands from the replication backlog.
- Partial resynchronisation (after a short disconnect): The replica sends its last known offset. If the command is still in the master's backlog, only the missed commands are sent — much faster.
💡 Pro tip: The default replication backlog size is 1 MB. For high-write workloads, increase
repl-backlog-sizeinredis.confto avoid full resyncs after brief network hiccups.
Key properties
- Asynchronous by default: The master does not wait for a replica to acknowledge a write before replying to the client. This gives maximum write performance but means a crash could lose writes not yet replicated.
- Eventual consistency: Replicas will eventually have the same data as the master, but there is a small lag (typically sub-millisecond on the same datacenter).
- Replication ID + offset: Each master has a unique replication ID and an offset. Replicas track their current offset. The combination identifies the exact point in the replication stream.
How it works step by step
Setting up a Redis replica involves three main phases:
1. Configuration
On the replica node, add one line to redis.conf (or use the SLAVEOF / REPLICAOF command):
# redis.conf on replica server
replicaof 192.168.1.100 6379
Or dynamically at runtime:
redis-cli> REPLICAOF 192.168.1.100 6379
⚠️ Warning:
SLAVEOFis deprecated since Redis 5; useREPLICAOF.
2. Handshake & sync
When the replica connects:
- The master initialises a replication backlog (if not already done).
- It
psyncs with the master, providing its replication ID and offset. - The master checks if partial resync is possible: * If yes, it sends only the missing commands from the backlog. * If no (or first time), it forks a child, dumps an RDB, sends the RDB file, and then streams all buffered writes.
- Once the RDB is loaded, the replica starts applying incoming write commands in real time.
3. Steady state
After initial sync, the master pushes every write command to all connected replicas. The INFO replication command shows the current state:
redis-cli> INFO replication
# Replication
role:master
connected_slaves:1
slave0:ip=192.168.1.101,port=6379,state=online,offset=12345,lag=0
Hands-on walkthrough
Let's create a local replication setup with two Redis instances on the same machine (for learning only). Use different ports: 6379 (master) and 6380 (replica).
Step 1: Start the master
redis-server --port 6379 --daemonize yes
Step 2: Start the replica and point it to the master
redis-server --port 6380 --replicaof 127.0.0.1 6379 --daemonize yes
Step 3: Verify replication status
redis-cli -p 6379 INFO replication
Expected output (simplified):
# Replication
role:master
connected_slaves:1
slave0:ip=127.0.0.1,port=6380,state=online,offset=14,lag=0
master_replid:abc123...
master_repl_offset:14
Step 4: Write on master, read on replica
redis-cli -p 6379 SET mykey hello
# OK
redis-cli -p 6380 GET mykey
# "hello"
The replica has the data.
Step 5: Confirm replica is read-only
redis-cli -p 6380 SET anotherkey fail
# (error) READONLY You can't write against a read only replica.
Perfect — the replica rejects writes by default.
Compare options / when to choose what
| Feature | Single instance | Master-replica (1 master, N replicas) | Redis Sentinel (auto-failover) | Redis Cluster (sharding + replication) |
|---|---|---|---|---|
| Read scaling | ❌ No | ✅ Yes, N replicas | ✅ Yes | ✅ Yes (sharded + replicas) |
| Write scaling | ❌ Single point | ❌ Single master | ❌ Single master | ✅ Yes (multiple shards) |
| Automatic failover | ❌ None | ❌ Manual only | ✅ Yes (Sentinel) | ✅ Yes (Cluster) |
| Data safety (crash) | ❌ None without persistence | ✅ Replica can be promoted | ✅ Replica promoted automatically | ✅ Shards survive if enough replicas |
| Setup complexity | Low | Low | Medium | High |
| Use case | Dev, small apps | Read-heavy apps, backups | High-availability production | Large scale, automatic sharding |
💡 Pro tip: For production read-heavy workloads, start with 2–3 replicas behind a load balancer. Add more replicas only if needed; each replica adds CPU and memory load on the master during full resync.
When to choose what
- You need to survive a server crash → Master-replica with Sentinel.
- You have many more reads than writes → Master-replica with replicas handling reads.
- You need automatic failover → Redis Sentinel (or Redis Cluster if you also need sharding).
- You write more than a single instance can handle → Redis Cluster.
Troubleshooting & edge cases
Replica stays in sync or handshake state
Check:
* Network connectivity between master and replica.
* Firewall rules on the master's port (default 6379).
* Master's replica-serve-stale-data setting: if no, the replica doesn't serve read requests until fully synced.
Replica lags or falls behind during heavy writes
- Increase
repl-backlog-size(default 1 MB) to hold more commands before they are evicted. - Use a dedicated network or lower-latency link between master and replicas.
- Monitor
lagfield inINFO replication— values > 0 indicate replication delay.
Full resync on every reconnect
This happens when the replica's offset is too old (outside the replication backlog). Short-term fix: increase backlog size. Long term: configure a proper persistence strategy so replicas don't restart from scratch.
Master crashes before replication completes
Some writes may be lost. Use WAIT command on the master to block until a configurable number of replicas acknowledge the write, providing synchronous replication. Trade-off: reduced write throughput.
# Wait up to 1000 ms for at least 1 replica to acknowledge
redis-cli> WAIT 1 1000
# (integer) 1 ← indicates 1 replica has seen the write
Replica won't accept writes
By default, replicas are read-only. If you need temporary writes on a replica (e.g., for indexing), set replica-read-only no — but be aware that those writes will be lost if the replica becomes the master.
What you learned & what's next
You now understand Redis replication basics:
- Master asynchronously replicates all writes to replicas.
- Replicas are read-only hot standbys that can serve queries or be promoted on failure.
- Setup is a one-liner:
REPLICAOFcommand orreplicaofconfig. - Monitoring with
INFO replicationgives you offset, lag, and connection state. - Partial resynchronisation avoids full RDB transfers for short disconnects.
What's next? The next lesson dives into Redis Sentinel — automated failover, monitoring, and notification. You'll learn how to build a high-availability setup where replicas automatically become the master if the primary fails. You'll also see how to connect your app to Sentinel for seamless recovery.
Practice recap
Start two Redis instances on ports 6379 (master) and 6380 (replica). Write a key on the master and verify it appears on the replica. Then run redis-cli -p 6380 SET test fail to confirm read-only behaviour. Finally, check INFO replication on both instances and note the offset and lag values. This hands-on exercise solidifies the master-replica relationship.
Common mistakes
- Assuming replication is synchronous — writes are async by default; use
WAITonly if you accept lower throughput. - Forgetting to set
replica-read-only yes— you may accidentally allow writes on replicas that will be lost on failover. - Setting too many replicas on one master — each replica adds CPU/memory overhead during full resync; 2–5 replicas is a safe range.
- Not increasing
repl-backlog-sizefor high-write workloads — a small backlog forces full resyncs after brief disconnections. - Confusing replication with persistence — replication protects against server failure but does not eliminate the need for AOF/RDB.
Variations
- Use Sentinel for automatic failover instead of manual replica promotion.
- Redis Cluster provides sharded replication — each shard has its own master and replicas, allowing both read and write scaling.
- Some cloud providers (e.g., AWS ElastiCache) manage replication and failover transparently; still understand the basics to tune performance.
Real-world use cases
- E-commerce product catalogue: one master handles writes (stock updates), 3 replicas serve read-heavy product page queries.
- Gaming leaderboard: master accepts player scores, replicas serve leaderboard reads to thousands of concurrent players.
- Session store outage protection: master stores session data, replica acts as hot standby; automatic failover via Sentinel keeps users logged in.
Key takeaways
- Redis replication is master-slave (primary-replica): master handles writes, replicas serve reads and act as failover targets.
- Asynchronous by default — eventual consistency, fast writes, but potential data loss on master crash.
- Partial resynchronisation using replication backlog avoids full RDB transfers for short disconnections.
- Set up replicas with
REPLICAOFcommand orreplicaofconfig; verify withINFO replication. - Replicas are read-only by default; increase
repl-backlog-sizefor high-write environments. - Replication alone does not provide automatic failover — use Sentinel or Cluster for production HA.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.