redis

by apecloud

Helm chartv1.2.0-alpha.0App 7.2.7Verified publisher

Redis is an in-memory database that persists on disk. The data model is key-value, but many different kind of values are supported: Strings, Lists, Sets, Sorted Sets, Hashes, Streams, HyperLogLogs, Bitmaps.

About this chart

Redis

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. This example shows how it can be managed in Kubernetes with KubeBlocks.

Features In KubeBlocks

Lifecycle Management

TopologyHorizontalscalingVertical scalingExpandvolumeRestartStop/StartConfigureExposeSwitchover
replicationYesYesYesYesYesYesYesNo
standaloneYesYesYesYesYesYesYesN/A
shardingYesYesYesYesYesYesYesNo

Backup and Restore

FeatureMethodDescription
Full Backupdatafileuses redis-cli BGSAVE command to backup data
Continuous Backupaofcontinuously perform incremental backups by archiving Append-Only Files (AOF)

Versions

Major VersionsDescription
7.07.0.6
7.27.2.4

Prerequisites

  • Kubernetes cluster >= v1.21

  • kubectl installed, refer to K8s Install Tools

  • Helm, refer to Installing Helm

  • KubeBlocks installed and running, refer to Install Kubeblocks

  • Redis Addon Enabled, refer to Install Addons

  • Create K8s Namespace demo, to keep resources created in this tutorial isolated:

    kubectl create ns demo
    

Examples

Create

Create a Redis replication cluster with two components, one for Redis, and one for Redis Sentinel[^1].

For optimal reliability, you should run at least three Redis Sentinel replicas. Having three or more Sentinels ensures a quorum can be reached during failover decisions, maintaining the high availability of your Redis deployment.

# cat examples/redis/cluster.yaml
apiVersion: apps.kubeblocks.io/v1
kind: Cluster
metadata:
  name: redis-replication
  namespace: demo
spec:
  # Specifies the behavior when a Cluster is deleted.
  # Valid options are: [DoNotTerminate, Delete, WipeOut] (`Halt` is deprecated since KB 0.9)
  # - `DoNotTerminate`: Prevents deletion of the Cluster. This policy ensures that all resources remain intact.
  # - `Delete`: Extends the `Halt` policy by also removing PVCs, leading to a thorough cleanup while removing all persistent data.
  # - `WipeOut`: An aggressive policy that deletes all Cluster resources, including volume snapshots and backups in external storage. This results in complete data removal and should be used cautiously, primarily in non-production environments to avoid irreversible data loss.
  terminationPolicy: Delete
  # Specifies the name of the ClusterDefinition to use when creating a Cluster.
  # Note: DO NOT UPDATE THIS FIELD
  # The value must be `postgresql` to create a PostgreSQL Cluster
  clusterDef: redis
  # Specifies the name of the ClusterTopology to be used when creating the
  # Cluster.
  topology: replication
  # Specifies a list of ClusterComponentSpec objects used to define the
  # individual Components that make up a Cluster.
  # This field allows for detailed configuration of each Component within the Cluster
  componentSpecs:
    - name: redis
      # ServiceVersion specifies the version of the Service expected to be
      # provisioned by this Component.
      # Valid options are: [7.0.6,7.2.4]
      serviceVersion: "7.2.4"
      # Determines whether metrics exporter information is annotated on the
      # Component's headless Service.
      # Valid options are [true, false]
      disableExporter: false
      # Specifies the desired number of replicas in the Component
      replicas: 2
      # Specifies the resources required by the Component.
      resources:
        limits:
          cpu: '0.5'
          memory: 0.5Gi
        requests:
          cpu: '0.5'
          memory: 0.5Gi
      # Specifies a list of PersistentVolumeClaim templates that define the storage
      # requirements for the Component.
      volumeClaimTemplates:
        # Refers to the name of a volumeMount defined in
        # `componentDefinition.spec.runtime.containers[*].volumeMounts
        - name: data
          spec:
            # The name of the StorageClass required by the claim.
            # If not specified, the StorageClass annotated with
            # `storageclass.kubernetes.io/is-default-class=true` will be used by default
            storageClassName: ""
            accessModes:
              - ReadWriteOnce
            resources:
              requests:
                # Set the storage size as needed
                storage: 20Gi
    - name: redis-sentinel
      serviceVersion: "7.2.4"
      replicas: 3
      resources:
        limits:
          cpu: '0.5'
          memory: 0.5Gi
        requests:
          cpu: '0.5'
          memory: 0.5Gi
      # Specifies a list of PersistentVolumeClaim templates that define the storage
      # requirements for the Component.
      volumeClaimTemplates:
        # Refers to the name of a volumeMount defined in
        # `componentDefinition.spec.runtime.containers[*].volumeMounts
        - name: data
          spec:
            # The name of the StorageClass required by the claim.
            # If not specified, the StorageClass annotated with
            # `storageclass.kubernetes.io/is-default-class=true` will be used by default
            storageClassName: ""
            accessModes:
              - ReadWriteOnce
            resources:
              requests:
                # Set the storage size as needed
                storage: 20Gi

kubectl apply -f examples/redis/cluster.yaml

A cluster named redis-replication will be created with 1 primary pod, 1 secondary pod, and 3 sentinel pods.

kubectl get -n demo cluster redis-replication # get cluster info
kubectl get pod -n demo -l app.kubernetes.io/instance=redis-replication # get all pods of the cluster

[!NOTE] If all Pods are running, but the cluster status is still Creating, you may need to wait for a while until all Redis Pods are ready with corresponding Roles.

To check the role of each Redis pod, you can use the following command:

# replace `redis-replication` with your cluster name
kubectl get po -n demo -l app.kubernetes.io/instance=redis-replication,apps.kubeblocks.io/component-name=redis -L kubeblocks.io/role

Why Redis Sentinel starts first?

Redis Sentinel is a high availability solution for Redis. It provides monitoring, notifications, and automatic failover for Redis instances.

Each Redis replica, from the Redis component, upon startup, will connect to the Redis Sentinel instances to get the current leader and follower information. It needs to determine:

  • Whether it should act as the primary (master) node.
  • If not, which node is the current primary to replicate from.

In more detail, each Redis replica will:

  1. Check for Existing Primary Node
    • Queries Redis Sentinel to find out if a primary node is already elected.
    • Retrieve the primary's address and port.
  2. Initialize as Primary if Necessary
    • If no primary is found (e.g., during initial cluster setup), it configures the current Redis instance to become the primary.
    • Updates Redis configuration to disable replication.
  3. Configure as Replica if Primary Exists
    • If a primary is found, it sets up the current Redis instance as a replica.
    • Updates the Redis configuration with the replicaof directive pointing to the primary's address and port.
    • Initiates replication to synchronize data from the primary.

KubeBlocks ensures that Redis Sentinel starts first to provide the necessary information for the Redis replicas to initialize correctly. Such dependency is well-expressed in the KubeBlocks CRD ClusterDefinition ensuring the correct startup order.

More details on how components for the replication topology are started, upgraded can be found in:

kubectl get cd redis -oyaml | yq '.spec.topologies[] | select(.name=="replication") | .orders'

Horizontal scaling

Scale-out

Horizontal scaling out Redis component by adding ONE more replica:

# cat examples/redis/scale-out.yaml
apiVersion: operations.kubeblocks.io/v1alpha1
kind: OpsRequest
metadata:
  name: redis-scale-out
  namespace: demo
spec:
  # Specifies the name of the Cluster resource that this operation is targeting.
  clusterName: redis-replication
  type: HorizontalScaling
  # Lists HorizontalScaling objects, each specifying scaling requirements for a Component, including desired total replica counts, configurations for new instances, modifications for existing instances, and instance downscaling options
  horizontalScaling:
    # Specifies the name of the Component.
  - componentName: redis
    # Specifies the replica changes for scaling in components
    scaleOut:
      # Specifies the replica changes for the component.
      # add one more replica to current component
      replicaChanges: 1

kubectl apply -f examples/redis/scale-out.yaml

After applying the operation, you will see a new pod created and the cluster status goes from Updating to Running, and the newly created pod has a new role secondary.

And you can check the progress of the scaling operation with following command:

kubectl describe -n demo ops redis-scale-out

Scale-in

Horizontal scaling in Redis component by removing ONE replica:

# cat examples/redis/scale-in.yaml
apiVersion: operations.kubeblocks.io/v1alpha1
kind: OpsRequest
metadata:
  name: redis-scale-in
  namespace: demo
spec:
  # Specifies the name of the Cluster resource that this operation is targeting.
  clusterName: redis-replication
  type: HorizontalScaling
  # Lists HorizontalScaling objects, each specifying scaling requirements for a Component, including desired total replica counts, configurations for new instances, modifications for existing instances, and instance downscaling options
  horizontalScaling:
    # Specifies the name of the Component.
  - componentName: redis
    # Specifies the replica changes for scaling in components
    scaleIn:
      # Specifies the replica changes for the component.
      # add one more replica to current component
      replicaChanges: 1
kubectl apply -f examples/redis/scale-in.yaml

Scale-in/out using Cluster API

Alternatively, you can update the replicas field in the spec.componentSpecs.replicas section to your desired non-zero number.

# snippet of cluster.yaml
apiVersion: apps.kubeblocks.io/v1
kind: Cluster
spec:
  componentSpecs:
    - name: redis
      serviceVersion: "7.2.4"
      replicas: 2 # decrease `replicas` for scaling in, and increase for scaling out
      disableExporter: false

Vertical scaling

Vertical scaling involves increasing or decreasing resources to an existing database cluster. Resources that can be scaled include:, CPU cores/processing power and Memory (RAM).

Vertical scaling up or down requests and limits cpu or memory resource for Redis component:

# cat examples/redis/verticalscale.yaml
apiVersion: operations.kubeblocks.io/v1alpha1
kind: OpsRequest
metadata:
  name: redis-verticalscaling
  namespace: demo
spec:
  # Specifies the name of the Cluster resource that this operation is targeting.
  clusterName: redis-replication
  type: VerticalScaling
  # Lists VerticalScaling objects, each specifying a component and its desired compute resources for vertical scaling.
  verticalScaling:
  - componentName: redis
    # VerticalScaling refers to the process of adjusting the compute resources (e.g., CPU, memory) allocated to a Component. It defines the parameters required for the operation.
    requests:
      cpu: '1'
      memory: 1Gi
    limits:
      cpu: '1'
      memory: 1Gi

kubectl apply -f examples/redis/verticalscale.yaml

You will observe that the follower pods are recreated first, followed by the leader pod, to ensure the availability of the cluster.

Scale-up/down using Cluster API

Alternatively, you may update spec.componentSpecs.resources field to the desired resources for vertical scale.

# snippet of cluster.yaml
apiVersion: apps.kubeblocks.io/v1
kind: Cluster
spec:
  componentSpecs:
    - name: redis
      serviceVersion: "7.2.4"
      replicas: 2 # decrease `replicas` for scaling in, and increase for scaling out
      resources:
        requests:
          cpu: "1"       # Update the resources to your need.
          memory: "2Gi"  # Update the resources to your need.
        limits:
          cpu: "2"       # Update the resources to your need.
          memory: "4Gi"  # Update the resources to your need.

Expand volume

Volume expansion is the ability to increase the size of a Persistent Volume Claim (PVC) after it's created. It is introduced in Kubernetes v1.11 and goes GA in Kubernetes v1.24. It allows Kubernetes users to simply edit their PersistentVolumeClaim objects without requiring any downtime at all if possible.

[!NOTE] Make sure the storage class you use supports volume expansion.

Check the storage class with following command:

kubectl get storageclass

If the ALLOWVOLUMEEXPANSION column is true, the storage class supports volume expansion.

If you don't have a storage class that supports volume expansion, you can create a new one. Please refer to CSI drivers for more information.

To increase size of vol

Deploy redis with OpenTenant

Each tenant gets its own release of this chart, with its own namespace, secrets and domain. The builder below already has redis on a Hetzner server. Change the host, add apps from the marketplace, then copy the generated files. Providers and prices are samples, and nothing here is sent anywhere.

  1. Pick a serverConnect Hetzner, OVHcloud or AWS. The builder starts on Hetzner, the cheapest sample rate.
  2. Place the chartredis is pinned at v1.2.0-alpha.0 in opentenant.yaml. Drag more apps from the marketplace onto a rack.
  3. ApplySave opentenant.yaml and main.tf from the console, then run the commands below.
# opentenant.yaml, main.tf and dns.tf come from the builder below
opentenant validate opentenant.yaml
terraform init && terraform apply