Caching Strategies: Lazy Loading and Write-Through
Implement lazy loading to populate the cache on misses and write-through to keep the cache consistent with every database write.
Why Caching Strategies Matter
Inserting a cache between your application and database requires a caching strategy — a set of rules that determine when data is put into the cache, when it is read from the cache, and when it is evicted. Choosing the wrong strategy leads to either stale data (cache returns outdated values), cold cache misses (cache is empty and every request hits the database), or cache stampede (many simultaneous requests for the same missing key all hit the database simultaneously). The two foundational strategies are lazy loading and write-through.
Lazy Loading (Cache-Aside): How It Works
Lazy loading (also called cache-aside) is the most common caching pattern. The application checks the cache first. On a cache hit, data is returned directly from the cache — fast path. On a cache miss, the application fetches data from the database, writes the result into the cache with a TTL, and returns it to the caller. The cache is only populated with data that is actually requested — hence 'lazy'. The next request for the same key will find it in the cache.
# Lazy loading pattern (Python with redis-py)
def get_user(user_id, redis_client, db):
cache_key = f'user:{user_id}'
# 1. Check cache
cached = redis_client.get(cache_key)
if cached:
return json.loads(cached) # Cache HIT
# 2. Cache MISS: fetch from DB
user = db.query('SELECT * FROM users WHERE id = %s', user_id)
# 3. Populate cache with TTL of 300 seconds
redis_client.setex(cache_key, 300, json.dumps(user))
return userAll lessons in this course
- Redis vs Memcached: Choosing the Right Engine
- ElastiCache Redis Replication Groups and Cluster Mode
- Caching Strategies: Lazy Loading and Write-Through
- Session Storage and Leaderboard Patterns