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.
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 |
RememberElastiCache 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.
import jsonimport 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 menuThe 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:
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 menuPattern 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.
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))TipCombine 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.
import redisfrom flask import Flask, redirect, render_template, request, sessionfrom 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 TTLSession(app) def login(): session["user_id"] = authenticate_user(request.form) return redirect("/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.
export AWS_REGION=ap-south-1export VPC_ID=vpc-0abc1234567890defexport APP_SG=sg-0aaa1111bbbb2222cexport SUBNET_A=subnet-0aaa1111bbbb2222cexport SUBNET_B=subnet-0ddd3333eeee4444f- Create a security group that only the application security group can reach on port 6379:
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- Create a subnet group from two private subnets in different AZs:
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- Create a Multi-AZ replication group with one primary and one replica, with encryption at rest and in transit, then wait for it:
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- Fetch the primary endpoint:
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- 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 isredis6and the client isredis6-cli:
sudo dnf install -y redis6redis6-cli -h $REDIS_HOST -p 6379 --tls PING- Try keys and TTLs inside the client:
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 30redis6-cli -h $REDIS_HOST --tls TTL session:abc123- Simulate Lazy Loading by hand: a miss, a "database read", a store, then a hit:
redis6-cli -h $REDIS_HOST --tls GET product:P001 # (nil) = missredis6-cli -h $REDIS_HOST --tls SET product:P001 '{"name":"Biryani","price":250}' EX 300redis6-cli -h $REDIS_HOST --tls GET product:P001 # now a hit- Read the hit and miss counters. The ratio of hits to total lookups is your cache hit rate:
redis6-cli -h $REDIS_HOST --tls INFO stats | grep -E "keyspace_hits|keyspace_misses"- Test failover. The replica is promoted, and the same endpoint keeps working after DNS updates:
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- Clean up. Delete the replication group first, because the subnet group and security group cannot be removed while it exists:
aws elasticache delete-replication-group \ --replication-group-id mumbai-prod-redis --region $AWS_REGIONaws 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_REGIONaws ec2 delete-security-group --group-id $REDIS_SG --region $AWS_REGIONProduction Best Practices & Common Pitfalls
Common MistakeRunning 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 MistakeAssuming 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.
SecurityNever 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-policysuits your use, for exampleallkeys-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 useSCANinstead. - Use Sorted Sets for leaderboards.
ZADDandZRANGErank 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 |