Cache patterns
| Pattern | How | Good for | Catch |
|---|---|---|---|
| Cache-aside (lazy) | App reads cache; on miss reads DB and fills cache | Default for most reads | First read slow; stale until TTL/invalidate |
| Write-through | Write cache + DB together | Read-after-write freshness | Slower writes; caches data never read |
| Write-back | Write cache; flush to DB later | Write-heavy counters | Data loss if cache dies |
| Read-through | Cache library loads from DB itself | Same as aside, cleaner code | Coupling to cache lib |
Cache-aside
def get_user(id):
u = redis.get(f'user:{id}')
if u: return u # hit
u = db.query('SELECT ... WHERE id=%s', id)
redis.set(f'user:{id}', u, ex=300) # TTL 5 min
return u
def update_user(id, data):
db.update(id, data)
redis.delete(f'user:{id}') # invalidate, don't update