TExcelTAD
Home › Redis › Redis Replication, Sentinel & Cluster

Redis Replication, Sentinel & Cluster

One Redis server is a single point of failure, and its memory and CPU have limits. Redis offers three building blocks to go further: replication copies the data to other servers, Sentinel promotes a replica automatically when the primary fails, and Cluster splits the data across many primaries. This lesson explains how each works; they need several servers, so the commands are shown as sessions and the key ideas are modelled in Python.

Replication: primary and replicas

A replica connects to a primary (historically called master) and keeps an exact copy of its data. All writes go to the primary, which streams them to its replicas. Replicas can serve reads, which spreads read traffic.

text
# on the replica server
redis> REPLICAOF 10.0.0.5 6379
OK
redis> ROLE
1) "slave"
2) "10.0.0.5"
3) (integer) 6379
4) "connected"
5) (integer) 128734

A standalone server, like the one behind the playground, reports itself as a primary with no replicas:

redis · try it yourself
ROLE
WAIT 0 0
redis> ROLE
1) "master"
2) (integer) 0
3) (empty array)
redis> WAIT 0 0
(integer) 0

WAIT numreplicas timeout blocks until that many replicas have acknowledged all previous writes; here there are none, so it returns 0 at once.

How a replica stays in sync:

  1. On first connect it asks for a full sync: the primary makes an RDB snapshot and sends it, followed by the writes that happened meanwhile.
  2. Afterwards the primary streams every write command to the replica.
  3. After a short disconnect the replica asks for a partial resync from its last offset, served from the primary's replication backlog buffer.

Note: Replication is asynchronous. The primary acknowledges a write to the client before the replicas have it. If the primary dies right then, the last writes can be lost. WAIT narrows this window but does not make Redis a strongly consistent database.

Sentinel: automatic failover

Redis Sentinel is a separate process (run at least three of them) that monitors a primary and its replicas. When a majority of Sentinels agree that the primary is down, they elect a leader, promote the best replica, and reconfigure the other replicas to follow it. Clients ask the Sentinels for the current primary's address.

text
# sentinel.conf
sentinel monitor shop-cache 10.0.0.5 6379 2      # 2 sentinels must agree it is down
sentinel down-after-milliseconds shop-cache 5000
sentinel failover-timeout shop-cache 60000
python
# redis-py with Sentinel
from redis.sentinel import Sentinel
sentinel = Sentinel([("10.0.0.21", 26379), ("10.0.0.22", 26379), ("10.0.0.23", 26379)])
primary = sentinel.master_for("shop-cache")    # writes
replica = sentinel.slave_for("shop-cache")     # reads

The "majority" rule (the quorum) is why you need at least three Sentinels on separate machines: with two, a network split leaves each side unable to decide.

Cluster: sharding the keyspace

Redis Cluster splits the data across several primaries (each with its own replicas). The keyspace is divided into 16,384 hash slots. A key's slot is CRC16(key) mod 16384, and every primary owns a range of slots:

text
node A: slots     0 –  5460
node B: slots  5461 – 10922
node C: slots 10923 – 16383

A client sends a command to the node that owns the key's slot. If it guesses wrong, the node answers with a redirect (-MOVED 3999 10.0.0.6:6379), and cluster-aware clients cache the slot map so that this rarely happens.

Here is the real slot function in Python, including hash tags: if a key contains {...}, only the part inside the braces is hashed. That lets you force related keys into the same slot:

python · try it yourself
def crc16(data: bytes) -> int:
    """CRC-16/XMODEM, the variant Redis Cluster uses."""
    crc = 0
    for byte in data:
        crc ^= byte << 8
        for _ in range(8):
            crc = ((crc << 1) ^ 0x1021) if crc & 0x8000 else (crc << 1)
            crc &= 0xFFFF
    return crc

def key_slot(key: str) -> int:
    start = key.find("{")
    if start != -1:
        end = key.find("}", start + 1)
        if end > start + 1:                 # non-empty {tag}
            key = key[start + 1:end]
    return crc16(key.encode()) % 16384

def node_for(slot):
    return "A" if slot <= 5460 else "B" if slot <= 10922 else "C"

for key in ["user:1", "user:2", "cart:1", "{user:1}:profile", "{user:1}:cart", "foo{}bar"]:
    slot = key_slot(key)
    print(f"{key:<18} slot {slot:>5}  node {node_for(slot)}")
user:1             slot 10778  node B
user:2             slot  6777  node B
cart:1             slot  1420  node A
{user:1}:profile   slot 10778  node B
{user:1}:cart      slot 10778  node B
foo{}bar           slot 14292  node C

Similar-looking keys spread out: user:1 and user:2 happen to share node B but not a slot, and cart:1 lives on node A. Both {user:1} keys hash only the tag user:1, so they share slot 10778 with each other (and with the plain key user:1). In foo{}bar the braces are empty, so the whole key is hashed. On a real cluster, CLUSTER KEYSLOT user:1 returns the same number as this function.

Multi-key commands in a cluster

Commands that touch several keys (MGET, SINTER, RENAME, transactions, Lua scripts) only work when all keys are in the same slot. Otherwise the node replies:

text
redis> MSET user:1 Ada user:2 Linus
(error) CROSSSLOT Keys in request don't hash to the same slot
redis> MSET {user}:1 Ada {user}:2 Linus
OK

Use hash tags deliberately for data that is used together (a user's profile, cart and sessions), but not for everything: a single huge tag puts all its keys on one node.

Which one do I need?

Need Setup
Development, or a cache you can lose one server
Survive a server failure, data fits in one machine primary + replicas + 3 Sentinels
More data or more write throughput than one machine Redis Cluster (≥ 3 primaries, each with a replica)
Someone else runs it a managed service (Redis Cloud, AWS ElastiCache/MemoryDB, Azure, Google Memorystore)

Test yourself

How many hash slots does Redis Cluster use?

  1. 1024
  2. 4096
  3. 16384
  4. 65536

Which keys are guaranteed to be in the same cluster slot?

  1. user:1 and user:2
  2. {order:9}:items and {order:9}:status
  3. a and b
  4. Any two keys on the same node

What is the role of Redis Sentinel?

  1. Split data across nodes
  2. Monitor primaries and promote a replica on failure
  3. Encrypt traffic
  4. Persist data to disk