Skip to content
derpx06.dev
WritingExplainersNotesAbout
works on my machineit's always DNSship itLGTMTODO: sleepoff by oneread the docsgit push --force-with-lease404: sleep not foundhave you tried turning it off and on againrubber duck says: explain itpremature optimisationworks on my machineit's always DNSship itLGTMTODO: sleepoff by oneread the docsgit push --force-with-lease404: sleep not foundhave you tried turning it off and on againrubber duck says: explain itpremature optimisation

Learning in public.

A student's notebook on system design, distributed systems and databases. Shared as I learn.

ReadWritingExplainersNotesAbout
ElsewhereGitHubLinkedInHugging FaceLeetCode
Say hellomanaskhairnar1511@gmail.com
derpx06
NORMALmain© 2026 Derpx06Pune, Indiatop ↑
Blog/Foundations

What is caching? Why it makes things fast (and tricky)

A cache is a bet that you will ask for the same thing twice. Here is what happens when the bet wins, loses, or goes stale.

Derpx0615 Oct · 5 min read
Contents
What happens when you ask for something?Why does a tiny miss rate still hurt?Where do caches live?What gets thrown out when the cache is full?What if the copy is too old?So why is invalidation the hard part?What's a stampede?Try it yourselfSources
0% read · 5 min leftBack to top ↑
On this page0%
Contents
What happens when you ask for something?Why does a tiny miss rate still hurt?Where do caches live?What gets thrown out when the cache is full?What if the copy is too old?So why is invalidation the hard part?What's a stampede?Try it yourselfSources

Open a news app and the feed loads quickly. Close it and open it again, and it is often even quicker. A big part of that speed is one simple trick: keep a copy of the answer somewhere close, so nobody has to fetch it again.

That trick is caching. A cache is a small, fast place that holds copies of things you'll probably need again soon. A good way to think about it: a cache is not storage, it is a bet. It bets you will ask for the same thing twice. Every hard part of caching is about what happens when the bet goes wrong.

The corner shop rule

The big supermarket is 10 minutes away. The shop downstairs keeps a few popular items ready, so you grab one in 10 seconds. It cannot stock everything, so it stocks what people keep asking for.

What happens when you ask for something?

Say your app needs a user's profile. First it asks the cache. If the cache has it, that's a hit. If not, that's a miss: the app goes to the slow place (database, disk, another server) and usually saves a copy for next time.

Click Next and follow the same request twice. The first time it misses, the second time it hits.

App
Cache
Database

1st ask: the app checks the cache first

Step 1 of 5
One miss, then one hit. Only the first trip pays the slow price.

Notice the database is skipped on the second ask. The hit rate is just hits divided by total asks, so 9 hits out of 10 asks is a 90% hit rate.

The whole goal is to raise that number. So how much does a few misses matter?

Why does a tiny miss rate still hurt?

The OSTEP operating systems book has a neat example. A memory access costs about 100 nanoseconds and a disk access about 10 milliseconds. Those two are very far apart.

Memory100 ns
Disk10,000,000 ns
OSTEP's example numbers: 100 ns for memory, 10 ms (10,000,000 ns) for disk. The scale is logarithmic. Bars use a log scale.

Disk is about 100,000 times slower here. So with a 90% hit rate the average access works out to about 1 millisecond. At 99.9% it's about 10.1 microseconds, roughly 100 times faster.

90% hit rate1000 µs
99.9% hit rate10.1 µs
Average access time (OSTEP's example: 100 ns memory, 10 ms disk)

Going from 90% to 99.9% sounds small, but it is a huge win. The slow trip is so slow that even rare misses dominate the average.

So caches are great. But they're small. What happens when one fills up?

Where do caches live?

Same idea, different places. They all keep copies close. They differ in how close and who manages them.

CPU cache (tiny, inside the chip)
Browser cache (your own device)
Redis (a fast server in front of a database)
The database or origin server (the slow truth)
Each layer is a copy of the layer below it.

The OSTEP chapter explains that this works because programs show locality. Things used recently get used again soon (temporal), and things near a used item get used soon too (spatial). No locality, no point in caching.

What gets thrown out when the cache is full?

A cache is small on purpose. When it's full and something new arrives, something old has to go. That's eviction, and the rule for picking the victim is the eviction policy.

LRU (least recently used) removes the item you haven't touched for the longest time. It is like clearing phone storage: the app you have not opened in months goes first.

PolicyWho gets evicted
LRUThe item unused for the longest time
LFUThe item used the fewest times
RandomAny item at all

Redis offers all of these as settings (allkeys-lru, allkeys-lfu, allkeys-random). Its docs call allkeys-lru a good default when you have no reason to pick another. The docs also explain that Redis uses an approximation of LRU: it samples a few keys and evicts the oldest of those, because exact LRU costs more memory.

Eviction handles "no space". But what about a copy that's simply too old?

What if the copy is too old?

TTL (time to live) handles that. You give each copy a countdown, and when it hits zero the copy is gone.

The browser does this with HTTP headers. Cache-Control: max-age=3600 means the copy is fresh for 3600 seconds. After that it's stale, and per MDN the cache has to check with the server before reusing it.

1Copy is fresh
2max-age runs out
3Copy is stale
4Ask server: still valid?
5304 Not Modified, reuse it (or 200 with new data)
How a browser checks a stale copy, using an ETag.

That check is cheap. The browser sends the copy's ETag (a version label) in If-None-Match. If nothing changed, the server replies 304 Not Modified with no body.

So TTL keeps things fresh. But what if the original changes before the timer ends?

So why is invalidation the hard part?

Cache invalidation means making sure copies don't outlive the truth. The original changes, and every copy is now quietly wrong. That is stale data.

In syncPrice in database: 500. Price in cache: 500.
→
StalePrice in database: 450. Price in cache: still 500.

You usually cannot see which copies are wrong, and the same fact might sit in a CPU, a browser, a CDN and Redis all at once.

Long TTL

Fewer trips to the slow source. Faster and cheaper.

Long TTL

Stale data hangs around longer.

A short TTL is the reverse: fresher data, more misses. There is no free setting, which is why this problem is famous.

MDN's best trick sidesteps it. For files like bundle.v123.js, put a version in the filename. When the file changes, the name changes, so the old copy is never asked for again.

What's a stampede?

Say a popular item expires and 1,000 requests arrive in the same second. All of them see a miss, and all 1,000 hit the database together. That is a cache stampede: a crowd all asking for the same thing at the same moment.

Hot item expires
Many requests miss together
All hit the database
Database slows down
Everything misses even longer
↺ repeat
A stampede feeds itself.

Two common fixes (this part is a summary, not from the sources below): let only one request rebuild the item while the others wait, or add a bit of randomness to TTLs so items don't all expire together.

Try it yourself

Install Redis, run redis-server, then use redis-cli in another terminal.

Bash
SET news "v1" EX 10
GET news
TTL news

EX 10 means "expire in 10 seconds". TTL shows the seconds left. Wait 10 seconds, run GET news again, and you'll get nothing back (a miss). To see real numbers on a busy server, run INFO stats and read keyspace_hits and keyspace_misses.

You can also see the browser side. Open DevTools, go to the Network tab, reload a site and look at the Cache-Control header on a response.

Key takeaways
  • A cache is a bet that you'll ask for the same thing again, not a second database.
  • Hits are fast, misses are slow, and even a small miss rate dominates the average.
  • Eviction (LRU) handles a full cache and TTL handles old data.
  • Invalidation is hard because copies sit in many places and you can't see which are stale.

Sources

  • Redis docs: Key eviction
  • MDN: HTTP caching
  • Arpaci-Dusseau, Operating Systems: Three Easy Pieces, chapter 22: Beyond Physical Memory: Policies
ShareXLinkedInEmail
Written by Derpx06A developer who builds AI search tools and the code around them. I explain what I got wrong first, so you can skip it. Spotted a mistake? Tell me — corrections get credited.
Foundations · 3 minWhy is 0.1 + 0.2 not 0.3 in code?Foundations · 4 minHow does Git work inside? (Snapshots, not changes)Foundations · 5 minHow do maps apps find the fastest route?
Start here
01Why is 0.1 + 0.2 not 0.3 in code?02How does Git work inside? (Snapshots, not changes)03How does your computer know the time? (And why it can be wrong)