Cache-aside, read-through, write-through, write-back: who fills the cache, and when?
A caching strategy is the rule for who fills the cache and when it is written. It decides how the cache and the database work together.
A cache is only useful if it holds the right data. Two questions decide that: on a read miss, who loads the data? and on a write, where does the data go first?
Without a clear strategy, the cache and the database drift apart. Users see old prices, lost orders or wrong counts.
| Strategy | Often used for |
|---|---|
| Cache-aside | The most common choice: user profiles, product data, API answers with Redis or Memcached |
| Read-through | Cache libraries and services that load data for you; CDNs work like this for files |
| Write-through | Data that must not be lost and is read right after being written (settings, profiles) |
| Write-back | Very write-heavy data where a small loss is acceptable: counters, view counts, metrics, game scores |
| Write-around | Data written once and rarely read: logs, uploads, bulk imports |
The app is in charge. The cache is a side store.
The cache is in charge. The app only talks to the cache. On a miss, the cache loads from the database.
Each write goes to the cache and the database together, and the app waits for both.
Each write goes to the cache only. The cache copies to the database later, often in batches.
Writes go to the database only. The cache is filled by reads.
| Strategy | Read speed | Write speed | Risk |
|---|---|---|---|
| Cache-aside | Fast after the first read | Normal | Stale data after races; small |
| Read-through | Fast after the first read | Normal | Stale data after writes |
| Write-through | Fast, always fresh | Slower (two writes) | Low |
| Write-back | Fast, always fresh | Fastest | Data loss if the cache crashes |
| Write-around | First read after a write is slow | Normal | Stale copy if not removed |
get(key): value = cache.get(key). If it is missing: value = db.read(key), then cache.set(key, value, ttl). Return value.
update(key, value): db.write(key, value), then cache.delete(key).
| Term | Meaning in easy words |
|---|---|
| Cache-aside | App checks the cache, loads from the database on a miss and fills the cache itself |
| Read-through | The cache loads missing data from the database on its own |
| Write-through | Writes go to the cache and the database together |
| Write-back / write-behind | Writes go to the cache first and are saved to the database later |
| Write-around | Writes skip the cache and go to the database |
| Dirty data | Data changed in the cache but not yet saved to the database |
| Flush | Copying dirty data from the cache to the database |
| Lazy loading | Filling the cache only when something is asked for |
| Race condition | Two actions happen in an unlucky order and give a wrong result |
| Source of truth | The one place whose data is always the right answer (the database) |