What are the common caching strategies?
A small number of patterns that differ in who writes to the cache and when — and choosing the wrong one for your consistency requirements is where cache bugs come from.
The read patterns:
Cache-aside, the most common. The application checks the cache; on a miss it reads the database, stores the result, and returns it. Simple, and the application owns the logic. Its weakness is the thundering herd: when a popular key expires, many requests miss simultaneously and all hit the database.
Read-through, where the cache itself fetches on a miss. Cleaner application code, less control.
The write patterns:
Write-through. Writes go to the cache and the database synchronously. The cache is always consistent; writes are slower.
Write-behind, writing to the cache and flushing to the database asynchronously. Fast writes, and data loss is possible if the cache fails before flushing.
Write-around, writing directly to the database and letting the cache populate on the next read. Avoids polluting the cache with data nobody reads, at the cost of one slow read after each write.
Invalidation is the hard part. The options are: time-based expiry, which is simple and serves stale data for up to the TTL; explicit invalidation on write, which is accurate and easy to miss somewhere; versioned keys, embedding a version in the key so old entries become unreachable and expire naturally — robust and frequently the best answer; and eviction policies when memory fills, usually least-recently-used.
The failure modes worth knowing by name:
Stampede, addressed by locking so one request refreshes while others serve stale data, or by refreshing before expiry.
Cache penetration, where requests for keys that do not exist bypass the cache every time — fixed by caching the negative result.
Stale reads after a write, which is the consistency question you must answer deliberately.
The first question to ask: how stale can this data be? Everything else follows from that answer, and a system that cannot tolerate any staleness frequently should not be cached at all.