Browse the Repo

file-type-icon.circleci
file-type-icon.github
file-type-iconexamples
file-type-iconmodules
file-type-iconelastic-cache
file-type-iconmemcached
file-type-iconredis
file-type-iconREADME.md
file-type-iconmain.tf
file-type-iconoutputs.tf
file-type-iconvars.tf
file-type-iconredis_copy_snapshot
file-type-icontest
file-type-icon.gitignore
file-type-icon.pre-commit-config.yaml
file-type-iconCODEOWNERS
file-type-iconLICENSE.txt
file-type-iconREADME.md
file-type-iconterraform-cloud-enterprise-private-module-...

Browse the Repo

file-type-icon.circleci
file-type-icon.github
file-type-iconexamples
file-type-iconmodules
file-type-iconelastic-cache
file-type-iconmemcached
file-type-iconredis
file-type-iconREADME.md
file-type-iconmain.tf
file-type-iconoutputs.tf
file-type-iconvars.tf
file-type-iconredis_copy_snapshot
file-type-icontest
file-type-icon.gitignore
file-type-icon.pre-commit-config.yaml
file-type-iconCODEOWNERS
file-type-iconLICENSE.txt
file-type-iconREADME.md
file-type-iconterraform-cloud-enterprise-private-module-...
Redis

Redis

Run a Redis cluster using Amazon’s ElastiCache Service. Supports replication, multi-zone automatic failover, and automatic backup.

Code Preview

Preview the Code

mobile file icon

README.md

down

Redis Module

This module creates an ElastiCache cluster that runs Redis.

The redis cluster is managed by AWS and automatically detects and replaces failed nodes, streamlines software upgrades and patches, enables easy scaling of the cluster both horizontally (add more nodes) and vertically (increase the power of existing nodes), and simplifies backup and restore functionality.

About Amazon ElastiCache

What is Amazon ElastiCache?

Before Amazon ElastiCache existed, teams would painstakingly configure the memcached or redis caching engines on their own. Setting up automatic failover, read replicas, backups, and handling upgrades are all non-trivial and AWS recognized they could implement these features according to best practices themselves, sparing customers the time and cost of doing it themselves. Behind the scenes, ElastiCache runs on EC2 Instances located in subnets and protected by security groups you specify.

Structure of an ElastiCache Redis deployment

  • Nodes: The smallest unit of an ElastiCache Redis deployment is a node. It's basically the network-attached RAM on which the cache engine (Redis in this case) runs
  • Shards: Also sometimes called "Node Group". A Shard is a replication-enabled collection of multiple nodes. Within a Shard, one node is the primary read/write node while the rest are read-only replicas of the primary node.
  • Cluster: An ElastiCache cluster is a collection of one or more Shards. Somewhat confusingly, an ElastiCache Cluster has a "cluster mode" property that allows a Cluster to distribute its data over multiple Shards.

Concept of Sharding & Replication in ElasticCache Redis

Redis implements replication in two ways:

  • Cluster Mode Disabled: With a single shard that contains all of the cluster's data in each node
  • Cluster Mode Enabled: With data partitioned across up to 500 shards

Each shard in a replication group has a single read/write primary node and up to 5 read-only replica nodes. You can create a cluster with higher number of shards and lower number of replicas totaling up to 90 nodes per cluster. This cluster configuration can range from 90 shards and 0 replicas to 15 shards and 5 replicas, which is the maximum number of replicas allowed.

The node or shard limit can be increased to a maximum of 500 per cluster if the Redis engine version is 5.0.6 or higher. For example, you can choose to configure a 500 node cluster that ranges between 83 shards (one primary and 5 replicas per shard) and 500 shards (single primary and no replicas). Make sure there are enough available IP addresses to accommodate the increase. Common pitfalls include the subnets in the subnet group have too small a CIDR range or the subnets are shared and heavily used by other clusters.

You can find more information here: https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Replication.Redis.Groups.html

Different Modes of ElasticCache Redis deployment

There are different types of modes you can deploy ElasticCache Redis:

Mode Description Configuration
Cluster Enabled - supports sharding <br/> - supports replication - enable_single_instance_mode = false <br/> - cluster_mode:num_node_groups > 1
Cluster Disabled - no replication <br/> - supports sharding - enable_single_instance_mode = false <br/> - cluster_mode:num_node_groups = 1 <br/> <br/> Note: do not include .cluster.on suffix if you are setting parameter_group_name.
Single Instance - no replication <br/> - no sharding - enable_single_instance_mode = true

How to Enable Cluster Mode with Single Sharding

By default, if you set cluster_mode::num_node_groups = 1, you are deploying Redis with the cluster mode disabled. If you want to enable cluster mode for redis with single sharding, you need to explicitly set the parameter group with cluster-enabled=yes (e.g., default.redis5.0.cluster.on). You can find the list of default parameter group for different redis version family group here: https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/ParameterGroups.Redis.html

Choosing Cluster Mode vs. Single Instance

You can use var.enable_single_instance_mode=true to deploy a single node Redis instance. Refer to examples/redis_single_instance as an example.

Here are some of the points you may consider while choosing which mode to run:

  • Scalability: Redis single instance is limited to a single server node, which can be scaled vertically, while Redis cluster mode supports horizontal scaling by distributing data across multiple nodes, up to 1000 nodes. This allows for increased capacity, availability, and fault tolerance.
  • High Availability: Redis single instance has limited high availability options, as it can only be replicated to a slave node. In contrast, Redis cluster mode provides more robust high availability features by automatically distributing data across multiple nodes and ensuring data replication, even in the case of node failures.
  • Performance: Redis cluster mode provides improved performance, as it allows for distributing the data across multiple nodes, providing more CPU and memory resources. Additionally, Redis cluster mode uses sharding to distribute keys across multiple nodes, allowing for parallel data processing and faster data access.
  • Complexity: Redis cluster mode introduces more complexity than Redis single instance. Configuring and managing a Redis cluster requires more effort and expertise, as it involves setting up and managing multiple nodes, and configuring the sharding and replication.

How do you connect to the Redis Cluster?

  • When connecting to Redis (cluster mode disabled) from your app, direct all operations to the Primary Endpoint of the Cluster. This way, in the event of a failover, your app will be resolving a DNS record that automatically gets updated to the latest primary node.

  • When connecting to Redis (cluster mode enabled) from your app, direct all reads/writes to the **Configuration Endpoint ** of the Cluster. Ensure you have a client that supports Redis Cluster (redis 3.2). You can still read from individual node enpoints.

  • In both "cluster mode enabled" and "cluster mode disabled" deployment models you can still direct reads to any of the Read Endpoints of the nodes in the Cluster, however you now risk reading a slightly out-of-date copy of the data in the event that you read from a node before the primary's latest data has synced to it.

  • (Optional) It is possible to link a user_group_id and provide a list of user_id's to add additional layers of security for your cluster or replication group. Refer to the ElasticCache RBAC Access documentation for further information.

  • (Optional) It is also possible to update the default user id used by AWS when creating a redis cluster and replace it with your own default user. This is actually recommended by AWS as a first step to securing your Redis cluster. Refer to the Role-Based Access Control (RBAC) documentation on how to do this. The new user_id can be passed into the Redis clusters user group via the default_user_id variable.

This module outputs Terraform output variables that contain the address of the primary endpoint and read endpoints. You can programmatically extract these variables in your Terraform templates and pass them to other resources (e.g. as environment variables in an EC2 Instance) You'll also see the variables at the end of each terraform apply call or if you run terraform output.

How do you scale the Redis Cluster?

You can scale your ElastiCache Cluster either horizontally (by adding more nodes) or vertically (by using more powerful nodes), but the method depends on whether Cluster Mode is enabled or disabled.

When Cluster Mode is Disabled

This mode is useful when you'd prefer to have only a single point for data to be written to the redis database. All data is written to the primary node of the single shard which is now replicated to the replica nodes. The advantage of this approach is that you're sure that all your data is present at a single point which could make migrations and backups a lot easier, if there's a problem with the primary write node however, all write attempts will fail.

  • Vertical: You can increase the type of the read replica nodes using the instance_type parameter ( see here for valid values).

  • Horizontal: You can add up to 5 replica nodes to a Redis Cluster using the cluster_size parameter. There is always a primary node where all writes take place, but you can reduce load on this primary node by offloading reads to the non-primary nodes, which are known as Read Replicas.

For more info on both methods, see Scaling Single-Node Redis (cluster mode disabled) Clusters.

When Cluster Mode is Enabled

When cluster mode is enabled, data you write is split among the primary nodes in multiple Shards, and each data stored in those Shards are replicated among the read replicas. If one Shard becomes unavailable for whatever reason, other shards are still available for writing.

To deploy a Redis "cluster mode enabled" cluster you must ensure that the enable_automatic_failover parameter is set to true and the cluster_mode variable has a single map with num_shards and replicas_per_shard parameters.

E.g. the following Terraform code specifies a "cluster mode enabled" Cluster with 2 Shards and 1 Read Replica per Shard

cluster_mode = [
  {
    num_node_groups         = 2
    replicas_per_node_group = 1
  }
]
  • Horizontal: A "cluster mode enabled" cluster can be scaled horizontally by adding more Shards - also called Resharding, the amount of read replicas present in the extra Shards is the same as the number specified when the cluster was originally created. Resharding can take anywhere from a few minutes to several hours.

  • Vertical: A "cluster mode enabled" cluster can be scaled vertically by changing the node types within each Shard. This method is offline only and the cluster has to be backed up, a new cluster created with the required node types and the backup restored to that new cluster. During this process your entire cluster will experience a downtime which could last for any length of time depending on how much data the original cluster contained.

For more info on scaling "cluster mode enabled" Redis clusters, see Scaling Multishard Redis (cluster mode disabled) Clusters

How do you use the auto-scaling feature?

Auto Scaling ElastiCache for Redis clusters summarizes how auto-scaling works for Redis clusters. You can enable auto-scaling via using the following variables:

  • enable_auto_scaling: true
  • auto_scale_dimension: choose one from the supported scalable dimension mentioned below
  • auto_scale_trigger_metric: choose one from the supported trigger metric mentioned below
  • auto_scale_min_capacity: choose the desired min capacity
  • auto_scale_max_capacity: choose the desired max capacity (Note: depends on the configuration of the Redis cluster. (e.g., 5 would be the maximum for replica auto-scaling)

Prerequisites

ElastiCache for Redis Auto Scaling is limited to the following:

  • Redis (cluster mode enabled) clusters running Redis engine version 6.0 onwards
  • Instance type families - R5, R6g, M5, M6g
  • Instance sizes - Large, XLarge, 2XLarge
  • Auto Scaling in ElastiCache for Redis is not supported for clusters running in Global datastores, Outposts or Local Zones.
  • AWS Auto Scaling for ElastiCache for Redis is not available in the following regions: China (Beijing), China ( Ningxia), AWS GovCloud (US-West) and AWS GovCloud (US-East).

Supported Predefined Metrics

Here are some predefined metrics available for Redis: ElastiCachePrimaryEngineCPUUtilization (shards auto-scale), ElastiCacheReplicaEngineCPUUtilization (replica auto-scale). You can find more information here:

Both pages also explain how to use a custom metric and you can find the list of CloudWatch metrics for Redis from here: https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/CacheMetrics.Redis.html

Supported Scalable Dimensions

ElastiCache for Redis supports the following types of automatic scaling dimensions:

  • elasticache:replication-group:NodeGroups - The number of node groups for an Amazon ElastiCache replication group.
  • elasticache:replication-group:Replicas - The number of replicas per node group for an Amazon ElastiCache replication group.

How do you use this module?

Start by referencing one of the example modules:

ElastiCache Old Terminology

Prior to October 2016, ElastiCache for Redis did not support partitioning (aka sharding) in Redis and as a result used a bunch of confusing terminologies to explain setting up a Redis cluster.

  • Cluster: In ElastiCache, each Redis node is labeled its own "cluster", despite that there is only a single node in the cluster. This is an artifact of how ElastiCache implements memcached clusters, which can support multiple nodes.

  • Replication Group: The Redis "read/write primary cluster" will asynchronously copy its data to all other Redis clusters (individual nodes) in the same Replication Group. In a sense, the "real" redis cluster in ElastiCache is actually the Replication Group.

  • Primary Cluster: In a Replication Group, the primary cluster is where all write traffic is directed. Initially, you can direct all your reads here as well.

  • Read Replicas: In a Replication Group, data written to the primary cluster is asynchronously copied to each Read Replica. These are useful both to reduce the read load on the primary cluster and to faciliate fast failover.

  • Multi-AZ: Using the Multi-AZ option means that if the primary cluster fails, ElastiCache will auto failover to a Read Replica. Without this option, the primary cluster node will simply replace itself, which will take longer and may result in additional data loss.

Common Gotcha's

  • In the event of a Redis failover, you will experience a small period of time during which writes are not accepted, so make sure your app can handle this gracefully. In fact, consider simulating Redis failovers on a regular basis or with automated testing to validate that your app can handle it correctly.

  • Test that your app does not cache the DNS value of the Primary Endpoint! Java, in particular, has undesirable defaults around DNS caching in many cases. If your code does not honor the TTL property of the Primary Endpoint's DNS record, then your app may fail to reach the new primary node in the event of a failure.

  • The only way to add more storage space to nodes in a Redis Cluster (cluster mode disabled) is to scale up to a larger node type.

Choosing Redis Cluster Mode vs. Single Instance

You can use var.disable_cluster_mode=true to deploy a single node Redis instance. Refer to examples/redis_single_instance as an example.

Here are some of the points you may consider while choosing which mode to run:

  • Scalability: Redis single instance is limited to a single server node, which can be scaled vertically, while Redis cluster mode supports horizontal scaling by distributing data across multiple nodes, up to 1000 nodes. This allows for increased capacity, availability, and fault tolerance.
  • High Availability: Redis single instance has limited high availability options, as it can only be replicated to a slave node. In contrast, Redis cluster mode provides more robust high availability features by automatically distributing data across multiple nodes and ensuring data replication, even in the case of node failures.
  • Performance: Redis cluster mode provides improved performance, as it allows for distributing the data across multiple nodes, providing more CPU and memory resources. Additionally, Redis cluster mode uses sharding to distribute keys across multiple nodes, allowing for parallel data processing and faster data access.
  • Complexity: Redis cluster mode introduces more complexity than Redis single instance. Configuring and managing a Redis cluster requires more effort and expertise, as it involves setting up and managing multiple nodes, and configuring the sharding and replication.

Questions? Ask away.

We're here to talk about our services, answer any questions, give advice, or just to chat.

Ready to hand off the Gruntwork?