Caching with ElastiCache and DAX
Overview
A cache keeps copies of frequently read data in fast memory so the database and application do less work. Caching improves latency, protects the backend during spikes and lets you scale reads without scaling the database. On SOA-C03 the task statement is to implement caching with services such as Amazon CloudFront and Amazon ElastiCache to enhance dynamic scalability.
Imagine a restaurant that pre-cuts popular ingredients and keeps them next to the chef. Every order that needs onions is faster, and the pantry (database) is visited less. The risk is stale ingredients, so you decide how long they may sit (TTL) and when to throw them out (eviction).
The operator's questions are: which engine (Valkey/Redis OSS or Memcached, or DAX for DynamoDB), how to make it highly available, how to size and scale it, and which metrics prove it works (cache hit rate, evictions, memory, CPU).
Key Concepts
- ElastiCache engines: Valkey / Redis OSS (rich data types, replication, persistence, Multi-AZ, Pub/Sub) and Memcached (simple, multi-threaded, no replication or persistence).
- Redis cluster mode enabled shards data across node groups for write and memory scale; cluster mode disabled has one shard with up to 5 read replicas.
- Multi-AZ with automatic failover promotes a replica when the primary fails; use the reader endpoint to spread reads.
- Caching strategies: lazy loading (cache-aside, can serve stale data), write-through (always fresh, more writes), plus TTL to bound staleness.
- DAX is a write-through, API-compatible in-memory cache for DynamoDB reads only, delivering microsecond latency without app redesign beyond switching the client.
- Key metrics: CacheHits, CacheMisses, Evictions, CurrConnections, EngineCPUUtilization, DatabaseMemoryUsagePercentage, ReplicationLag.
- ElastiCache Serverless scales capacity automatically and removes node sizing; node-based clusters let you pick instance families and reserved nodes.
- Secure with VPC subnets, security groups, encryption in transit (TLS), at rest (KMS) and Redis AUTH / IAM authentication.
Detailed Notes
Choosing a cache
| Need | Best fit | Why |
|---|---|---|
| Cache for DynamoDB reads, no code redesign | DAX | Item and query cache, microsecond reads |
| Session store, leaderboards, pub/sub, persistence | ElastiCache Valkey / Redis OSS | Data structures, replication, snapshots |
| Simple object cache, multi-threaded scale-out | ElastiCache Memcached | Easy horizontal sharding, no HA |
| Cache static or cacheable HTTP content at the edge | CloudFront | Offloads origin, lower global latency |
| Unpredictable traffic, minimal capacity planning | ElastiCache Serverless | Automatic scaling |
Redis / Valkey topology
| Feature | Cluster mode disabled | Cluster mode enabled |
|---|---|---|
| Shards | 1 | Up to 500 node groups |
| Replicas | Up to 5 per shard | Up to 5 per shard |
| Scaling writes | Scale up (bigger node) | Add shards (online resharding) |
| Endpoints | Primary + reader | Single configuration endpoint |
aws elasticache create-replication-group --replication-group-id sessions \
--replication-group-description "session cache" --engine valkey \
--cache-node-type cache.r7g.large --num-node-groups 2 --replicas-per-node-group 2 \
--automatic-failover-enabled --multi-az-enabled \
--transit-encryption-enabled --at-rest-encryption-enabled \
--cache-subnet-group-name private-cache --security-group-ids sg-0abc
Caching patterns
# Lazy loading (cache-aside)
def get_user(uid):
val = cache.get(f"user:{uid}")
if val is None: # cache miss
val = db.query(uid) # read from the database
cache.setex(f"user:{uid}", 300, val) # TTL 5 minutes
return val
- Lazy loading only caches what is requested; a cold cache causes a burst of misses (the thundering herd). Pre-warm or add jitter to TTLs.
- Write-through updates the cache on every write; no stale data but cache can hold unused items. Combine both with TTL.
Metrics and tuning
| Observation | Meaning | Action |
|---|---|---|
Low hit ratio (CacheHits / (CacheHits + CacheMisses)) | Keys not reused, TTL too short or cache too small | Review key design, raise TTL or size |
| Rising Evictions | Memory full, items removed before TTL | Scale up or add shards |
| High EngineCPUUtilization | Single-threaded Redis engine saturated | Add shards or read replicas, optimise commands |
| SwapUsage high (Memcached) | Memory pressure | Larger node |
| ReplicationLag increasing | Replica cannot keep up | Larger node, reduce write rate |
Scaling operations
- Vertical: modify the node type (brief failover for Redis replication groups).
- Horizontal reads: add replicas. Horizontal writes: add shards in cluster mode (online resharding).
- Auto Scaling for ElastiCache (Redis) adjusts shards or replicas by target tracking on
ElastiCachePrimaryEngineCPUUtilizationand similar metrics. - Use reserved nodes for steady workloads to reduce cost.
DAX specifics
aws dax create-cluster --cluster-name orders-dax --node-type dax.r5.large --replication-factor 3 \
--iam-role-arn arn:aws:iam::111122223333:role/DAXRole --subnet-group-name private-dax
DAX caches GetItem, BatchGetItem, Query and Scan results. It is write-through for writes sent through DAX, and it does not help strongly consistent reads (these pass through to DynamoDB). Item cache TTL defaults to 5 minutes. For heavy repeated reads of the same keys DAX can cut read capacity consumption dramatically.
Real World Example
Scenario – flash-sale database meltdown. An e-commerce site's product-detail API hits Amazon RDS for MySQL with the same few thousand rows. During a sale CPU on the database reaches 95% and latency climbs.
The team adds an ElastiCache for Redis (Multi-AZ) cluster using lazy loading with a 60-second TTL for product data and write-through for inventory counters. Cache hit ratio reaches 92%, database CPU falls below 30%, and p99 latency drops from 450 ms to 40 ms. An alarm on Evictions and a dashboard widget for hit ratio ensure the cache is sized correctly before the next event. A separate DynamoDB-backed recommendation service is fronted by DAX with no query changes.
Architecture Diagram
- 1The application checks the cache for the key.
- 2On a hit the value is returned in microseconds to milliseconds.
- 3On a miss the application reads the database.
- 4The result is written to the cache with a TTL for later requests.
- 5CloudWatch tracks hit ratio, evictions, CPU and memory to guide scaling.
Best Practices
- ✓Deploy Redis/Valkey with Multi-AZ and automatic failover and connect with the primary and reader endpoints, not node endpoints.
- ✓Set a TTL with jitter on every key to bound staleness and avoid synchronized expiry.
- ✓Alarm on Evictions, EngineCPUUtilization and DatabaseMemoryUsagePercentage, and track the hit ratio on a dashboard.
- ✓Enable encryption in transit and at rest and place caches in private subnets with tight security groups.
- ✓Use DAX for DynamoDB and CloudFront for HTTP content instead of building custom caches.
Common Interview Questions
Exam Tips
SOA-C03 focus
- Reduce database read load / speed up repeated reads -> ElastiCache; DynamoDB microsecond reads -> DAX.
- Need replication, persistence, failover -> Redis/Valkey; simple multi-threaded cache -> Memcached.
- Scale write capacity of Redis -> add shards (cluster mode enabled); scale reads -> add replicas.
- Static content or API responses cached close to users -> CloudFront, not ElastiCache.
Finished this lesson?
0 of 46 lessons done · 0% of the course

