Skip to content

Cache-aside and the other read/write strategies

Picture a shop’s product page. A thousand visitors a minute ask for the same product. Each time, the database looks the row up, assembles the answer and sends it back, and each time the answer is the same.

A cache is a small, fast store that keeps recent answers, so the database does that work once instead of a thousand times. When the answer is in the cache, the request is a hit. When it is not, the request is a miss, and it pays for the whole trip to the database. The share of requests that are hits is the hit ratio.

Mental model. A cache is a bet on repetition. You keep a copy of an answer close by. You win whenever someone asks for it again, and you lose a little on every copy nobody asks for twice.

The cache is not the truth. The database is. A cache holds copies that can be thrown away at any moment and rebuilt from the database. Facebook’s engineers describe their memcache the same way: it is not the authoritative source of the data, so it is allowed to evict entries. Keep that in mind, because almost every difficulty in this module comes from a copy that is out of date, missing, or suddenly gone.

Why the hit ratio matters more than it looks

Section titled “Why the hit ratio matters more than it looks”

The database only sees the misses. With R requests per second and a hit ratio of h, it serves R × (1 − h) reads per second.

Hit ratio Reads per second that reach the database, at 1,000 requests per second
80% 200
90% 100
95% 50
99% 10
99.9% 1

Going from 90% to 99% is nine points. For the database it is a ten-fold drop. The same arithmetic runs backwards: a cache whose hit ratio falls from 99% to 90% multiplies the load on the database by ten. The last three lessons of this module are about how that happens.

In cache-aside, also called lazy loading, the application does the work. The cache is a plain store that knows nothing about the database.

Read path

  1. Ask the cache for the key.
  2. If it is there (a hit), return it.
  3. If it is not (a miss), read the database, store the result in the cache with a lifetime, and return it.

Write path

  1. Update the database.
  2. Delete the cached copy. The next read will miss and fill the cache again with the new value.

The order of the write path matters. If you delete the cached copy first, a reader can arrive before the database has changed, miss, read the old row and put it back in the cache. The cache then holds stale data until its lifetime ends or the next write deletes it. Microsoft’s description of the pattern warns about exactly this, and Facebook’s memcache paper describes its own write path in the same order: the web server updates the database, then sends a delete to the cache. The reasoning about why the order matters is ours, and the next lesson works through it.

C# exampleCache-aside with a fake Redis and a fake clock
cache-aside.cs
// Cache-aside: the application checks the cache first.
// On a miss it reads the database and stores the result.
using ShardCraft.Playground;
var clock = new FakeClock();
var redis = new FakeRedis(clock);
var database = new Dictionary<string, string> { ["user:42"] = "Ada" };
var databaseReads = 0;
async Task<string?> GetUserAsync(string key)
{
var cached = await redis.GetAsync(key);
if (cached is not null) return cached; // hit
databaseReads++; // miss: ask the database
if (!database.TryGetValue(key, out var value)) return null;
await redis.SetAsync(key, value, ttl: TimeSpan.FromSeconds(30));
return value;
}
async Task UpdateUserAsync(string key, string value)
{
database[key] = value; // write the database first
await redis.DeleteAsync(key); // then drop the cached copy
}
async Task ShowAsync(string label)
{
var user = await GetUserAsync("user:42");
Console.WriteLine($"{label,-26} {user} (database reads so far: {databaseReads})");
}
await ShowAsync("1st read (miss)");
await ShowAsync("2nd read (hit)");
clock.Advance(TimeSpan.FromSeconds(31));
await ShowAsync("after 31 s (TTL expired)");
await UpdateUserAsync("user:42", "Grace");
await ShowAsync("after an update");
await ShowAsync("read again (hit)");
Output
1st read (miss) Ada (database reads so far: 1)
2nd read (hit) Ada (database reads so far: 1)
after 31 s (TTL expired) Ada (database reads so far: 2)
after an update Grace (database reads so far: 3)
read again (hit) Grace (database reads so far: 3)

This is the exact code that produced this output, run with the .NET SDK when the site was built. Nothing runs in your browser.

Read the output against the code. The first read misses and reads the database once. The second is a hit. After 31 simulated seconds the entry has expired, so the next read goes to the database again. After the update, the cached copy is gone, so the following read misses once and then hits.

The lab below is cache-aside under load. Each dot in the diagram stands for many requests.

Each request asks the cache first. On a miss the application reads the database and stores the result for next time. Watch the hit ratio climb as the cache fills, then change the traffic or how long entries live.

300 req/s
20 s
0%
ClientsHealthy299.8/sApplicationHealthy0% err.CacheShard 1: <1%, HealthyShard 2: <1%, HealthyShard 3: <1%, HealthyShard 4: <1%, HealthyHealthy<1%DatabaseHealthy1%
ClientsHealthy299.8/sApplicationHealthy0% err.CacheShard 1: <1%, HealthyShard 2: <1%, HealthyShard 3: <1%, HealthyShard 4: <1%, HealthyHealthy<1%DatabaseHealthy1%
  • Cache hit
  • Cache miss, goes on to the database
  • Waits for another request’s read
  • Request fails

Each dot stands for many requests. The numbers show the real rate.

Hit ratio 99%: 0.9% of requests reach the database (2.6 reads/s, capacity 400/s).

20 s

History

Hit ratio

99%

Use the left and right arrow keys to read values at each moment.

Database reads per second

4/s

Use the left and right arrow keys to read values at each moment.

p99 latency

2 ms

Use the left and right arrow keys to read values at each moment.

Data table
History
Simulated timeHit ratioDatabase reads per secondp99 latency
5 s91%26/s17 ms
10 s94%16/s17 ms
15 s99%4/s1.4 ms
20 s99%4/s2 ms
Cache lab metrics
ComponentStateUtilisationQueue
Cache, Shard 1Healthy<1%0
Cache, Shard 2Healthy<1%0
Cache, Shard 3Healthy<1%0
Cache, Shard 4Healthy<1%0
DatabaseHealthy1%0
Traffic
299.8/s
Successful
299.8/s
Error rate
0%
Hit ratio
99%
Database reads
2.6/s
p50
0.14 ms
p95
0.66 ms
p99
1.2 ms
Entries cached
491 / 500
Requests that write
0%
Stale hits
0%
Coalesced requests
0/s
Skipped the cache
0/s

Figures describe the last 5 simulated seconds.

Illustrative values, not benchmarks of any real product.

Model notes

Assumptions

  • Each request asks for a key drawn independently from a fixed popularity distribution. Real traffic has bursts and trends that this does not capture.
  • Every operation on a cache shard (lookups, stores, deletions) joins one queue served by a few slots, so a busy shard slows everything on it.
  • Requests follow a Zipf distribution over 500 keys: a few keys are popular and most are rarely asked for.

Simplifications

  • An entry’s lifetime starts when it is stored. Reading it does not extend it.
  • Only a version number is tracked for each key, not the data. A cached copy is stale when its version is behind the database’s.
  • The cache never runs out of memory, so no entry is evicted early. Real caches evict the least recently used entries when they are full.
  • A write updates the database and then deletes the cached copy (cache-aside). Write-through and write-behind are compared in the trade-off explorer, not simulated here.
  • Refresh before expiry reloads an entry in the background when a request reads it in the last part of its life. Production systems often use a probabilistic variant.
  • A cache that goes down loses everything it held and comes back empty. A cache with persistence would not.
  • The application learns that the cache is down at once, on the request that fails. Health checks and circuit breakers are not modelled.
  • When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.

Parameter values are illustrative. They are not benchmarks of any real product.

Try these, one at a time:

  1. Press Restart to see a cold start. In the first five simulated seconds about 77% of requests are hits, because the cache is filling. With the lab’s starting settings (300 requests per second over 500 keys, entries living 20 seconds) it settles near 93% hits, and the database serves about 23 reads per second.
  2. Shorten the entry lifetime to 5 seconds. The hit ratio settles near 81% and the database now serves about 58 reads per second. A short lifetime is a tax on the database.
  3. Raise the lifetime to 120 seconds. The hit ratio goes above 99%. Why not always choose a long lifetime? The next lesson answers that.

Return the lifetime to its starting value, raise Traffic to 1,500 requests per second, and press Flush the cache.

At 300 requests per second the database copes with an empty cache. At 1,500 it does not. When the cache is flushed, the database queue climbs to its limit, the 99th-percentile latency jumps to about 460 milliseconds, and some requests start to fail. This database can answer about 400 reads per second, and with the cache empty it is being asked for the full 1,500.

A cache can hide a database that is too small for the traffic. The day the cache is empty, the real size of the database shows. A cache that has just started, been flushed, or lost its contents behaves like this, and the dangerous moment is the one right after. Lesson 3 is about one way it goes wrong, and lesson 5 about another.

Cache-aside is one answer to the question “who keeps the cache in step with the database?”. There are three others, and the differences are in what each one protects and what each one risks.

  • Cache-aside. The application checks the cache, reads the database on a miss, fills the cache, and deletes the entry on a write.
  • Read-through. The application only talks to the cache. On a miss, the cache layer loads the value from the database itself.
  • Write-through. Every write updates the database and the cache as one operation, and is acknowledged only when both are done.
  • Write-behind. A write goes to the cache and is acknowledged at once. The cache layer writes it to the database later, often in batches.

Every option follows the trade-off framework: the decision, why you would make it, its benefits, its costs, how it fails, where it stops scaling, and the alternative. The explorer lays the four side by side, row by row. Hide the options you are not interested in, and tick the requirements that apply to a system you have in mind.

Caching strategies

Where does the cache sit on the read path and the write path, and who keeps it in step with the database?

Every option follows the same framework: decision, why, benefits, costs, failure modes, scaling limitations, alternative.

Choosing options and requirements needs JavaScript. All the options are shown below.

Options to compare

Show or hide options. At least one stays on.

What does your system need?

Tick the requirements that apply. Each option is then measured against them.

Cache-aside

Decision

The application reads the cache first. On a miss it reads the database and stores the result in the cache. On a write it updates the database, then removes the cached entry.

Why?

The cache stays optional and separate from the database. Only data that is actually read gets cached, and the application decides what to cache and for how long.

Benefits
  • Only requested data takes memory.
  • A cache failure does not lose or corrupt data: the database stays the source of truth, and the application can fall back to reading it.
  • It works with any cache and any database, and the rules can differ for each kind of data.
Costs
  • Every caller has to do the work (check, load, fill, invalidate), or a shared library has to.
  • The first read after a miss pays for a cache lookup, a database read and a cache write.
  • Between a write and the next read, a reader can miss or briefly see stale data.
Failure modes
  • A stale entry that lasts: a reader loads the old row, a writer then updates the database and removes the entry, and the reader stores the old row afterwards. The entry stays wrong until it expires or is removed again.
  • A stampede: a popular entry expires or is removed, many readers miss at the same moment, and all of them go to the database.
  • A cache outage sends every read to the database. If it cannot take the full read load, it overloads.
Scaling limitations
  • The hit ratio is limited by how much of the working set fits in memory and by how skewed the reads are.
  • The database must be sized for the cold-cache and cache-down read load, or protected from it.
Alternative

Choose Read-through when many services read the same data and you want the loading logic in one place instead of in every caller.

Read-through

Decision

The application only talks to the cache. On a miss, the cache layer itself loads the value from the database, stores it and returns it.

Why?

Callers get one simple way to read, and the loading logic lives in one place.

Benefits
  • Application code is simpler: callers never handle a miss.
  • One place to set expiry, serialisation and metrics for every caller.
  • The layer can be built to load each missing key once for all the readers waiting on it.
Costs
  • It needs a cache product or library that supports loaders.
  • The cache layer must know how to reach and query the database, so the two are coupled.
  • The cache sits on the read path, so it is no longer optional.
Failure modes
  • If the cache layer is down, reads fail unless the application can also read the database directly, which adds cache-aside’s fallback back in.
  • A slow or failing loader holds up every reader waiting on that key.
  • Without protection, a popular key that expires still causes a stampede, only inside the cache layer.
Scaling limitations
  • The same limit on the hit ratio as cache-aside.
  • The number of loads the layer runs against the database at once has to be capped, or a cold cache overloads it.
Alternative

Choose Cache-aside when the cache must stay optional, or your cache product has no loader support.

Write-through

Decision

Every write updates the database and the cache as one operation. The write is acknowledged only when both are done.

Why?

So that a read right after a write finds the new value in the cache, and an acknowledged write is already in the database.

Benefits
  • After a successful write, readers see the new value immediately, for that key.
  • Recently written data is already cached, so reads of it are hits and the database sees fewer reads.
  • An acknowledged write is already durable in the database.
Costs
  • A write takes as long as the database write plus the cache write: there is no gain on writes.
  • Data that is rarely or never read still takes cache memory, which makes the cache larger and more expensive.
  • It does not help data that was never written through the cache, so it is almost always paired with a way to load on a miss.
Failure modes
  • One of the two writes fails. The cache and the database then disagree, unless the layer undoes the other write or removes the entry.
  • Two writes to the same key at the same time can reach the cache and the database in different orders, and leave them different.
  • If the cache layer is unavailable, writes either fail or skip the cache and leave it stale.
Scaling limitations
  • Write throughput is still limited by the database: the cache absorbs none of it.
  • Every write also costs a cache operation, so the cache needs capacity for the full write rate.
Alternative

Choose Cache-aside when most of the data you write is not read soon, or the cache must stay optional: remove the entry on a write instead of writing it.

Write-behind

Decision

A write goes to the cache and is acknowledged at once. The cache layer writes it to the database later, often in batches.

Why?

To make writes fast and to take bursts of writes off the database.

Benefits
  • Low write latency: the application does not wait for the database.
  • Several changes to the same entry before the next flush can be merged into one database write.
  • A slow or unavailable database can be ridden out for a while, as long as the backlog fits in memory.
Costs
  • Until the queue is flushed, the cache is the only place that holds the write. The database lags behind it, and anything that reads the database directly sees older data.
  • It needs a flush queue, retries, ordering and a recovery plan: the most machinery of the four.
  • A database error arrives after the write was acknowledged, so the caller can no longer be told.
Failure modes
  • The node holding unflushed writes fails, and those writes are lost, unless the cache keeps backups of its queue.
  • The database stays down for long: the backlog grows until memory runs out or the layer has to refuse writes.
  • Writes reach the database in a different order from the one in which they were acknowledged, if the flusher does not keep the order.
Scaling limitations
  • The backlog is limited by memory. A write rate that stays above what the database accepts is delayed, not removed.
  • Making the cache durable (replication, persistence) costs money and latency that the design was meant to avoid.
Alternative

Choose Write-through when an acknowledged write must not be lost. To keep asynchronous database writes without that risk, put each write in a durable queue or log first and apply it to the database from there.

Nothing is ticked yet. Tick a requirement to see how each option measures up.

Two exercises with the explorer:

  1. Tick An acknowledged write must never be lost. Exactly one option does not meet it. Now untick it and tick A burst of writes must not overload the database. Exactly one option meets it, and it is the same one. That is a trade-off in its plainest form: the property that makes writes fast and cheap for the database is the one that puts acknowledged writes at risk.
  2. Tick The system must keep working when the cache is unavailable. Only one option can keep serving without the cache, and only if the database can carry the load. Keep this one in mind for lesson 5.

Your catalogue has 20 million items of about 3 kB each. You want 90% of requests to be hits, and you want two copies of the cache so that losing one machine does not empty it. How much memory do you need?

The calculator shows its formulas and the numbers that go into each step. It starts with every item equally popular (a skew of 0).

Cache memory calculator

Your numbers

million objects

How many different objects the requests ask for over the period you care about.

kB

The average size of one cached object.

bytes

What the cache stores besides the object: the key, pointers, the expiry time. It depends on the cache software, so measure it.

%

The share of requests the cache should answer.

0 means every object is equally popular. The higher it is, the more a few objects take most of the requests. Real traffic is skewed, so measure yours.

copies

How many copies of every cached key the cluster holds: 1 is no replica, 2 is a primary and one replica.

Changing the numbers needs JavaScript. The result is for the starting numbers.

Result

Cache memory to provision110 GB

Each copy holds 18M keys.

How it is calculated

Each step shows its formula, the numbers that go in, and the figure that comes out.

  1. Keys to cache

    k = the fewest of the most popular keys that serve at least h of the requests

    Rank the keys by popularity and add up their shares of the requests, most popular first. With H(n) = 1 + 1/2^s + 1/3^s + … + 1/n^s, k is the smallest number for which H(k) ÷ H(N) ≥ h. If s = 0, every key is equally popular and k = h × N.

    N objects in the working set
    20M
    s popularity skew
    0
    h target hit ratio
    90%

    k keys to cache18M (share of the working set: 90%)

  2. Bytes per cached key

    b = o + v

    The object, plus what the cache keeps beside it.

    o object size
    3 kB
    v per-key overhead
    64 B

    b bytes per cached key3.06 kB

  3. Memory for one copy

    M = k × b

    Every cached key takes b bytes.

    k keys to cache
    18M
    b bytes per cached key
    3.06 kB

    M memory for one copy55.2 GB

  4. Memory for all copies

    T = M × r

    Each copy holds the same keys, so the cluster needs r times the memory of one copy.

    M memory for one copy
    55.2 GB
    r copies
    2

    T memory for all copies110 GB

What each hit ratio costs, with your other numbers
Hit ratioKeys to cacheShare of the working setMemory, all copies
50%10M50%61.3 GB
80%16M80%98 GB
90% · your target18M90%110 GB
95%19M95%116 GB
99%19.8M99%121 GB
99.9%20M99.9%122 GB
Model notes

Assumptions

  • Requests ask for objects with Zipf popularity: the object of rank r is asked for in proportion to 1 / r^s. Real traffic is only approximately like this, so measure your own skew.
  • Popularity does not change over time, so the cache holds exactly the most popular keys. A real cache learns what is popular, and the popular set drifts, so it holds the best keys only approximately.
  • Every cached key takes the same overhead on top of the object. Real overhead depends on the cache software and its data structures, so measure it.

Simplifications

  • No headroom is added. A real cache needs some spare memory for fragmentation, for its own buffers, and for growth, so provision more than this figure.
  • Every copy holds every cached key. A cluster that splits the keys across nodes and keeps one replica of each part needs the same total, spread over more nodes.
  • Sizes use decimal units: 1 kB is 1 000 bytes and 1 GB is 10^9 bytes. Memory is often sold in binary units: 1 GiB is 2^30 bytes, about 7% more than 1 GB.
  • In back-of-envelope mode, the counts and sizes you enter are rounded to the nearest power of ten before anything is calculated. The result is an order of magnitude, not a figure to buy against.

Parameter values are illustrative. They are not benchmarks of any real product.

  1. With a skew of 0, which means every item is as popular as every other, you need to cache 90% of the items, and the answer is over 100 GB.
  2. Change the Popularity skew to 0.8. The most popular items now take a larger share of the requests, so fewer of them cover 90%: the answer falls to about 74 GB.
  3. Change it to 1.1. The answer falls to about 2.6 GB, forty times less than at the start.

The skew changed the answer by a factor of forty, and it is the one number you cannot look up: you have to measure it on your own traffic. Studies of web request logs found popularity that is “Zipf-like”, with an exponent that varied from one log to the next, which is why the calculator asks for it instead of assuming one. Try Back-of-envelope mode too: it rounds the counts and sizes to powers of ten, which is the precision you have in a first conversation about a design.

  • A cache keeps copies of answers close by. The database remains the source of truth, and any copy can be discarded and rebuilt.
  • The database only sees the misses: its load is R × (1 − h). Small changes in the hit ratio are large changes for the database.
  • In cache-aside the application reads the cache first, loads and fills on a miss, and on a write updates the database and then deletes the cached copy, in that order.
  • An empty cache is only as safe as the database behind it is large.
  • Read-through, write-through and write-behind move the work into the cache layer, and each one trades something: simplicity, durability, write load.
  • The memory a cache needs depends most on how skewed the traffic is, which you can only know by measuring.

Next: why entries cannot simply live forever, and how a lifetime, a deletion and a race between a reader and a writer decide whether the cache tells the truth.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.