Replication

Topology

Master-Replica topology — star-shaped, async replication
Master-Replica topology — star-shaped, async replication

Replicas are read-only by default (replica-read-only yes) and can serve reads, offloading traffic from the master — but reads may be stale if the replica is lagging.

The Replication Stream vs. the AOF

When a write command executes, Redis writes it to two separate in-memory buffers:

One command, two buffers — independent paths for local durability vs. distributed availability
One command, two buffers — independent paths for local durability vs. distributed availability

Both contain the same RESP-encoded commands. They're separate because they serve different guarantees — AOF is local durability, the replication stream is distributed availability. One failing (an AOF write stall) doesn't affect the other.

The repl_backlog is a circular buffer: older entries are overwritten as new ones arrive. This is what makes partial resync possible — a briefly disconnected replica can be sent just the missed commands. If it was gone too long and its range was overwritten, a full resync (entire RDB) is required.

Initial Sync (PSYNC)

Replica → master:  PSYNC <replicationid> <offset>
                   (first time: PSYNC ? -1)

Master:
  1. BGSAVE — fork(), serialize full RDB to disk
  2. Buffer ALL new writes arriving during the save into the repl_backlog
  3. Send RDB file to replica over TCP
  4. Send buffered backlog commands (delta)
  5. From here: stream new commands in real-time

The replica loads the RDB, applies the backlog delta, then stays in sync via the live stream. The master keeps serving clients throughout — BGSAVE is non-blocking.

BGSAVE scheduling on replica join

The master doesn't blindly fork for every new replica. It checks state first:

State when replica connectsMaster action
BGSAVE already in progressWait for it to finish, then send that RDB — no new fork
No BGSAVE in progressTrigger a new BGSAVE immediately
Old RDB on disk, nothing in progressIgnore the stale file, trigger a fresh BGSAVE

Reusing an in-progress BGSAVE is deliberate: if several replicas connect in a short window they're all served from one fork. Old RDB files are never reused because the backlog would have to cover the gap since that snapshot — a window that can be arbitrarily large and may already have been overwritten.

Diskless replication (repl-diskless-sync yes): the fork streams the RDB straight to the replica socket instead of writing to disk first. repl-diskless-sync-delay (default 5 s) lets the master batch multiple connecting replicas into a single fork.

Per-Replica Offset Tracking

The master tracks each replica independently. Each replica connection has its own repl_ack_offset — "this replica has consumed up to byte N of the stream." The repl_backlog itself is one shared circular buffer; it is not duplicated per replica.

Master repl_offset = 5000
Replica 1: repl_ack_offset = 5000  ← live
Replica 2: repl_ack_offset = 5000  ← live
Replica 3: connects → PSYNC ? -1   ← needs full sync
  1. Master records the current offset at BGSAVE start (5000).
  2. BGSAVE forks — writes an RDB of state-at-5000.
  3. Replicas 1 & 2 keep receiving live commands; the offset advances to 6000, 7000 …
  4. New writes also land in repl_backlog (this was already happening).
  5. RDB completes → sent to Replica 3.
  6. Master sends Replica 3 the backlog delta from 5000 → current offset; Replica 3 enters the live stream.

Replicas send REPLCONF ACK <offset> back roughly every second; the master updates each repl_ack_offset from these. This is also what WAIT uses. If a replica falls so far behind that the backlog has wrapped past its offset, partial resync is impossible and a full resync is required.

Master Failover

What happens when the master dies depends entirely on whether Sentinel or Cluster is in use.

Without Sentinel / Cluster (standalone)

Replicas detect the lost connection and enter a reconnect loop. They serve reads (if replica-serve-stale-data yes, the default) but reject writes. No automatic promotion happens — a human must intervene:

# On the chosen replica:
REPLICAOF NO ONE        # promotes it to master
# Then point other replicas at the new master:
REPLICAOF <new-master-ip> <port>

Any writes that reached the old master but hadn't been streamed to replicas are lost.

With Redis Sentinel

redis-sentinel is a completely separate program — not a replica, not a data store. It stores nothing and serves no reads or writes. Its only job is to watch Redis processes and orchestrate failover.

Machine 1:  redis (master)    + sentinel-1
Machine 2:  redis (replica-1) + sentinel-2
Machine 3:  redis (replica-2) + sentinel-3

The common deployment colocates one Sentinel per machine alongside Redis. Replicas live on separate machines — putting them on the master's machine defeats the purpose.

How a Sentinel assembles the fleet — a timeline

You only ever configure Sentinel with the master's address — never the replicas, never the other Sentinels. From that single seed, here's what happens, in order. The traffic splits across three distinct wires; keeping them straight is the point: the first two assemble the fleet, and only the third makes decisions.

t=0 — Connect to the master

Wire I — Monitoring: one configured address becomes three watched nodes
Wire I — Monitoring: one configured address becomes three watched nodes

Sentinel opens a connection to the configured master address and begins PINGing every 1s for liveness and issuing INFO every 10s. At this moment it knows about exactly one Redis node.

t ≈ 10s — Discover replicas from INFO

The first INFO response from the master returns slave0:ip=…,port=…,offset=… for every connected replica. Sentinel opens a direct connection to each replica and starts the same PING/INFO cycle on them. After this first INFO round, the Sentinel is connected to every Redis node in the deployment. This is Wire I — the monitoring wire. Each Sentinel does this independently of the others.

Failure detection also begins here: if any node misses a streak of PINGs longer than down-after-milliseconds, that Sentinel marks it s_down in its own local view. But s_down is just one Sentinel's opinion — it means nothing until peers corroborate (that happens on Wire III).

t ≈ 2s — Discover peer Sentinels through Pub/Sub

Wire II — Hello: Each Redis is a meeting room. Sentinels hear each other by being in the same rooms.
Wire II — Hello: Each Redis is a meeting room. Sentinels hear each other by being in the same rooms.

Think of each Redis process as an independent meeting room with a whiteboard labeled __sentinel__:hello. Every Sentinel walks into all three rooms — it holds a connection to the master and to each replica. In every room it does two things:

  1. SUBSCRIBEs to the whiteboard — so it sees whatever anyone else writes there.
  2. PUBLISHes a short identity message every ~2s: "I'm sentinel-1, my address is 10.0.0.1:26379, the master I believe in is 10.0.0.10:6379"

When sentinel-2 writes its identity on the master's whiteboard, Redis delivers that message to everyone subscribed to that whiteboard in that room. Since sentinel-1 and sentinel-3 are also subscribed to __sentinel__:hello on the master, they receive sentinel-2's message and discover it exists — no one had to tell them. They do the same through the replicas' rooms, which is why publishing on replicas matters: if the master goes down, that room disappears, but the replica rooms stay open. Sentinels keep discovering each other through those — without this redundancy, peer discovery would die with the master.

This is Wire II — discovery only. No votes travel here. The Pub/Sub rides the same connections Wire I already opened, so there are no extra sockets.

Message volume: with N sentinels and M nodes that's N × M publishes every ~2s — here 3 × 3 = 9 per cycle, fanning out to N × M × (N−1) deliveries. The payload is one short string; it stays cheap.

The moment a hello message reveals another Sentinel's ip:port, this Sentinel opens a direct TCP connection to that peer's port 26379. After one or two hello cycles (~2–4s from startup), every Sentinel has discovered every other Sentinel and the peer mesh is fully established. This entire mesh is built proactively during normal operation, long before anything goes wrong.

The full connection map for a single Sentinel in steady state:

sentinel-1
  ├── master:6379        (Wire I — monitoring + Wire II — discovery Pub/Sub)
  ├── replica-1:6379     (Wire I — monitoring + Wire II — discovery Pub/Sub)
  ├── replica-2:6379     (Wire I — monitoring + Wire II — discovery Pub/Sub)
  ├── sentinel-2:26379   (Wire III — peer voting, leader election)
  └── sentinel-3:26379   (Wire III — peer voting, leader election)

Wires I and II share the same sockets to the Redis nodes — the Pub/Sub channel rides the existing monitoring connections. Wire III sockets are separate and direct Sentinel→Sentinel, with no Redis in the middle.

Wire III — What the peer mesh does: direct Sentinel↔Sentinel on :26379
Wire III — What the peer mesh does: direct Sentinel↔Sentinel on :26379

Summary: the three wires

WireEndpointsCarriesCadence
I · monitoring sentinel → each redis node
:6379
PING liveness; INFO role, replica list, offsets. Produces s_down. PING 1s
INFO 10s
II · hello sentinel ⇄ each node's Pub/Sub
__sentinel__:hello
Peer discovery only — ip:port, run-id, epoch, believed master address. No votes. 2s
III · peer sentinel ⇄ sentinel
:26379
IS-MASTER-DOWN-BY-ADDR for o_down; leader-election votes for the epoch. on demand

The one-sentence version: wires I and II are how the fleet assembles itself from a single configured address; wire III is how it decides anything — and only wire III has to work at the moment the master is gone.

What happens when the master goes down

The timeline above built the fleet — all three wires are up, every Sentinel is connected to every Redis node and every other Sentinel. Now the master dies. Here's the sequence that follows.

Why 3 Sentinels, not 2

The whole system runs on majority agreement. With 3, quorum = 2.

✓ 3 sentinels — failover works

Machine 1 dies
  → lose master + sentinel-1
sentinel-2 + sentinel-3 alive
  → 2/3 = majority → can act

✗ 2 sentinels — failover is stuck

Machine 1 dies
  → lose master + sentinel-1
sentinel-2 alone
  → 1/2, no majority → stuck

2 sentinels can always split 1-1. 3 always produces a majority winner.

Step 1 — Two-stage "is it really down?" check

StageWhat it means
s_down (subjectively down)Sentinel-1 can't reach the master for down-after-milliseconds → "I personally think it's down." But maybe my network path is broken, not the master.
o_down (objectively down)Sentinel-1 asks 2 and 3 on Wire III: "can you reach the master?" Both say no → quorum (2/3) agrees → objectively down → act now.

This is what prevents a Sentinel with a bad network path from triggering a false failover. Notice how the question "is it really down?" travels on Wire III — the direct peer links — not through the possibly-dead master.

Step 2 — Leader election (the "Raft-like vote")

Once o_down is declared, all 3 Sentinels know the master is dead. If all 3 simultaneously promoted a replica you could end up with two masters — split brain. So only one Sentinel drives the failover.

Sentinel-1 declared o_down first
→ broadcasts on Wire III: "vote for me as leader, epoch=7"

Each sentinel votes for the FIRST request it hears in this epoch:
  sentinel-2 hears sentinel-1 first → votes for sentinel-1
  sentinel-3 hears sentinel-1 first → votes for sentinel-1

sentinel-1 wins 3/3 → elected leader for this failover

"Epoch" is a round counter that increments with each failover; it prevents stale messages from a previous election interfering with the current one. It's called "Raft-like" because real Raft uses the same ideas — terms, majority votes, first-come-first-served voting — though Sentinel doesn't implement full Raft.

Step 3 — Leader picks the best replica

sentinel-1 (leader) checks all replicas:
  Replica-1: priority=100, repl_ack_offset=9500
  Replica-2: priority=100, repl_ack_offset=9200

→ picks Replica-1 (higher offset = received more data = less loss)

Sends to Replica-1:  REPLICAOF NO ONE              ← promotes to master
Sends to Replica-2:  REPLICAOF <replica-1-ip> 6379 ← now follows new master

Selection criteria in order: replica-priority (lower = preferred, 0 = never promote), then highest repl_ack_offset, then lowest run ID as tiebreaker.

Step 4 — How clients find the new master

Client → Sentinel: SENTINEL get-master-addr-by-name mymaster
Sentinel → Client: 10.0.0.1 6379   ← before failover
                   10.0.0.2 6379   ← after failover (replica-1 is now master)

This is why Sentinel requires sentinel-aware client libraries. A client that caches the master IP will keep hitting a dead server after failover.

Data loss window: still async — writes the old master accepted but hadn't streamed to any replica are lost. min-replicas-to-write and min-replicas-max-lag limit this by refusing writes on the master if too few replicas are keeping up.

With Redis Cluster

Each shard has a primary + replicas, and cluster nodes gossip with each other over a separate cluster-bus connection — a different channel from the replication-link PING/REPLCONF ACK covered above, running alongside it rather than replacing it. No separate Sentinel process. At a glance:

  1. Other primaries mark it PFAIL (possible fail) after cluster-node-timeout.
  2. A quorum of primaries agree → FAIL.
  3. A replica of the failed primary requests a failover vote from the other primaries.
  4. It wins the vote → promotes itself and takes over the hash slots.
  5. Other nodes update their routing tables.

Clients get MOVED or CLUSTERDOWN during the window and must retry. The election is faster than Sentinel's because escalation to FAIL is a direct broadcast, not a round of asking peers "can you reach it?" after the fact. The full mechanics — the gossip payload, PFAIL→FAIL quorum math, and the failover vote — are in the Redis Cluster part, once hash slots and shards are properly on the table.

Replica Reads — Caveats

ScenarioRisk
Write to master, read from same masteralways fresh
Write to master, read from replicamay return old value if the replica is lagging
WAIT 1 0 after the writesafe blocks until ≥1 replica has applied it

In Redis Cluster, replicas reject reads by default even from clients — the client must send READONLY on its connection to opt in for that session.

What WAIT Does (and Doesn't Do)

SET foo bar
WAIT numreplicas timeout_ms
WAIT 1 100    # block until ≥1 replica has ACK'd, or 100ms passes

The master captures its current repl_offset when WAIT is called, then holds your client connection until the requested number of replicas have sent REPLCONF ACK <offset> with an offset ≥ that value.

# Write something critical, then ensure at least 1 replica has it
# before redirecting a read to a replica
SET user:42:balance 1000
WAIT 1 0      # 0 = wait forever until 1 replica ACKs
GET user:42:balance   # now safe to read from a replica

WAIT narrows the async replication gap for the writes you care about without forcing the whole system into sync mode.