Master ElastiCache Redis vs Memcached selection and caching strategies (lazy loading, write-through). Integrate caching into application architecture.
ElastiCache — In-Memory Caching
ElastiCache provides managed Redis and Memcached caching layers. Adding a cache between your application and database can reduce database load by 90%+ and improve response times from milliseconds to microseconds.
Teacher Note: Without cache: every page view queries the database. 10,000 users see the homepage = 10,000 identical database queries. With cache: first user queries DB, result stored in cache for 60 seconds. Next 9,999 users get the result from cache in 1ms — database never queried again.
Redis vs Memcached
| Feature | Redis | Memcached |
|---|
| Data structures | Rich: strings, lists, sets, sorted sets, hashes, streams | Simple: strings only |
| Persistence | Yes — RDB snapshots and AOF logs | No — data lost on restart |
| Replication | Yes — Multi-AZ, read replicas | No — each node is standalone |
| Pub/Sub | Yes — message publishing and subscription | No |
| Clustering | Yes — horizontal sharding | Yes — simple horizontal scaling |
| Lua scripting | Yes | No |
| Use cases | Sessions, leaderboards, pub/sub, queues, complex caching | Simple distributed caching, session storage without failover needs |
Caching Strategies
| Strategy | How It Works | Pros | Cons |
|---|
| Lazy Loading (Cache-Aside) | App checks cache first. Miss = query DB, then store in cache | Only caches what is requested | First request is slow (cache miss) |
| Write-Through | Write to cache AND database simultaneously | Cache always up-to-date | More writes, potential waste on rarely-read data |
| Write-Behind | Write to cache only, sync DB asynchronously | Fastest writes | Risk of data loss if cache fails before DB write |
# Python - Lazy Loading pattern
import redis
cache = redis.Redis(host='my-cluster.cache.amazonaws.com')
def get_user(user_id):
# Check cache first
cached = cache.get(f'user:{user_id}')
if cached:
return json.loads(cached) # Cache hit - fast!
# Cache miss - query database
user = db.query('SELECT * FROM users WHERE id = %s', user_id)
# Store in cache for 5 minutes
cache.setex(f'user:{user_id}', 300, json.dumps(user))
return user
Exam Tip: Redis Sorted Sets are perfect for leaderboards — O(log N) operations for adding scores and retrieving top-N players. ElastiCache Redis also supports Pub/Sub for real-time features like notifications and live dashboards. Choose Redis for almost all new workloads — Memcached is only preferred for extremely simple caching with maximum horizontal scaling.