Caching with ElastiCache
Use managed Redis-compatible caches to cut database load and latency, with sensible caching patterns and eviction.
Intermediate · about 3 hours · difficulty 3/5
Learn first: Relational Databases with RDS and Aurora
A cache keeps frequently read data in memory so your app does not hit the database for every request. Amazon ElastiCache runs Valkey, Redis OSS and Memcached for you. Azure Cache for Redis and Google Memorystore are the equivalents.
When to cache
- Read-heavy data that changes slowly: product catalogues, course listings, configuration.
- Expensive computed results: leaderboards, aggregated dashboards.
- Session storage for stateless app servers behind an Auto Scaling group.
- Rate limiting and simple queues using Redis data structures.
Caching patterns
- Cache-aside (lazy loading): check cache, on miss read the database and populate the cache. Simple and common.
- Write-through: update the cache whenever you write the database. Fresher data, more writes.
- Always set a TTL so stale data eventually expires.
ElastiCache options
- Serverless ElastiCache scales automatically and is simplest to start with.
- Node-based clusters with replication groups and Multi-AZ failover for predictable workloads.
- Cluster mode shards data across nodes for large datasets.
- Encryption in transit and at rest, and AUTH or IAM authentication.
Pitfalls
- Caching without TTLs and serving stale prices for days.
- A thundering herd when a hot key expires and thousands of requests hit the database at once.
- Treating the cache as the source of truth; it can be evicted at any time.
You are ready to move on when you can add cache-aside caching to an API and measure the drop in database queries and response time.
Key concepts
- Cache-aside pattern
- Write-through pattern
- TTLs and eviction
- Valkey and Redis OSS
- Memcached
- ElastiCache Serverless
- Session storage
Mini project
Run Redis locally with Docker, add cache-aside to a small API that reads from PostgreSQL, and log hit and miss rates. Optionally repeat with a free-tier eligible cache.t3.micro or t4g.micro ElastiCache node for an hour, then delete it immediately.
Check yourself
What is the thundering herd problem, and name one way to prevent it.
Free resources
- Amazon ElastiCache documentation (AWS)
- Caching best practices (AWS)
- Redis documentation (Redis)