Distributed Caching: Policies, Eviction & Invalidation
Saving repeated, expensive work inside the application itself — and the policies that decide what stays in memory and what gets evicted.
Intermediate
| Good fit for caching | Poor fit for caching |
|---|---|
| Expensive-to-compute or expensive-to-fetch data requested repeatedly (top restaurants, a user's session) | Data that's write-heavy and rarely re-read (an audit log) |
| Data that tolerates some staleness (restaurant ratings, view counts) | Data with strict consistency requirements (a live account balance mid-transaction) |
| Data requested often enough that a cache hit is likely before it expires | Data requested once and never again (a one-off report) |
| Policy | Behavior | Trade-off |
|---|---|---|
| Write-through | Every write goes to the cache and the database together (or the cache write triggers the database write). | Strong cache/database consistency, but higher write latency. |
| Write-back | Writes land in the cache first and are asynchronously flushed to the database later. | Very low write latency, but risks losing recent writes if the cache fails before flushing, and risks stale reads elsewhere. |
| Write-around | Writes go straight to the database, bypassing the cache; the cache is only populated on a subsequent read (cache miss). | Avoids filling the cache with data that might never be re-read, but the first read after a write is always a slow cache miss. |
| Memcached | Redis | |
|---|---|---|
| Data model | Simple key-value strings | Rich data structures — strings, hashes, lists, sets, sorted sets |
| Persistence | Purely in-memory, no disk persistence | Optional disk persistence (snapshotting or an append-only log) |
| Typical use | Straightforward object caching | Caching plus lightweight structures like leaderboards, rate-limit counters, or pub-sub |