Skip to content

Caching

Mid / Senior

Cache strategies, invalidation, and the failure modes that bite in production.

2 questions · answers hidden

  1. 01Compare cache-aside, read-through, and write-through.
    • Cache-aside (lazy loading): the application checks the cache, and on a miss loads from the DB and populates the cache. Simple and resilient (a cache outage just means more DB load), but the first request for any key is always slow, and stale data is possible until TTL expiry.
    • Read-through: the cache library itself loads from the backing store on a miss. Same behaviour as cache-aside but the logic lives in the cache layer, not scattered through the app.
    • Write-through: every write goes to the cache and the DB synchronously. Reads are always warm and consistent, but writes pay extra latency and you cache data that may never be read.

    Write-behind (async flush to the DB) improves write latency but risks data loss on cache failure.

    #q-compare-cache-aside-read-through-and-write-through
  2. 02What is a cache stampede and how do you prevent it?

    When a hot key expires, many concurrent requests miss simultaneously and all hit the database to recompute the same value, sometimes overwhelming it.

    Mitigations:

    • Locking / single-flight: the first miss acquires a lock and recomputes; others wait for the result.
    • Early / probabilistic expiration: refresh the value slightly before the TTL, so one request recomputes while the rest still get a cache hit.
    • Stale-while-revalidate: serve the expired value and refresh in the background.
    #q-what-is-a-cache-stampede-and-how-do-you-prevent-it