AlgoViz

Caching Strategies and Eviction

medium 25 min

Place fast memory between applications and persistent storage to slash read latency and protect databases.

Video lesson · Chapter 1 of 5

One profile, a thousand visits

0:00 / 3:43

Cache-aside

1:17Reel

Caching Strategies and Eviction in one picture
Caching Strategies and Eviction in one picture

Theory

Read or listen first. About 1 min.

What it is

A cache is a small, fast place that keeps copies of data whose original lives somewhere slower. When the copy is there, you get an answer quickly. When it is not, you fetch the original and usually keep a copy for next time.

Caches work because people ask for the same things again. A small part of the data gets most of the requests, so a small fast store can answer most of them.

Why it exists

Reading from memory is thousands of times faster than reading from a disk, and nearer is faster than farther. A cache shortens the wait and takes load away from the slower store behind it.

The price is that there are now two versions of the truth. Most of the difficulty in caching is deciding how old a copy may be, and how to remove it when the original changes.

A short history

  1. 1965

    Maurice Wilkes describes a small "slave memory" in front of a larger one, the idea behind processor caches.

  2. 1968

    The IBM System/360 Model 85 is the first commercial computer with a cache memory.

  3. 1990s

    The web brings browser caches, proxy caches and, from 1998, Akamai's content delivery network.

  4. 2003

    Brad Fitzpatrick writes memcached for LiveJournal, sharing spare memory between web servers.

  5. 2009

    Salvatore Sanfilippo releases Redis, an in-memory store with richer data types.

Words to know

Hit and miss
The copy was there, or it was not.
Hit rate
The share of requests answered by the cache.
TTL
Time to live: how long a copy may be used.
Eviction
Removing something to make room.
Invalidation
Removing a copy because the original changed.
Stale
Older than the original.
Stampede
Many requests missing the same key at once.

How it works

Step through the idea, or press Play.

Step 1 of 3

Lookup. Application checks in-memory cache before hitting the primary datastore

Understand it

Disk and network lookups are orders of magnitude slower than reading directly from RAM. Caching inserts an in-memory layer between compute and persistent storage to eliminate database bottlenecks, but introduces trade-offs around stale data, memory pressure, and operational complexity.

Start here

The pencil case

In a drawing class, all pencils live in a cupboard down the hall. Walking there for every line would take all day, so Noor keeps a few in a pencil case on the desk. The case is a cache, and the cupboard is the database.

Pencils close at hand
Drawing classCUPBOARDpencil caseMiss: walk to the cupboard

Five ideas in one picture

  • Copy

    The case holds copies. The cupboard stays the place of record.

  • Near

    It is fast because it is close and small.

  • Few

    It works because the same few pencils are needed again and again.

  • Full

    Space is limited, so something has to leave.

  • Old

    A copy can fall behind the original.

The same idea, bigger

The library desk

Imagine a librarian. Every book lives on far shelves, but a small shelf on the desk holds the few that people keep asking for. That desk shelf is a cache.

A small shelf that saves long walks
FAR SHELVESDESK SHELFMiss: walk to the far shelves

The whole picture

Where a cache can sit

Each layer answers what it can

A request tries the browser or app cache on the user's device, then the CDN edge cache, then inside our system the in-process cache of one app server, then Redis shared by all servers, and last the database with its own buffer cache.
The nearer the copy, the faster the answer and the harder it is to update. Only misses travel on.

What each layer is good at

LayerShared byGood forWatch out
Browser or appOne userImages, scripts, the user's own dataYou cannot delete it remotely; use versioned names
CDN edgeUsers nearbyPublic contentPrivate data, purge delay
In-processOne serverA few very hot itemsServers disagree for a moment
Redis or MemcachedAll serversMost application dataA network trip; one hot key on one node
Database bufferAll queriesPages read oftenStill runs the query

What to keep

What is worth caching

Good to cache

  • Read many times, changed rarely
  • Slow to compute or far away
  • Fine if it is a few seconds old
  • Small next to its traffic

Leave it alone

  • Read once and never again
  • Must be exact for a decision, such as a payment
  • Different for nearly every request
  • Already fast with an index

The key decides who shares the copy

DataKeyExpires after
Public product pageproduct, id, language5 minutes
One person's ordersorders, person id, page number1 minute
Search resultssearch, sorted filters30 seconds
Feature settingssettings, version numberUntil the version changes
Example times. Everything that changes the answer belongs in the key.

Numbers

How much does a hit rate buy?

10,000 reads a second, seen from the database

Hit rateReads at the databaseCompared with no cache
0%10,000 a secondall of it
50%5,000 a seconda half
90%1,000 a seconda tenth
95%500 a seconda twentieth
99%100 a seconda hundredth
Going from 90% to 99% looks small and cuts the database load by ten.

Will the database hold?

100,000,000100,000=1,000/s average,3×1,000=3,000/s peak,3,000×(1−0.9)=300/s\frac{100{,}000{,}000}{100{,}000} = 1{,}000/s\ \text{average}, \quad 3 \times 1{,}000 = 3{,}000/s\ \text{peak}, \quad 3{,}000 \times (1 - 0.9) = 300/s
100 million reads a day, peak three times the average, 90% hits. The database must serve 300 reads a second at peak, and 3,000 if the cache is empty.

How much memory?

1,000,000 hot items×2 KB=2 GB,2 GB×1.5=3 GB1{,}000{,}000\ \text{hot items} \times 2\ \text{KB} = 2\ \text{GB}, \qquad 2\ \text{GB} \times 1.5 = 3\ \text{GB}
Assumptions: one million items are asked for often, 2 KB each, and half as much again for keys, bookkeeping and room to grow.

The default

Cache-aside, drawn

Reading and updating

Reading: the app asks Redis first; on a miss it reads the database and stores the result in Redis with a TTL. Updating: the app changes the database first and then deletes the key in Redis.
Blue reads, pink writes, orange fills the copy. Dashed steps happen only on a miss.

A miss, then a hit

Average read time

t=h⋅tcache+(1−h)(tcache+tdb),h=0.9: 0.9⋅1+0.1⋅11=2 mst = h \cdot t_{cache} + (1 - h)(t_{cache} + t_{db}), \qquad h = 0.9:\ 0.9 \cdot 1 + 0.1 \cdot 11 = 2\ \text{ms}
Assuming 1 ms for the cache and 10 ms for the database. At 90% hits the average falls from 10 to 2 ms, and the database sees a tenth of the reads.

Architecture

Core caching patterns

Each pattern has its own page: cache-aside, write-through, write-back, and choosing a cache pattern puts them side by side.

  1. 1

    Cache-aside (Lazy loading)

    The application orchestrates both cache and database. It queries the cache first. If missed, it reads from the database, writes the result to the cache, and returns. On writes, the application updates the database and deletes (invalidates) the cache entry.

  2. 2

    Write-through

    The application writes directly to the caching layer, which synchronously persists to the database. The client only receives confirmation once both writes succeed. Reads of what was saved are fast, and the caller waits for both writes.

  3. 3

    Write-back (Write-behind)

    The application writes immediately to the cache and receives an immediate acknowledgement. A background process batches updates and flushes them asynchronously to disk. Offers maximum write throughput but risks data loss if the cache node crashes before persistence.

Writing through and writing back

Write-through: the app writes to the cache, which writes to the database and waits before answering. Write-back: the app writes to the cache and is answered; batches reach the database later.
The dashed arrow is the risk: until that batch lands, the cache holds the only copy.

Why deleting is still not perfect

Rare, but real: an old read is stored after the delete. A short TTL limits the damage; versioned writes or a lease prevent it.

Trade-offs

Write pattern trade-offs

Cache-aside & Write-through

  • Cache-aside only caches items actually queried by users.
  • Cache-aside can fall back to the database when the cache fails, if the database can take the load.
  • Write-through keeps cache and storage in step, as long as every write goes through it.
  • Neither keeps the only copy of acknowledged data in memory.

Write-back

  • Unflushed dirty records in memory are lost if a cache instance crashes.
  • Increases architectural complexity with write-queues and background sync workers.
  • Secondary consumers reading directly from the database observe delayed state.

Memory Management

Eviction policies

This is the short version. Cache eviction compares the policies in depth, and cache TTL is about expiry times.

Which policy?

Caches run on bounded memory. When max capacity is reached, an eviction policy decides which entries to purge to make room for new items.

  1. 1

    Least Recently Used (LRU)

    Discards the key that has not been read or written for the longest duration. Well-suited for temporal locality where recently accessed keys are likely to be accessed again.

  2. 2

    Least Frequently Used (LFU)

    Discards the key with the lowest total access counter. Well-suited for identifying consistently popular data, though historical counts can prevent newer hot items from staying cached.

  3. 3

    Time to Live (TTL)

    Associates an expiration timestamp with each key. Expired keys are cleared passively upon lookup or actively via periodic scans.

  4. 4

    First In First Out (FIFO)

    Discards keys strictly in the chronological order they were inserted, regardless of ongoing read interest.

Failure

When a hot key expires

The drawing shows the problem and one cure. Thundering herd covers the others.

Stampede, and one refresher

Top: the hot key expires and three app servers send the same query to the database. Bottom: one server wins a lock in Redis and runs the query; the other two get the old copy.

One server refreshes

Failure

What else goes wrong

ProblemWhat happensFirst thing to do
StampedeOne hot key expires and everybody asks the databaseOne refresher, old copy for the rest
PenetrationKeys that do not exist are asked for again and againRemember the empty answer for a short time
AvalancheMany keys expire in the same second, or the cache restarts emptySpread the expiry times, limit misses in flight
Hot keyOne key gets more reads than one cache node can serveKeep it in app memory for a second, or copy it
Stale copyA delete was lost or a race stored an old valueTTL on everything, retry deletes
Cache downAll reads fall throughShort timeouts, a limit in front of the database
Cache consistency goes deeper into stale copies, distributed caching into many nodes.

Operate it

What to measure

  1. 1

    Hit rate, per kind of data

    One average hides a page with 20% hits behind a page with 99%.

  2. 2

    Reads that reach the database

    This is the number the database feels.

  3. 3

    Evictions and memory

    Many evictions and a falling hit rate mean the cache is too small.

  4. 4

    Time per cache call, slowest 1%

    A cache that is slow is worse than none, because every request pays for it first.

  5. 5

    Age of copies

    Compare a sample of copies with the originals and alert when they differ for too long.

The hit rate is low: why?

Beyond the server

Caching answers over HTTP

Browsers and content delivery networks follow rules that travel with the answer, such as how long it may be kept. API caching explains those headers.

Summary

The whole topic in one minute.

A cache keeps copies of popular data somewhere faster or nearer. It cuts waiting time and protects the store behind it.

Cache-aside is the usual starting point: read the cache, fall back to the database, fill the cache, and delete the key on a change. Choose how old data may be, choose what to evict, and plan for the moment a hot key disappears.

  • Cache-aside is the default choice for read-heavy workloads with tolerable stale reads.
  • Write-through puts the new value in the cache at once, if all writes use it. The caller waits for both writes.
  • Write-back delivers extreme write performance for ingestion pipelines but introduces risk of data loss.
  • LRU is a common first choice for eviction, while a TTL limits how old a copy can get.
  • Protect the database: one refresher for a hot key, short entries for missing keys, and a limit on misses in flight.

Sources