Skip to content

TTL and invalidation: keeping copies honest

The cache holds a copy. The database holds the truth, and the truth changes. Nothing tells the cache, so a cached copy is stale from the moment the database has a newer value and the cache has not heard about it.

There are two tools for dealing with that, and most real caches use both:

  • Expiry. Every entry is stored with a time to live (TTL). When the time is up, the entry is gone, and the next read fetches a fresh copy.
  • Invalidation. When the application changes the database, it also deletes the cached copy, so the next read fetches the new value.

An entry is stored at a moment, and it cannot be served after that moment plus its TTL. So if the database changes while a copy is cached, the copy is stale for at most the time that remains of its life: never longer than the TTL. This holds for an expiry fixed when the entry is stored, which is what the lab models. Some caches also offer a sliding expiry, which restarts the clock each time the entry is read. With that, a popular entry can outlive its TTL many times over, and the ceiling is gone.

That is a useful promise, because it holds whatever happens: a lost message, a bug in the invalidation code, a server that was unreachable when the write happened. The TTL does not need anyone to remember anything.

The price is paid in misses. Every expiry is a miss, and every miss is a database read. A short TTL gives fresher data and a heavier database. A long TTL does the opposite.

The lab starts in the situation where the TTL is the only thing that keeps data fresh: Delete the cached copy on write is off. Two percent of requests are writes.

A TTL ends the life of every entry, whatever happens in the database. With deletion on write switched off, the TTL is the only thing that makes cached data fresh again. Change the lifetime and the write rate, and watch how much of what the cache serves is out of date.

30 s
2%
Off
ClientsHealthy299/sApplicationHealthy0% err.CacheShard 1: <1%, HealthyShard 2: <1%, HealthyShard 3: <1%, HealthyShard 4: <1%, HealthyHealthy<1%DatabaseHealthy1%
ClientsHealthy299/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.

81% of cache hits are stale: the database has changed since the entry was stored.

30 s

History

Stale share of hits

84%

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

Hit ratio

100%

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

Database reads per second

0/s

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

Data table
History
Simulated timeStale share of hitsHit ratioDatabase reads per second
5 s38%100%0/s
10 s66%100%0/s
15 s76%100%0/s
20 s72%100%0/s
25 s80%100%0/s
30 s84%100%0/s
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/s
Successful
299/s
Error rate
0%
Hit ratio
100%
Database reads
5.4/s
p50
0.14 ms
p95
0.69 ms
p99
5.3 ms
Entries cached
0 / 100
Requests that write
2%
Stale hits
81%
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.
  • Every write changes the single value of its key. A cached copy is stale when the database has changed since it was read.

Simplifications

  • The model counts stale reads. It does not measure how old the data is, only that it is behind.
  • 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.

Move the Entry lifetime (TTL) slider and watch the Stale share of hits chart, which is the share of cache hits that returned a copy that was already out of date. These are the numbers the lab settles at, measured over a minute once it has warmed up. Yours will be close.

Entry lifetime Hits that were stale Hit ratio Database reads per second
1 s 9% 78% 66
2 s 16% 87% 40
5 s 28% 94% 18
10 s 42% 97% 10
30 s 65% 99% 3
60 s 80% 99% 2

At the starting lifetime of 30 seconds, about two in three of the answers the cache gives are out of date. The lab has 100 keys, 300 requests per second and 2% writes, so on average each key is written about every 17 seconds (the popular ones more often), and a copy that lives 30 seconds is usually overtaken by a write before it expires. A table like this one is why “just set a TTL” is not a design.

Now switch Delete the cached copy on write on. The stale share falls to zero. The hit ratio falls a little, to about 97%, and the database serves about 8 reads per second instead of 3, because every write now makes the next read a miss. That is the price of deleting: one extra miss per write.

When a write happens, the application can delete the cached copy, or it can write the new value into the cache. Deleting is simpler to get right.

Facebook’s memcache chooses deletion, and their paper gives the reason: deletes are idempotent. What follows from that is our own reasoning. Doing a delete twice, or late, does no harm, while updating in place has to be ordered: two writers that update the cache in a different order from the order in which they updated the database leave the cache holding the older value, and nothing corrects it until the entry expires.

What happens if a reader and a writer race?

Section titled “What happens if a reader and a writer race?”

Deleting after the write is not airtight. Here is the sequence that beats it:

time →
Reader A miss ─ read database (old value, v1) ─────────────────────────────────── store v1 in cache
Writer B update database → v2 ─ delete cache entry

Reader A read the old value before the database changed. Writer B then updated the database and deleted the cache entry, which was not there yet. Reader A, slow, now stores the value it read, which is old. The cache holds v1 and the database holds v2, and no further write is coming to correct it. The copy stays wrong until its TTL ends.

Facebook’s paper calls this a stale set and addresses it with leases. On a miss, the cache gives the reader a token. A delete invalidates the token. When the slow reader finally tries to store its value, the cache sees that the token is no longer valid and refuses it.

The TTL is the backstop for everything the deletion misses. That is the reason to use both: delete on write for freshness, and a TTL as the safety net for the races, the lost messages and the bugs.

The same goes when the cache cannot be reached at the moment of a write. The database is updated, the deletion fails, and the cached copy stays. Only the TTL fixes the copy afterwards.

Ask two questions about the data, in this order:

  1. How wrong can this value be, and for how long, before it hurts someone?
  2. How many reads can the database carry if every entry expires as often as that?

Three examples show how different the answers are:

  • A product description changes rarely, and a reader who sees yesterday’s wording is not harmed. A long TTL is fine, and deleting on write is a bonus.
  • A “2 left in stock” counter is read at the moment someone decides to buy. A stale value costs real money. Either delete on every change or do not cache it.
  • A revoked permission has to stop working at once. Delete on change, and keep a short TTL as the backstop in case the deletion is lost.

The same ideas apply to caches that sit closer to the user, such as CDN and browser caches, which the course covers later.

Switch Delete the cached copy on write off again, and set the lifetime to 1 second. The stale share falls under 10%. Is the cache still worth having? It serves about 78% of reads, which is a lot. But the database now serves about 66 reads per second, twenty times more than at 30 seconds.

Now put the lifetime back to 30 seconds and switch deletion on. You keep about 97% hits, the database serves about 8 reads per second, and stale reads are gone. When freshness matters, deleting on write keeps far more of the cache’s benefit than a short TTL does.

  • A cached copy is stale when the database has changed and the cache has not heard about it.
  • A TTL bounds staleness: a copy can never be served longer than its lifetime. A short TTL means fresher data and more database reads.
  • Deleting the cached copy on write removes most staleness, at the price of one extra miss per write.
  • Deleting is simpler than updating in place, because a delete is idempotent and an update has to be ordered.
  • A slow reader can put an old value back after a write (a stale set). Leases stop it, and the TTL limits its damage.
  • Use both: deletion for freshness, and a TTL as the safety net for what deletion misses.

Next: what happens when many entries expire at the same moment, and every reader decides to rebuild the same value at once.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.