3 · Caching · Cache patterns

Cache patterns

PatternHowGood forCatch
Cache-aside (lazy)App reads cache; on miss reads DB and fills cacheDefault for most readsFirst read slow; stale until TTL/invalidate
Write-throughWrite cache + DB togetherRead-after-write freshnessSlower writes; caches data never read
Write-backWrite cache; flush to DB laterWrite-heavy countersData loss if cache dies
Read-throughCache library loads from DB itselfSame as aside, cleaner codeCoupling 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