# Caching strategies and how to choose one (https://layerscache.com/docs/learn/caching-strategies)

> Caching strategies compared: cache-aside, read-through, write-through, write-back, write-around and refresh-ahead. See how each works and which to pick.



A **caching strategy** is the rule for when data enters the cache and how writes reach the database. Reads are handled by **cache-aside**, **read-through** or **refresh-ahead**; writes by **write-through**, **write-back** (write-behind) or **write-around**. For most read-heavy applications the best default is cache-aside or read-through for reads and write-around (invalidate after the database commit) for writes.

The right choice depends on three questions: how often data is read compared with written, how stale a read may be, and whether losing a write is acceptable.

**Level:** zero to one · &#x2A;*You need:** [What is caching?](/docs/learn/what-is-caching)

## What are the types of caching strategies? [#what-are-the-types-of-caching-strategies]

There are two groups, because a cache has two jobs: answer reads and absorb writes. Pick one read strategy and one write strategy, and the pair is your design.

| Group | Strategies                               | Question it answers                                  |
| ----- | ---------------------------------------- | ---------------------------------------------------- |
| Read  | Cache-aside, read-through, refresh-ahead | Who loads the value when the cache has none?         |
| Write | Write-through, write-back, write-around  | When does a change reach the database and the cache? |

Here is each write path in one picture. The read paths come next, one per section.

```mermaid
sequenceDiagram
  participant App
  participant Cache
  participant DB as Database
  Note over App,DB: Write-through
  App->>DB: write
  App->>Cache: write the same value
  Note over App,DB: Write-back
  App->>Cache: write only here
  Cache-->>DB: flush later in a batch
  Note over App,DB: Write-around
  App->>DB: write
  App->>Cache: delete the key
```

## Cache-aside (lazy loading) [#cache-aside-lazy-loading]

The application owns the logic: check the cache, on a miss query the database, store the result with a TTL. Only data that is requested gets cached, and if the cache is down, reads go to the database. It is the most common strategy and has its own lesson: [the cache-aside pattern](/docs/learn/cache-aside-pattern).

```mermaid
sequenceDiagram
  participant App
  participant Cache
  participant DB as Database
  App->>Cache: get user:42
  Cache-->>App: miss
  App->>DB: select user 42
  DB-->>App: row
  App->>Cache: set user:42 with a TTL
```

```ts
const cached = await redis.get(key)
if (cached) return JSON.parse(cached) as User
const user = await db.users.find(id)
await redis.set(key, JSON.stringify(user), 'EX', 300)
return user
```

## Read-through [#read-through]

Read-through is cache-aside moved inside the cache. You give the cache a loader, and it decides when to call it. Because one component sees every miss, it can make sure 100 concurrent misses for one key run the loader once instead of 100 times.

```mermaid
sequenceDiagram
  participant App
  participant Cache
  participant DB as Database
  App->>Cache: get user:42
  Cache->>DB: load user 42
  DB-->>Cache: row
  Cache-->>App: the user
```

```ts
const user = await cache.getOrSet(`user:${id}`, () => db.users.find(id))
```

`getOrSet` in lazy-layers-cache is a read-through call. It reads memory, then Redis, then calls your loader once per key, even when the misses come from different servers.

### Cache-aside vs read-through [#cache-aside-vs-read-through]

The data flow is the same. The difference is who writes the glue code.

|                                  | Cache-aside                                     | Read-through                            |
| -------------------------------- | ----------------------------------------------- | --------------------------------------- |
| Who calls the database on a miss | Your application                                | The cache, through a loader you give it |
| Duplicate loads for one key      | One per concurrent miss, unless you add locking | One, because the cache sees every miss  |
| Typical tool                     | Redis with hand-written code                    | A library such as lazy-layers-cache     |

## Write-through [#write-through]

On every write, update the database and then the cache in the same request. The next read is a guaranteed hit with the new value. The costs: every write is slower, and you cache data that may never be read.

```ts
await db.users.update(id, changes)
const user = await db.users.find(id)
await cache.set(`user:${id}`, user)
```

Write the database first. If you write the cache first and the database write fails, the cache holds a value that never existed.

## Write-back (write-behind) [#write-back-write-behind]

The application writes only to the cache, and a background process flushes changes to the database in batches. Writes are as fast as a cache write, and many updates to one key collapse into one database write. If the cache loses the buffered writes before the flush, they are gone. Use it for data where that is acceptable, such as view counters or analytics, and not for orders or balances.

### Write-through vs write-back [#write-through-vs-write-back]

|                                  | Write-through      | Write-back               |
| -------------------------------- | ------------------ | ------------------------ |
| Write latency                    | Database speed     | Cache speed              |
| Durability when the call returns | Yes                | No, until the flush      |
| If the cache fails               | Nothing is lost    | Buffered writes are lost |
| Good for                         | Profiles, settings | Counters, metrics        |

## Write-around [#write-around]

Write only to the database, then delete the cached copy. The next read misses and loads the committed value. This is the safest write strategy to pair with cache-aside or read-through, because the cache never holds a value the database rejected.

```ts
await db.users.update(id, changes)
await cache.invalidate(`user:${id}`)
```

Deleting is safer than updating the cache from the write path: two concurrent writers can update the cache in the opposite order from the database, but two deletes always leave the cache empty. Read more in [cache invalidation](/docs/learn/cache-invalidation).

## Refresh-ahead [#refresh-ahead]

Reload a key in the background shortly before it expires, while callers keep reading the current value. Popular keys never expire in front of a user, which also removes the stampede that an expiry causes. In lazy-layers-cache this is `earlyRefresh`:

```ts
// After 80% of the TTL, the next hit reloads the key once in the background.
const price = await cache.getOrSet(`price:${sku}`, () => pricing.get(sku), { earlyRefresh: 0.8 })
```

The cost is reloading keys that nobody asks for again, so use it for a short list of hot keys, not everything.

## What are the Redis caching strategies? [#what-are-the-redis-caching-strategies]

Redis is a store, not a strategy. It does not call your database, so with Redis the common choice is cache-aside: `GET` the key, and on a miss query the database and `SET` the result with an expiry. Write-around is `DEL` after the commit. Read-through and write-back need a library or your own code on top of Redis. The [Redis cache in Node.js](/docs/learn/redis-cache-nodejs) lesson shows the code.

## How to choose a caching strategy [#how-to-choose-a-caching-strategy]

1. **Mostly reads, a few seconds of staleness is fine** (product pages, profiles, settings): read-through or cache-aside with a TTL, plus write-around.
2. **A user must see their own write at once** (a profile they just saved): add write-through for that key, or invalidate and let the next read load it.
3. **Very hot keys with expensive loads** (a home page feed): read-through with refresh-ahead or stale-while-revalidate, so no request waits on the reload.
4. **High write volume where losing a few writes is acceptable** (counters, metrics): write-back.
5. **Data must never be stale** (permissions, balances): do not cache it, or cache it briefly and invalidate on every write.

## The same strategies with getOrSet [#the-same-strategies-with-getorset]

| Strategy                    | lazy-layers-cache                                                                                      |
| --------------------------- | ------------------------------------------------------------------------------------------------------ |
| Read-through                | `getOrSet(key, loader)` and `getOrSetMany(keys, loader)`                                               |
| Write-through               | `set(key, value)` after the database write                                                             |
| Write-around                | `invalidate(key)`, `invalidateByPattern('user:42:*')` or `invalidateTags(['team:7'])` after the commit |
| Refresh-ahead               | `earlyRefresh: 0.8`                                                                                    |
| Serve stale while reloading | `staleWhileRevalidate: true`                                                                           |

For how the library keeps layers and servers in step after a write, read [invalidation](/docs/concepts/invalidation) and [lazy loading](/docs/concepts/lazy-loading).

Next lesson: [the cache-aside pattern](/docs/learn/cache-aside-pattern).

## Further reading [#further-reading]

* [CodeAhoy, Caching Strategies and How to Choose the Right One](https://codeahoy.com/2017/08/11/caching-strategies-and-how-to-choose-the-right-one/): cache-aside, read-through, write-through, write-around and write-back, each with a short explanation.
* [AWS ElastiCache, caching strategies](https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/Strategies.html): lazy loading, write-through and adding a TTL, with their advantages and disadvantages.
* [Microsoft, Cache-Aside pattern](https://learn.microsoft.com/en-us/azure/architecture/patterns/cache-aside): contrasts cache-aside with caches that provide read-through and write-through themselves.
* [Hello Interview, Caching for System Design Interviews](https://www.hellointerview.com/learn/system-design/core-concepts/caching): the four core cache patterns, and which one to default to in an interview.
* [Yang et al., Twitter cache clusters, OSDI 2020](https://www.usenix.org/conference/osdi20/presentation/yang): measured 153 production clusters and found write-heavy workloads in more than 35% of them.


## Questions

### What are the main caching strategies?

Reads use cache-aside (the application loads on a miss), read-through (the cache loads on a miss) or refresh-ahead (the cache reloads before expiry). Writes use write-through (write the cache and the database together), write-back or write-behind (write the cache now, the database later) or write-around (write only the database and invalidate the cache).

### Which caching strategy is best?

For most read-heavy web applications, cache-aside or read-through for reads, plus write-around (invalidate after the database commit) for writes. It keeps the database as the source of truth, caches only what is read, and survives the cache going down. Choose write-through when reads right after a write must hit, and write-back only when you can afford to lose buffered writes.

### What is the difference between cache-aside and read-through?

Both load a value on a miss and store it. In cache-aside, your application code checks the cache, calls the database and writes the cache. In read-through, you hand the cache a loader and it does those steps itself, which also lets it deduplicate concurrent misses.

### What is the difference between write-through and write-back?

Write-through writes the database and the cache in the same request, so the write is durable when it returns. Write-back (also called write-behind) writes the cache first and flushes to the database later in batches, which is faster but loses the buffered writes if the cache fails before the flush.

### What is a Redis caching strategy?

Redis is most often used with cache-aside: read the key, and on a miss query the database and SET the result with an expiry. Redis itself does not load from your database, so read-through and write-back with Redis are implemented by a library or your own code.