9.6 KiB
AWS ElastiCache for Redis Setup Guide
This guide walks you through setting up Redis on AWS using ElastiCache, which is AWS's managed Redis service.
Prerequisites
- AWS Account with appropriate permissions
- AWS CLI configured (optional, but helpful)
- Your application running on AWS (EC2, ECS, Lambda, etc.)
- VPC (Virtual Private Cloud) set up in AWS
Step-by-Step Setup
Step 1: Create a VPC and Subnet Group (if not already done)
ElastiCache requires a VPC. If you don't have one:
-
Go to AWS Console → VPC Dashboard
-
Create VPC (if needed):
- Click "Create VPC"
- Choose "VPC and more"
- Name:
your-app-vpc - IPv4 CIDR:
10.0.0.0/16 - Create public and private subnets
- Enable DNS hostnames
-
Create Subnet Group for ElastiCache:
- Go to ElastiCache → Subnet Groups
- Click "Create subnet group"
- Name:
redis-subnet-group - VPC: Select your VPC
- Availability Zones: Select at least 2 zones
- Subnets: Select private subnets (recommended for security)
Step 2: Create Security Group
- Go to EC2 → Security Groups
- Create Security Group:
- Name:
redis-security-group - Description:
Security group for ElastiCache Redis - VPC: Select your VPC
- Inbound Rules: Add rule
- Type:
Custom TCP - Port:
6379 - Source: Select your application's security group (or specific IP/CIDR)
- Type:
- Outbound Rules: Default (All traffic)
- Name:
Step 3: Create ElastiCache Redis Cluster
-
Go to AWS Console → ElastiCache
-
Click "Create" → Choose "Redis"
-
Configure Cluster Settings:
Cluster Settings:
- Name:
your-app-redis(must be unique) - Description:
Redis cache for rate limiting and OTP - Engine version: Latest Redis 7.x (recommended)
- Port:
6379(default) - Parameter group:
default.redis7(or create custom)
Node Type:
- Node type: Choose based on your needs:
cache.t3.micro- Free tier eligible, 0.5 GB RAMcache.t3.small- 1.37 GB RAM (~$15/month)cache.t3.medium- 3.09 GB RAM (~$30/month)- For production:
cache.t4g.mediumor larger
Network & Security:
- VPC: Select your VPC
- Subnet group: Select the subnet group created in Step 1
- Availability Zone(s):
- Single AZ (cheaper, less resilient)
- Multi-AZ (recommended for production, automatic failover)
- Security groups: Select
redis-security-groupcreated in Step 2
Backup & Maintenance:
- Automatic backups: Enable (recommended)
- Backup retention: 1-7 days (your choice)
- Backup window: Choose low-traffic time
- Maintenance window: Choose low-traffic time
Encryption:
- Encryption in-transit: Enable (recommended for production)
- Encryption at-rest: Enable (recommended for production)
- Auth token:
- Enable: Recommended for production
- Auth token: Generate a strong password (save this!)
- Name:
-
Review and Create
- Review all settings
- Click "Create"
Step 4: Wait for Cluster Creation
- ElastiCache takes 5-15 minutes to create
- Status will change from "creating" to "available"
- Note the Primary Endpoint (e.g.,
your-app-redis.xxxxx.cache.amazonaws.com:6379)
Step 5: Configure Your Application
Update your .env file with the ElastiCache endpoint:
Option A: Without Auth Token (Not Recommended for Production)
REDIS_URL=redis://your-app-redis.xxxxx.cache.amazonaws.com:6379
Option B: With Auth Token (Recommended)
REDIS_URL=redis://:your-auth-token@your-app-redis.xxxxx.cache.amazonaws.com:6379
Option C: Using Separate Variables
REDIS_HOST=your-app-redis.xxxxx.cache.amazonaws.com
REDIS_PORT=6379
REDIS_PASSWORD=your-auth-token
Option D: With SSL/TLS (If Encryption in-transit is enabled)
REDIS_URL=rediss://:your-auth-token@your-app-redis.xxxxx.cache.amazonaws.com:6379
Note: rediss:// (with double 's') indicates SSL/TLS connection.
Step 6: Update Security Group (If Needed)
If your application can't connect:
-
Check Security Group Rules:
- Ensure your application's security group can access port 6379
- Or add your application's security group ID to Redis security group inbound rules
-
Test Connection (from EC2 instance):
# Install redis-cli sudo yum install redis -y # Amazon Linux # or sudo apt-get install redis-tools -y # Ubuntu # Test connection redis-cli -h your-app-redis.xxxxx.cache.amazonaws.com -p 6379 -a your-auth-token ping # Should return: PONG
Step 7: Verify Connection
- Restart your application
- Check logs for:
✅ Redis Client: Ready - If you see errors, check:
- Security group rules
- VPC routing
- Auth token is correct
- Endpoint URL is correct
Cost Optimization
Free Tier
- AWS Free Tier includes 750 hours/month of
cache.t2.microorcache.t3.micro - Perfect for development/testing
Cost-Saving Tips
- Use smaller instance types for development
- Disable automatic backups for non-production
- Use single-AZ for development (multi-AZ costs more)
- Stop/Delete clusters when not in use
- Reserved Instances for production (save up to 55%)
High Availability Setup
Multi-AZ Configuration
- Enable Multi-AZ during cluster creation
- Automatic failover if primary node fails
- Read Replicas for read scaling:
- Go to ElastiCache → Your cluster → Actions → Add replica
- Choose availability zones
- Replicas can be promoted to primary if needed
Cluster Mode (Redis Cluster)
For larger scale:
- Enable Cluster Mode during creation
- Multiple shards for horizontal scaling
- Automatic sharding across nodes
Security Best Practices
- ✅ Enable Auth Token (password authentication)
- ✅ Enable Encryption in-transit (SSL/TLS)
- ✅ Enable Encryption at-rest
- ✅ Use Private Subnets (not public subnets)
- ✅ Restrict Security Groups (only allow your application)
- ✅ Use VPC Endpoints (if accessing from Lambda)
- ✅ Regular Security Updates (AWS handles this)
Monitoring and Alerts
CloudWatch Metrics
- Go to ElastiCache → Your Cluster → Monitoring
- Key Metrics to Monitor:
CPUUtilization- Should be < 80%MemoryUtilization- Should be < 80%NetworkBytesIn/Out- Network trafficCacheHits/CacheMisses- Cache performanceEvictions- Memory pressure indicator
Set Up Alarms
- Go to CloudWatch → Alarms
- Create alarms for:
- High CPU (> 80%)
- High Memory (> 80%)
- Connection failures
- Failover events
Troubleshooting
Connection Timeout
Problem: Application can't connect to Redis
Solutions:
- Check security group allows traffic from your application
- Verify VPC routing tables
- Ensure both are in same VPC
- Check if endpoint URL is correct
- Verify auth token is correct
Authentication Failed
Problem: NOAUTH Authentication required or WRONGPASS
Solutions:
- Verify auth token in
.envmatches ElastiCache auth token - Check if auth token is enabled in ElastiCache
- Use format:
redis://:password@host:port
High Memory Usage
Problem: Memory utilization > 90%
Solutions:
- Upgrade to larger node type
- Enable eviction policy (already enabled by default)
- Review what data is stored in Redis
- Set TTL on keys (your code already does this)
Slow Performance
Problem: High latency or slow responses
Solutions:
- Check CPU utilization
- Enable read replicas for read-heavy workloads
- Upgrade node type
- Check network latency (use same region as application)
- Monitor
CacheHitsvsCacheMissesratio
Alternative: AWS MemoryDB for Redis
For even higher durability (data persisted to disk):
- Go to MemoryDB (separate service)
- Similar setup to ElastiCache
- Better durability (multi-AZ with automatic failover)
- Higher cost than ElastiCache
- Use when: Data persistence is critical
Alternative: Self-Hosted on EC2
If you prefer more control:
- Launch EC2 instance (Amazon Linux or Ubuntu)
- Install Redis:
sudo yum install redis -y # Amazon Linux sudo systemctl start redis sudo systemctl enable redis - Configure security group (port 6379)
- Set up Redis password in
/etc/redis.conf - Use EC2 private IP in your
.env
Note: You'll need to manage backups, updates, and scaling yourself.
Quick Reference
Get Endpoint URL
aws elasticache describe-cache-clusters \
--cache-cluster-id your-app-redis \
--show-cache-node-info \
--query 'CacheClusters[0].CacheNodes[0].Endpoint.Address'
Get Auth Token
- Go to ElastiCache → Your Cluster → Configuration
- Auth token is shown (or set during creation)
Update Auth Token
- Go to ElastiCache → Your Cluster
- Actions → Modify
- Change auth token
- Apply immediately or schedule
Delete Cluster
- Go to ElastiCache → Your Cluster
- Actions → Delete
- Confirm deletion
- Warning: This deletes all data!
Next Steps
- ✅ Create ElastiCache Redis cluster
- ✅ Update
.envwith endpoint and auth token - ✅ Update security groups
- ✅ Restart application
- ✅ Verify connection:
✅ Redis Client: Ready - ✅ Set up CloudWatch alarms
- ✅ Monitor performance
Support
- AWS Documentation: https://docs.aws.amazon.com/elasticache/
- AWS Support: AWS Console → Support Center
- Pricing Calculator: https://calculator.aws/