Skip to main content

Implementing ElastiCache Redis Caching Patterns

Implement ElastiCache Redis with Lazy Loading, Write-Through, and Session Store patterns to cut database load and serve repeat reads in microseconds.

Overview and What You Will Learn

Amazon ElastiCache is a managed in-memory cache that sits in front of a database so repeated reads are served from RAM in under a millisecond instead of hitting the database. Use Redis for almost every production workload, and pair it with one of three patterns: Lazy Loading, Write-Through or a Session Store.

In this lab, you will:

  • Build a Multi-AZ Redis replication group with encryption on, using the AWS CLI
  • Run basic commands, TTLs and a Lazy Loading simulation from an EC2 instance
  • Read cache hit and miss counters
  • Trigger a failover and watch a replica take over

Why This Matters in Production

Picture a food delivery platform like Swiggy at dinner peak. Thousands of users open the same restaurant menu each second, and without a cache every request becomes an identical SELECT against the database. CPU climbs, latency rises for every query, and the database becomes the bottleneck. With Redis in front, the first request fills the cache and the next ten thousand are answered from memory while the database stays quiet.

Core Principles

Why Caching Solves Two Database Problems

A cache removes repeated reads, which cuts database load, and it replaces a 5 to 20 ms query with a sub-millisecond lookup. The application checks the cache first, and only a miss reaches the database.

flowchart TD A([Request]) --> B{In cache?} B -->|Hit| C[Return from Redis] B -->|Miss| D[(Query database)] D --> E[Store with TTL] E --> C classDef start fill:#475569,color:#FFFFFF classDef decision fill:#F59E0B,color:#111827 classDef cache fill:#10B981,color:#FFFFFF classDef db fill:#326CE5,color:#FFFFFF class A start class B decision class C,E cache class D db

Redis or Memcached

Choose Redis for any workload where losing the cache would hurt, because it supports replication, Multi-AZ failover and persistence. Memcached only fits a simple, multi-threaded string cache that can disappear without consequence.

Feature Redis Memcached
Data structures Strings, hashes, lists, sets, sorted sets Strings only
Replication and failover Yes, automatic Multi-AZ No
Persistence and pub/sub Yes No
Remember

ElastiCache also offers Valkey, an open-source Redis-compatible engine, at a lower price. The commands and patterns in this guide apply to it as well.

Pattern 1: Lazy Loading (Cache-Aside)

The application checks the cache, and on a miss it reads the database and stores the result with a TTL. Only requested data is cached, and a cache outage falls back to the database, but data can be stale until the TTL expires.

Python
import json
import redis
cache = redis.Redis(host="devops-cache.abc123.ng.0001.aps1.cache.amazonaws.com",
port=6379, ssl=True)
def get_restaurant_menu(restaurant_id):
cache_key = f"menu:{restaurant_id}"
cached = cache.get(cache_key)
if cached:
return json.loads(cached) # Cache hit
menu = db.query("SELECT * FROM menus WHERE restaurant_id = %s", restaurant_id)
cache.setex(cache_key, 300, json.dumps(menu)) # Miss: store for 300 seconds
return menu

The risk is a cache stampede: when a hot key expires, thousands of requests miss at once and all hit the database. A lock lets one request repopulate the key while the rest wait:

Python
import redis_lock
def get_restaurant_menu(restaurant_id):
cache_key = f"menu:{restaurant_id}"
cached = cache.get(cache_key)
if cached:
return json.loads(cached)
with redis_lock.Lock(cache, f"lock:{cache_key}", expire=10):
cached = cache.get(cache_key) # Re-check: another request may have filled it
if cached:
return json.loads(cached)
menu = db.query("SELECT * FROM menus WHERE restaurant_id = %s", restaurant_id)
cache.setex(cache_key, 300, json.dumps(menu))
return menu

Pattern 2: Write-Through

Every write updates the database and the cache together, so reads almost always hit and data is never stale. The cost is a slower write and memory spent on data that may never be read.

Python
def update_restaurant_menu(restaurant_id, menu_data):
db.execute("UPDATE menus SET data = %s WHERE restaurant_id = %s",
json.dumps(menu_data), restaurant_id)
cache.setex(f"menu:{restaurant_id}", 300, json.dumps(menu_data))
Tip

Combine the two. Use Write-Through for data that is read and written often, and Lazy Loading for read-heavy data that rarely changes. Always set a TTL either way.

Pattern 3: Session Store

Store user sessions in Redis instead of in EC2 memory, so any instance can serve any user and you do not need sticky sessions. Sticky sessions skew load, and the session is lost anyway if that instance dies.

Python
import redis
from flask import Flask, redirect, render_template, request, session
from flask_session import Session
app = Flask(__name__)
app.config["SESSION_TYPE"] = "redis"
app.config["SESSION_REDIS"] = redis.Redis(
host="devops-cache.abc123.ng.0001.aps1.cache.amazonaws.com", port=6379, ssl=True)
app.config["PERMANENT_SESSION_LIFETIME"] = 86400 # 24 hour TTL
Session(app)
@app.route("/login", methods=["POST"])
def login():
session["user_id"] = authenticate_user(request.form)
return redirect("/dashboard")
@app.route("/dashboard")
def dashboard():
if "user_id" not in session:
return redirect("/login")
return render_template("dashboard.html", user_id=session["user_id"])

ElastiCache Redis or DAX for DynamoDB

Use DAX when the only goal is faster DynamoDB reads, because it needs no code changes beyond the endpoint. Use ElastiCache Redis when you must cache computed results, aggregations or data from other sources.

Cluster Mode and Failover

Cluster Mode Disabled has one primary and up to five read replicas, so it scales reads. Cluster Mode Enabled splits data across shards, each with its own primary and replicas, so it scales memory and writes too.

Mode Scales Use for
Disabled Reads only Datasets that fit one node
Enabled Reads, writes, memory Large or write-heavy datasets

On a primary failure, ElastiCache promotes a replica and updates the endpoint DNS, usually within a minute. Your application must reconnect, and connection pooling helps. ElastiCache Serverless removes node sizing entirely and bills for data stored and compute used, which suits new or spiky workloads.

Detailed Step-by-Step Practical Lab

This lab uses the AWS CLI and a small EC2 instance in the same VPC. Replace the placeholder IDs with your own, and remember that Redis must live in private subnets.

Bash
export AWS_REGION=ap-south-1
export VPC_ID=vpc-0abc1234567890def
export APP_SG=sg-0aaa1111bbbb2222c
export SUBNET_A=subnet-0aaa1111bbbb2222c
export SUBNET_B=subnet-0ddd3333eeee4444f
  1. Create a security group that only the application security group can reach on port 6379:
Bash
export REDIS_SG=$(aws ec2 create-security-group \
--group-name redis-sg --description "Redis from app tier" \
--vpc-id $VPC_ID --query GroupId --output text --region $AWS_REGION)
aws ec2 authorize-security-group-ingress \
--group-id $REDIS_SG --protocol tcp --port 6379 \
--source-group $APP_SG --region $AWS_REGION
  1. Create a subnet group from two private subnets in different AZs:
Bash
aws elasticache create-cache-subnet-group \
--cache-subnet-group-name redis-subnet-group \
--cache-subnet-group-description "Private subnets for Redis" \
--subnet-ids $SUBNET_A $SUBNET_B --region $AWS_REGION
  1. Create a Multi-AZ replication group with one primary and one replica, with encryption at rest and in transit, then wait for it:
Bash
aws elasticache create-replication-group \
--replication-group-id mumbai-prod-redis \
--replication-group-description "Mumbai prod cache lab" \
--engine redis --cache-node-type cache.t3.micro \
--num-cache-clusters 2 \
--automatic-failover-enabled --multi-az-enabled \
--cache-subnet-group-name redis-subnet-group \
--security-group-ids $REDIS_SG \
--at-rest-encryption-enabled --transit-encryption-enabled \
--region $AWS_REGION
aws elasticache wait replication-group-available \
--replication-group-id mumbai-prod-redis --region $AWS_REGION
  1. Fetch the primary endpoint:
Bash
export REDIS_HOST=$(aws elasticache describe-replication-groups \
--replication-group-id mumbai-prod-redis --region $AWS_REGION \
--query 'ReplicationGroups[0].NodeGroups[0].PrimaryEndpoint.Address' --output text)
echo $REDIS_HOST
  1. From an EC2 instance in the same VPC, install a client and connect. Because encryption in transit is on, the client needs --tls. On Amazon Linux 2023 the package is redis6 and the client is redis6-cli:
Bash
sudo dnf install -y redis6
redis6-cli -h $REDIS_HOST -p 6379 --tls PING
  1. Try keys and TTLs inside the client:
Bash
redis6-cli -h $REDIS_HOST --tls SET user:101:name "Rahul Sharma"
redis6-cli -h $REDIS_HOST --tls GET user:101:name
redis6-cli -h $REDIS_HOST --tls SET session:abc123 active EX 30
redis6-cli -h $REDIS_HOST --tls TTL session:abc123
  1. Simulate Lazy Loading by hand: a miss, a "database read", a store, then a hit:
Bash
redis6-cli -h $REDIS_HOST --tls GET product:P001 # (nil) = miss
redis6-cli -h $REDIS_HOST --tls SET product:P001 '{"name":"Biryani","price":250}' EX 300
redis6-cli -h $REDIS_HOST --tls GET product:P001 # now a hit
  1. Read the hit and miss counters. The ratio of hits to total lookups is your cache hit rate:
Bash
redis6-cli -h $REDIS_HOST --tls INFO stats | grep -E "keyspace_hits|keyspace_misses"
  1. Test failover. The replica is promoted, and the same endpoint keeps working after DNS updates:
Bash
aws elasticache test-failover \
--replication-group-id mumbai-prod-redis \
--node-group-id 0001 --region $AWS_REGION
aws elasticache describe-events --source-type replication-group \
--duration 30 --region $AWS_REGION
  1. Clean up. Delete the replication group first, because the subnet group and security group cannot be removed while it exists:
Bash
aws elasticache delete-replication-group \
--replication-group-id mumbai-prod-redis --region $AWS_REGION
aws elasticache wait replication-group-deleted \
--replication-group-id mumbai-prod-redis --region $AWS_REGION
aws elasticache delete-cache-subnet-group \
--cache-subnet-group-name redis-subnet-group --region $AWS_REGION
aws ec2 delete-security-group --group-id $REDIS_SG --region $AWS_REGION

Production Best Practices & Common Pitfalls

Common Mistake

Running one cache node with no replica. When it fails the cache disappears, every request falls back to the database at once, and the sudden spike can take the database down too. Run at least one replica with Multi-AZ failover.

Common Mistake

Assuming ElastiCache works transparently in front of RDS. It is not a proxy, so your code must check the cache, fall back to the database on a miss, and store the result.

Security

Never put ElastiCache in a public subnet or open its security group to the internet. Keep it private, allow only the application security group, and turn on encryption at rest, encryption in transit and Redis AUTH or IAM authentication.

  • Set a TTL on every cached item. Without one the cache grows until the eviction policy discards useful data, so also confirm maxmemory-policy suits your use, for example allkeys-lru.
  • Reuse connections. Opening a new Redis connection per request is expensive, so use connection pooling.
  • Watch the hit rate in CloudWatch. A rate below roughly 80% means the keys or TTLs do not match real query patterns.
  • Avoid KEYS * on a live cluster. It scans every key and blocks the server, so use SCAN instead.
  • Use Sorted Sets for leaderboards. ZADD and ZRANGE rank millions of entries in microseconds, where a database would sort the full table.
  • Choose Redis over Memcached for new workloads. Memcached only wins for a simple, disposable, multi-threaded string cache.

Quick Reference & Troubleshooting Commands

Command Description
aws elasticache describe-replication-groups List clusters and their endpoints
aws elasticache describe-events See failovers and maintenance events
aws elasticache test-failover Trigger a controlled failover
redis6-cli -h HOST --tls PING Test connectivity
redis6-cli -h HOST --tls SET key value EX 300 Set a key with a 300 second TTL
redis6-cli -h HOST --tls TTL key Check remaining time to live
redis6-cli -h HOST --tls INFO stats Read hit and miss counters
Problem Likely cause Fix
Cannot connect Security group blocks 6379, or --tls missing Allow the app security group and add --tls
Hit rate below 50% TTL too short or wrong keys cached Raise the TTL and cache what is queried most
Memory grows without bound No TTL on keys Set TTLs and review maxmemory-policy
No failover on primary loss Automatic failover disabled Enable it on the replication group
Sessions lost between requests Sessions stored in EC2 memory Move sessions to Redis

Resources

AWS Direct Connect vs VPN: Run Both as Failover

AWS Direct Connect vs VPN: Run Both as Failover

Run AWS Direct Connect as primary and Site-to-Site VPN as BGP failover. Size the backup, set route preference and test it before an outage does.

10 min read•Aug 2026
Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot, at the crossover where Lambda stops being cheaper — 2026 pricing, invocation thresholds, and interruption math.

5 min read•Aug 2026
Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault: cost math, rotation, dynamic secrets and a decision flow, plus the Vault, IBM and OpenBao licensing context.

10 min read•Aug 2026
AWS VPC Security: Hardening Every Layer

AWS VPC Security: Hardening Every Layer

Harden your AWS VPC in layers: subnets, Security Groups, NACLs, Flow Logs, endpoints, and IAM conditions, with CLI examples for production.

10 min read•Jul 2026
Event-Driven Architecture on AWS Explained

Event-Driven Architecture on AWS Explained

Build event-driven systems on AWS with SQS, SNS, EventBridge and Kinesis: fan-out, DLQs, idempotent consumers and queue-based scaling.

11 min read•Jul 2026
S3 vs RDS vs DynamoDB: Choosing AWS Storage

S3 vs RDS vs DynamoDB: Choosing AWS Storage

Choosing S3, RDS, or DynamoDB wrong costs you in performance, cost, and scalability. Here is a practical decision guide based on your actual access patterns.

5 min read•Jul 2026
AWS Cost Optimisation: 8 Actions That Cut Bills

AWS Cost Optimisation: 8 Actions That Cut Bills

Cut your AWS bill without re-architecting: eight ordered steps from anomaly alerts and tagging to rightsizing, VPC endpoints, Savings Plans and Spot.

11 min read•Jul 2026
EC2 vs Lambda vs Fargate: Choosing AWS Compute

EC2 vs Lambda vs Fargate: Choosing AWS Compute

Choose between EC2, Lambda and Fargate using traffic shape, state and runtime limits, with worked cost break-evens instead of rules of thumb.

11 min read•Jul 2026

Explore More in AWS Storage and Databases

All 6 Topics

Frequently Asked Questions

Is Implementing ElastiCache Redis Caching Patterns free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Implementing ElastiCache Redis Caching Patterns topic cover?

Implement ElastiCache Redis with Lazy Loading, Write-Through, and Session Store patterns to cut database load and serve repeat reads in microseconds.

Found a mistake, an outdated step or a broken link?