Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 42 ยท High Availability and Scaling

Replication

Learn Redis replication: leader and replicas, REPLICAOF, full and partial resync, the replication backlog, stale reads on replicas and the WAIT command, with demos.

A single Redis server is a single point of failure: if the machine dies, or you need to restart it, every client loses its data source. Replication is the first tool Redis gives you against that. One server is the master (also called primary or leader) and accepts writes. One or more replicas connect to it, receive a continuous copy of every change and keep their own in-memory copy of the dataset.

Replicas give you three things: a hot copy that can be promoted if the master dies (the next two lessons build on this), read scaling because clients can read from replicas, and a safer way to take backups because a replica can run BGSAVE while the master keeps serving traffic. They do not give you strong consistency. Redis replication is asynchronous, and understanding exactly what that means is the main goal of this lesson. If you have not read about durability yet, Persistence: RDB and AOF explains the snapshot files that replication reuses.

Real Redis cannot run on this page, so redis-cli and config snippets are read-only. The runnable examples are plain JavaScript models of the replication stream: they implement the ideas (offsets, a bounded backlog, partial versus full resync, delayed delivery, acknowledgements) but not the real wire protocol or the RDB format.

Setting up a replica

Starting a replica is one command, or one line in redis.conf:

Text
127.0.0.1:6380> REPLICAOF 127.0.0.1 6379
OK
127.0.0.1:6380> INFO replication
# Replication
role:slave
master_host:127.0.0.1
master_port:6379
master_link_status:up
slave_read_only:1
Text
# redis.conf of the replica
replicaof 10.0.0.5 6379
masterauth "the-master-password"
replica-read-only yes

SLAVEOF is the old name of the same command and still works. REPLICAOF NO ONE turns a replica back into a master, which is exactly how a failover promotes it. Notice role:slave in the INFO output: the field name predates the renaming and was kept for compatibility. If the master requires authentication, the replica needs masterauth (and masteruser when ACL users are used, see Securing Redis).

By default a replica is read-only: writes sent to it fail with READONLY You can't write against a read only replica. Keep it that way; a writable replica diverges from its master, and the next full resync throws those writes away.

One master, many replicas

Master Takes every write.
Stream Each write is forwarded.
Replicas Hold copies, serve reads.

Replicas can even have replicas of their own.

1 / 2

How a replica catches up

When a replica connects it sends PSYNC <replication-id> <offset> and the master decides between two paths.

  • Full resync. The master forks, writes an RDB snapshot (since Redis 7 it can stream it straight to the replica with diskless replication, repl-diskless-sync yes), sends it, and meanwhile buffers every new write. The replica discards its old data, loads the snapshot, then applies the buffered writes. This is expensive: a fork, a full dataset transfer and a load on the replica.
  • Partial resync. If the replica was connected before, it says "I have everything up to byte offset N of replication stream X". If the master still holds the bytes after N, it simply sends the missing part. Cheap and fast.

Where does the master keep those bytes? In the replication backlog, a fixed-size in-memory ring buffer (repl-backlog-size, 1 MB by default) holding the most recent part of the write stream. Every write advances the master's replication offset by the size of the command stream, and every replica tracks how far it got. A short network blip stays inside the backlog and costs almost nothing. A replica that stays away long enough for the backlog to wrap around, or that talks about a different replication ID (a different history), gets a full resync.

sequenceDiagram
    participant R as Replica
    participant M as Master
    R->>M: PSYNC replid offset
    alt offset still in backlog
        M-->>R: +CONTINUE, then missing commands
    else too old or unknown history
        M-->>R: +FULLRESYNC, RDB snapshot, buffered commands
    end
    M-->>R: live stream of new writes

A reconnecting replica asks for a partial resync first; the master falls back to a full one when it cannot.

The next TryIt models this. The master keeps a tiny backlog (60 bytes, so the effect is visible). Each write advances the offset by the length of the command text, which is a simplification of the real byte count.

JS Offsets, backlog and PSYNC

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the three results together. The first connection has no history, so it is a full resync. The short outage stays inside the backlog and replays only the two missed commands. The long outage is older than the backlog, so the master falls back to copying everything. In production you size the backlog by multiplying your write rate (bytes per second) by the longest disconnection you want to survive cheaply.

After a failover, a promoted replica keeps the old history as a secondary replication ID, so the other replicas can usually partially resync with it instead of reloading the full dataset. That detail is why failovers are fast on a healthy cluster.

Asynchronous replication, stale reads and WAIT

The master does not wait for replicas before answering a client. It executes the write, replies OK, and forwards the command in the background. The consequences are practical:

  • Stale reads. A client that writes to the master and then immediately reads from a replica may see the old value. Reading your own writes from a replica is not guaranteed.
  • Lost writes on failover. If the master crashes after acknowledging a write but before sending it to any replica, and a replica is promoted, that write is gone. Redis trades a small loss window for speed.
  • Replicas do not expire keys on their own. The master sends a DEL when a key expires. A replica hides keys that are logically expired when you read them, but it relies on the master for the actual removal (see Keys, Expiry and TTL).

Two tools narrow the gap. WAIT numreplicas timeout blocks the calling client until that many replicas have acknowledged everything written so far on this connection, or the timeout (milliseconds, 0 means forever) passes, and it returns how many replicas acknowledged. It does not undo anything on timeout: the write stays on the master. WAIT therefore improves durability, but it does not make Redis strongly consistent. Redis 7.2 added WAITAOF, which waits for the data to be fsynced to the AOF locally and on replicas.

The second tool is a guard on the master: min-replicas-to-write 1 together with min-replicas-max-lag 10 makes the master refuse writes when fewer than one replica has been in contact within 10 seconds. That trades availability for a smaller loss window, and it matters again in High Availability with Sentinel.

The second TryIt models delivery with ticks. One replica is fast (acknowledges after 1 tick), the other slow (after 4 ticks).

JS Stale reads and WAIT

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The timed-out WAIT is the important line: it returns fewer acknowledgements than you asked for and the application has to decide what to do, usually retry, log, or tell the user the write is "accepted but not yet safe".

Practical notes

  • Replica of a replica (chaining) reduces load on the master when you have many replicas; each hop adds a little more lag.
  • Read from replicas only when staleness is acceptable: product catalogs, counters on dashboards and cached pages are fine; balances and "did my login succeed" checks are not.
  • Watch the link, not just the process. master_link_status, master_last_io_seconds_ago and the offset difference between master_repl_offset on the master and slave_repl_offset on the replica tell you the lag. Monitoring and Troubleshooting turns these into alerts.
  • Memory. During a full resync the master's fork and its output buffers can use extra memory; leave headroom (see Memory Limits and Eviction).
  • Replication is not a backup. A bad FLUSHALL is replicated instantly to every replica. Keep snapshots too.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A replica reconnects after a short network outage. What does the master do if the replica's offset is still inside the replication backlog?

    PSYNC with a known replication ID and an offset that the backlog still covers lets the master replay just the missing part of the stream.
  2. 2. Which statement about Redis replication is true?

    The master replies first and forwards writes in the background, which is why stale reads and a small loss window on failover are possible.
  3. 3. What does WAIT 2 100 return?

    WAIT returns how many replicas acknowledged, both on success and on timeout. It never rolls back the write.
  4. 4. How do you turn a replica into a standalone master?

    REPLICAOF NO ONE stops replication and makes the server a master, which is how a failover promotes a replica.
  5. 5. Why is replication NOT a substitute for backups?

    Replication copies mistakes as faithfully as good writes. Snapshots taken at points in time are what let you go back.

Summary

  • A master accepts writes and streams them to replicas; REPLICAOF host port starts replication and REPLICAOF NO ONE ends it.
  • A new replica gets a full resync (RDB plus buffered writes); a returning replica gets a partial resync if its offset is still in the replication backlog (repl-backlog-size).
  • Replication is asynchronous: replicas can serve stale reads and an acknowledged write can be lost if the master dies before forwarding it.
  • WAIT counts replica acknowledgements, WAITAOF also waits for fsync, and min-replicas-to-write makes the master refuse writes when too few replicas are healthy.
  • Replicas are read-only by default and rely on the master to expire keys.
  • Replication protects against machine failure, not against mistakes: keep real backups.

Next, automatic failover on top of replicas: High Availability with Sentinel.