Learn Redis Β· 13/15

Scaling Out: Replication, Sentinel, and Cluster

9 min read

Scaling Out: Replication, Sentinel, and Cluster Scaling Out: Replication, Sentinel, and Cluster Scaling Out: Replication, Sentinel, and Cluster

Alright, let's talk about making your Redis setup bigger, stronger, and more resilient. πŸ’ͺ As your application grows, a single Redis instance might start to feel like a one-person kitchen trying to serve a thousand hungry customers. It can get overwhelmed! This is where scaling out comes in. We'll explore three key strategies to handle more traffic and keep things running smoothly even when things go wrong.

πŸ“œ Primary-Replica Replication: Scaling Read Operations

The Problem: Imagine your blog suddenly goes viral. πŸš€ You're getting a massive number of read requests as people flock to see your latest post. Your single Redis instance, which is busy handling both reads and writes (like new comments), starts to slow down.

The Solution: This is where primary-replica replication shines. It's a simple yet powerful concept: you create one or more copies (replicas) of your main Redis instance (the primary).

  • Primary: The single source of truth. All write operations (e.g., SET, HSET, LPUSH) go to the primary.
  • Replica: A read-only copy of the primary. Replicas can handle a large number of read operations (e.g., GET, HGET, LRANGE), thus taking the load off the primary.

Think of it like a popular author (the primary) writing a book. Instead of everyone crowding around the author to read the original manuscript, copies (replicas) are printed and distributed, allowing many people to read simultaneously without disturbing the author.

How it Works Under the Hood (The Gist)

When you set up a replica, it connects to the primary and performs an initial full synchronization. The primary creates a snapshot of its data (an RDB file) and sends it to the replica. After that, the primary sends a continuous stream of commands to the replica to keep it updated with any new changes. This replication process is asynchronous, which means the primary doesn't wait for the replica to confirm receipt of every command, keeping things fast.

Hands-On: Setting up Primary-Replica Replication

Let's get our hands dirty. For this, you'll need two Redis instances running. Let's assume your primary is on 127.0.0.1:6379 and you want to set up a replica on 127.0.0.1:6380.

1. Configure the Replica:

Open the configuration file for your replica instance (redis.conf for port 6380). Add or uncomment the following line:

apache
replicaof 127.0.0.1 6379

You can also set this configuration on the fly using the redis-cli:

bash
redis-cli -p 6380 REPLICAOF 127.0.0.1 6379

2. Verify the Replication:

Connect to the primary and check its replication status:

bash
redis-cli -p 6379 INFO replication

You should see information about the connected replica.

Now, connect to the replica and check its status:

bash
redis-cli -p 6380 INFO replication

You should see that its role is slave (an older term for replica) and the master_host and master_port are correctly set.

3. Test it Out:

  • Write some data to the primary:
    bash
    redis-cli -p 6379 SET mykey "Hello, replication!"
  • Read the data from the replica:
    bash
    redis-cli -p 6380 GET mykey
    You should see "Hello, replication!".

Interesting Fact: By default, replicas are read-only. This is a safety feature to prevent accidental data inconsistencies.

πŸ›‘οΈ Redis Sentinel: Automated Failover and High Availability

The Problem: Your primary-replica setup is great for handling reads, but what happens if the primary server crashes? 😱 Your application can no longer write data, and you have to manually promote a replica to become the new primary. This is a single point of failure and requires manual intervention, which is not ideal for production systems.

The Solution: Enter Redis Sentinel, your ever-watchful guardian. Sentinel is a separate process that monitors your Redis instances and provides high availability. If the primary goes down, Sentinel will automatically:

  1. Detect the failure.
  2. Elect a new primary from the available replicas.
  3. Reconfigure the other replicas to follow the new primary.
  4. Inform your application about the new primary's address.

Imagine a team of security guards (Sentinels) monitoring a VIP (the primary). If the VIP has a problem, the guards will immediately designate one of the VIP's trained body-doubles (replicas) to take their place, ensuring the mission continues without a hitch.

Key Concepts of Sentinel

  • Quorum: This is the minimum number of Sentinels that must agree that a primary is down before a failover process is initiated. This prevents false positives where a single Sentinel might have a network issue and mistakenly think the primary is offline. A common setup is to have 3 Sentinels with a quorum of 2.
  • Subjective Down (SDOWN): When a single Sentinel can't reach the primary, it marks it as "subjectively down."
  • Objective Down (ODOWN): When the number of Sentinels reporting an SDOWN condition reaches the configured quorum, the primary is marked as "objectively down," and the failover process begins.

Hands-On: A Glimpse into Sentinel Setup

Setting up Sentinel involves creating a sentinel.conf file for each Sentinel process.

A minimal sentinel.conf might look like this:

smali
sentinel monitor mymaster 127.0.0.1 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
sentinel parallel-syncs mymaster 1
  • sentinel monitor mymaster 127.0.0.1 6379 2: This tells Sentinel to monitor a primary named mymaster at 127.0.0.1:6379 with a quorum of 2.
  • sentinel down-after-milliseconds mymaster 5000: The time in milliseconds that a primary must be unreachable before a Sentinel considers it subjectively down.
  • sentinel failover-timeout mymaster 60000: The time in milliseconds after which a failover is considered to have timed out.
  • sentinel parallel-syncs mymaster 1: The number of replicas that can be reconfigured to sync with the new primary at the same time.

To start Sentinel, you would run:

bash
redis-server /path/to/sentinel.conf --sentinel

Your client application would then connect to a Sentinel to get the current address of the primary, rather than hardcoding the primary's address.

Industry Practice: For a production environment, it is highly recommended to run at least three Sentinel instances on different machines to ensure a robust setup.

πŸš€ Redis Cluster: Scaling Writes and Sharding Data

The Problem: Your application is now incredibly popular, with a massive amount of data and a high volume of both read and write requests. A single primary, even with replicas, can't handle the write load anymore, and the entire dataset is too large to fit on a single machine.

The Solution: This is where Redis Cluster comes to the rescue. It provides a way to automatically partition your data across multiple Redis nodes, a process called sharding. This means that both your data and the read/write load are distributed, allowing you to scale horizontally by adding more nodes.

Imagine a massive library (your dataset). Instead of having one giant, overwhelming room, the library is divided into several smaller, manageable sections (shards), each with its own librarian (Redis node). When you're looking for a specific book (a key), you're directed to the correct section.

How Redis Cluster Works

Redis Cluster uses a concept called hash slots to distribute data. There are 16,384 hash slots in a cluster. When you store a key, Redis calculates a CRC16 hash of the key and then performs a modulo operation with 16,384 to determine which hash slot the key belongs to. Each node in the cluster is responsible for a subset of these hash slots.

Redis Cluster also provides high availability. Each primary node in the cluster can have one or more replicas. If a primary fails, one of its replicas can be automatically promoted to become the new primary, ensuring that the data in those hash slots remains available.

πŸ”’ Understanding Hash Slots in a Redis Cluster

The Problem: How does Redis Cluster decide where to store a key? And how can you perform operations on multiple keys at once if they might be on different nodes?

The Solution: As we just touched on, it's all about hash slots. Let's dive a little deeper.

The formula is simple: HASH_SLOT = CRC16(key) % 16384.

For example, in a 3-node primary cluster:

  • Node A might hold hash slots 0 to 5500.
  • Node B might hold hash slots 5501 to 11000.
  • Node C might hold hash slots 11001 to 16383.

When a client sends a command for a particular key, any node in the cluster can calculate the hash slot for that key. If the node receiving the command is not the one responsible for that hash slot, it will respond with a MOVED error, telling the client which node it should talk to. Smart clients will cache this information to avoid this redirection in the future.

The "Hash Tag" Trick for Multi-Key Operations

A common challenge with sharded databases is performing operations on multiple keys that might reside on different nodes. Redis Cluster will reject commands that involve keys in different hash slots with a CROSSSLOT error.

To solve this, Redis Cluster has a clever feature called hash tags. If a key contains a substring enclosed in curly braces {}, only the part inside the braces is used to calculate the hash slot.

For example, the keys user:{123}:profile and user:{123}:orders are guaranteed to be in the same hash slot because only the 123 part is used for the hash calculation. This allows you to perform multi-key operations on related data.

Caution: While powerful, overuse of hash tags can lead to an unbalanced cluster, where one node holds significantly more data than others (a "hot spot"). Use them wisely!

Hands-On: Creating a Simple Redis Cluster

Creating a Redis Cluster requires at least three primary nodes for a minimal production-like setup.

1. Configuration:

You'll need a redis.conf for each node with at least these settings:

stata
port 7000
cluster-enabled yes
cluster-config-file nodes-7000.conf
cluster-node-timeout 5000
appendonly yes

2. Starting the Nodes:

Start each Redis instance with its respective configuration file.

3. Creating the Cluster:

The redis-cli tool makes creating a cluster easy. For a cluster with 3 primaries and 3 replicas, you would run a command like this:

bash
redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005 --cluster-replicas 1

This command will automatically assign hash slots and set up the primary-replica relationships.

Funny Exaggeration: Trying to run a multi-key operation on keys in different slots is like trying to pay for your groceries in the vegetable aisle. The cashier (the Redis node) will just point you to the correct checkout lane.


πŸ“š Further Reading and References

Challenge

You are a Redis administrator designing a sharded database using Redis Cluster. Your task involves both configuration and data modeling.

Part 1: Configuration
In the configuration section, write the two redis.conf directives required to:

  1. Enable Redis Cluster mode.
  2. Specify that the cluster's state configuration file should be named nodes-7001.conf.

Part 2: Data Hashing
In the commands section, write three separate redis-cli SET commands. These commands must use hash tags to ensure that data for a specific user is stored on the same cluster node.

  • The user ID is 952.
  • The key for the username should be user:username:{952} and its value alice.
  • The key for the email should be user:email:{952} and its value [email protected].
  • The key for the last login timestamp should be user:lastlogin:{952} and its value 1672531200.

Expected result

The solution must be divided into two parts as indicated by the comments in the initial code.

Part 1 should contain two configuration lines:

  • The cluster-enabled directive set to yes.
  • The cluster-config-file directive specifying nodes-7001.conf.

Part 2 should contain three valid SET commands:

  • Each command must correctly use the SET syntax (e.g., SET key value).
  • All three keys must use the specified format which includes the hash tag {952} to ensure they map to the same hash slot.
  • The keys and their corresponding values must match the user data specified in the instructions.
plain text

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.