Skip to content

10. Redis Cluster

10.1 What is Redis Cluster?

🌐 Analogy: If replication is "one boss with several subordinates," Cluster is like an "alliance" — multiple nodes each manage a portion of the data (16384 hash slots), sharing the load together.

  • Data is automatically sharded across multiple nodes
  • Each master can have replicas (high availability)
  • Nodes communicate via the Gossip protocol
  • Supports online scaling (adding/removing nodes)

10.2 Hash Slots

Redis Cluster divides the data space into 16384 slots, with each node responsible for a portion of them.

bash
# Calculate which slot a key belongs to
CLUSTER KEYSLOT "user:1001"
bash
(integer) 8106

📝 Note: Using {hash_tag} allows multiple keys to land in the same slot: user:{1001}:name and user:{1001}:age will be in the same slot, supporting cross-key operations.

10.3 Cluster Setup

bash
# Prepare 6 node config files (3 masters + 3 replicas)
# Add to each redis-cluster.conf:
cluster-enabled yes
cluster-config-file nodes-6379.conf
cluster-node-timeout 5000

# Create cluster using redis-cli
redis-cli --cluster create \
  192.168.1.101:6379 \
  192.168.1.102:6379 \
  192.168.1.103:6379 \
  192.168.1.104:6379 \
  192.168.1.105:6379 \
  192.168.1.106:6379 \
  --cluster-replicas 1

# View cluster info
redis-cli -c -h 192.168.1.101 CLUSTER INFO

# View node info
redis-cli -c -h 192.168.1.101 CLUSTER NODES

# View slot assignment
redis-cli -c -h 192.168.1.101 CLUSTER SLOTS
bash
cluster_state:ok
cluster_slots_assigned:16384
cluster_slots_ok:16384
cluster_slots_pfail:0
cluster_slots_fail:0
cluster_known_nodes:6
cluster_size:3

10.4 Cluster Scaling

bash
# Add new node
redis-cli --cluster add-node 192.168.1.107:6379 192.168.1.101:6379

# Reshard slots (needed when scaling up)
redis-cli --cluster reshard 192.168.1.101:6379
# Follow prompts to enter number of slots to migrate and target node ID

# Remove node (migrate slots first, then delete)
redis-cli --cluster del-node 192.168.1.101:6379 <node-id>

# Add replica node
redis-cli --cluster add-node 192.168.1.108:6379 192.168.1.101:6379 \
  --cluster-slave --cluster-master-id <master-node-id>

⚠️ Note: Running KEYS * in a cluster only returns keys from the current node. Use redis-cli --cluster check for cluster health checks.