ElastiCache
Overview
Amazon ElastiCache is a managed in-memory data store and cache that supports Redis OSS / Valkey and Memcached. Because data lives in RAM, reads and writes complete in microseconds, much faster than disk-based databases. ElastiCache sits in front of a database such as RDS or DynamoDB to absorb repeated reads, or acts as a primary store for session data, leaderboards and real-time counters.
The main benefit of caching is two-fold: lower latency for users and lower load on the backing database, which postpones expensive database scaling. The main design challenge is cache coherence: keeping cached data fresh through strategies such as lazy loading, write-through and TTLs.
The exam focuses on choosing between Redis and Memcached, understanding caching strategies, and recognising when ElastiCache is the answer: repeated reads, session sharing for stateless web servers, and real-time leaderboards.
Key Concepts
- Two engines: Redis OSS / Valkey (rich data structures, persistence, replication, Multi-AZ) and Memcached (simple, multithreaded, no persistence).
- Redis supports strings, hashes, lists, sets, sorted sets, pub/sub, geospatial data, transactions, Lua scripting and snapshots/AOF persistence.
- Redis high availability: replication groups with up to 5 read replicas per shard, Multi-AZ with automatic failover, cluster mode sharding across up to 500 nodes.
- Memcached: multi-node horizontal sharding, multithreaded, no replication, no persistence, no failover - data is lost if a node fails.
- Lazy loading (cache-aside) loads data on a miss; write-through updates the cache on every write; add a TTL to limit staleness and memory growth.
- Security: runs in your VPC; security groups, encryption at rest and in transit, Redis AUTH/RBAC and IAM authentication.
- Global Datastore gives cross-Region replication for Redis; ElastiCache Serverless removes node management and scales automatically.
- Common patterns: database query caching, session store, leaderboards, rate limiting, pub/sub messaging, and real-time analytics.
Detailed Notes
Redis vs Memcached
| Feature | Redis OSS / Valkey | Memcached |
|---|---|---|
| Data structures | Rich (lists, sets, sorted sets, hashes, streams) | Simple key-value strings |
| Replication / Multi-AZ failover | Yes (up to 5 replicas per shard) | No |
| Persistence / backups | Yes (snapshots, AOF) | No |
| Scaling | Cluster mode (shards) and replicas | Add/remove nodes (multithreaded) |
| Pub/Sub, transactions | Yes | No |
| Encryption and auth | At rest, in transit, AUTH/RBAC/IAM | In transit and SASL; at rest limited |
| Best for | HA caches, session stores, leaderboards, queues | Simple, disposable cache; multi-core scale |
Rule: if the scenario needs persistence, high availability, replication, sorting or complex data types, answer Redis. If it needs a simple, multithreaded cache and nothing else, Memcached is acceptable.
Caching strategies
| Strategy | How it works | Pros | Cons |
|---|---|---|---|
| Lazy loading (cache-aside) | App checks cache; on miss reads DB and writes cache | Only requested data cached; node failure is survivable | Miss penalty (3 trips); stale data possible |
| Write-through | App writes to cache and DB on every update | Cache is always fresh; no miss penalty on reads | Write penalty; caches unread data (use TTL) |
| TTL | Expire keys after a set time | Bounds staleness and memory | Needs tuning |
Combine lazy loading with write-through and a TTL for a balanced design.
import json, redis
cache = redis.Redis(host="my-cache.xxxxxx.use1.cache.amazonaws.com", port=6379, ssl=True)
def get_product(product_id):
key = f"product:{product_id}"
cached = cache.get(key)
if cached: # cache hit
return json.loads(cached)
product = db_query(product_id) # cache miss -> database
cache.setex(key, 300, json.dumps(product)) # lazy load, 5 minute TTL
return product
Redis cluster architecture
- Cluster mode disabled: one shard (primary + up to 5 replicas) that scales reads, with Multi-AZ failover typically under a minute.
- Cluster mode enabled: data is partitioned into shards (hash slots), each with replicas, to scale writes and memory horizontally; you can online-resize (reshard).
- Global Datastore replicates a Redis cluster to up to 2 other Regions for DR and local reads.
- ElastiCache Serverless needs no capacity planning: it scales memory and compute automatically.
Security and operations
- Deploy in private subnets of a cache subnet group; allow only the app's security group on port 6379 (Redis) or 11211 (Memcached).
- Enable in-transit encryption (TLS) and at-rest encryption (KMS); Redis supports AUTH tokens, RBAC users and IAM authentication.
- Monitor CacheHitRate, Evictions, CurrConnections, CPUUtilization, EngineCPUUtilization and ReplicationLag in CloudWatch. High evictions mean the cache is too small.
- Use reserved nodes for steady-state savings.
ElastiCache vs DAX vs MemoryDB
| ElastiCache | DAX | MemoryDB for Redis | |
|---|---|---|---|
| Purpose | General cache for any source | DynamoDB-only cache | Durable primary database, Redis-compatible |
| Durability | Optional snapshots | Cache only | Multi-AZ transaction log, durable |
| Code change | Yes (cache logic) | None (same API) | Use as the DB |
Real World Example
Scenario — a ticketing website suffers when a popular concert goes on sale.
Product pages and seat-availability queries hammer an RDS PostgreSQL database, response times exceed 3 seconds and users log in repeatedly because sessions were stored in each web server's memory.
The team adds an ElastiCache for Redis replication group in Multi-AZ mode. Product and event details use lazy loading with a 60-second TTL, cutting database reads by 90%. Seat holds use Redis atomic counters and sorted sets for a real-time waiting-room queue. Session data moves to Redis so any web server can serve any user, which lets the Auto Scaling group scale freely and survive instance replacement.
Page latency drops from seconds to under 50 ms, the database instance can be downsized, and an AZ failure triggers an automatic Redis failover without logging users out.
Architecture Diagram
The application checks Redis first and falls back to the database on a cache miss.
- 1A request reaches a stateless application server through the load balancer.
- 2The application looks the key up in Redis; on a cache hit it returns the data in microseconds.
- 3On a miss, the application queries the database, then writes the result into Redis with a TTL.
- 4Sessions are stored in Redis so any server can serve any user; a replica in another AZ takes over on failure.
Best Practices
- ✓Choose Redis (or Valkey) when you need replication, persistence, rich data types or Multi-AZ failover; use Memcached only for simple, disposable caches.
- ✓Always set TTLs and combine lazy loading with write-through to balance freshness and cost.
- ✓Deploy Multi-AZ replication groups with automatic failover and spread replicas across AZs for production.
- ✓Use cluster mode to scale memory and writes horizontally, and read replicas to scale reads.
- ✓Enable encryption in transit and at rest, require AUTH/RBAC or IAM, and restrict access by security group on private subnets.
- ✓Monitor CacheHitRate, Evictions and memory; resize or reshard when hit rate drops or evictions rise.
- ✓Design the application so the cache is optional: it must still work (more slowly) if the cache is cold or unavailable.
- ✓Store session state in Redis (or DynamoDB) rather than on web servers so tiers remain stateless and scalable.
Common Interview Questions
Exam Tips
SAA-C03 focus
- "Reduce database load for repeated reads" or "improve read performance" -> ElastiCache (put it in front of RDS/DynamoDB).
- "Multi-AZ, replication, persistence, backups, leaderboards (sorted sets), pub/sub" -> Redis. "Simple, multithreaded, horizontal scaling" -> Memcached.
- Lazy loading = cache on miss (stale risk); write-through = fresh data (write penalty). Both benefit from TTL.
- "Stateless web servers sharing session state" -> ElastiCache Redis (or DynamoDB).
- "Microsecond cache with no code changes for DynamoDB" -> DAX, not ElastiCache.
- "Redis-compatible durable primary database" -> MemoryDB, not ElastiCache.
- Redis: up to 5 read replicas per shard; cluster mode for scaling writes; Global Datastore for cross-Region.
- Ports: 6379 Redis, 11211 Memcached; ElastiCache cannot be accessed over the public internet, only inside a VPC.
Chapter quiz
Databases · 5 questions
1.A company's production RDS MySQL database must remain available if an Availability Zone fails, with automatic failover and no application changes. Which solution is the MOST appropriate?
2.A global application on Amazon Aurora MySQL needs low-latency reads in two other Regions and the ability to recover from a Regional outage within about a minute. What should the solutions architect use?
3.A DynamoDB table receives 200 strongly consistent reads per second for items that are 6 KB each. How many read capacity units (RCUs) must be provisioned?
4.A gaming application stores leaderboards and session data and must keep working during an AZ failure, with data persisted and replicated across nodes. Which ElastiCache option is MOST suitable?
5.Hundreds of Lambda functions that connect to an Amazon RDS for PostgreSQL database are exhausting the database's connection limit during traffic spikes. What is the BEST way to fix this with minimal code change?
0 of 5 answered
Finished this lesson?
0 of 64 lessons done · 0% of the course

