What is caching, and where can the cache live?
Keeping a copy of data somewhere faster and closer than its original source. The layers where a cache can live, from the browser to the database, how caches get filled and invalidated, and the problems they bring.
In one sentence
A cache stores copies of data that are expensive to get (slow query, far away server) so the next request can be answered from somewhere fast and close.
The idea
Reading from memory takes nanoseconds, from a database across the network milliseconds, and from a server on another continent a hundred milliseconds or more. Most apps also read the same popular data over and over: the trending video, the homepage, a user's profile.
A cache exploits that: the first request pays the full price, the next ones are served from the copy. Below, each request stops at the first layer that has the item. Toggle layers and watch the hit ratio, the latency and the load on the database.
Where can the cache live?
There isn't one cache. There is a chain of them between the user and the data, and a single request can cross several.
CDN / edge
What it stores
Copies of static files and cacheable responses in data centers around the world.
Example
Netflix and YouTube serve video chunks from servers near you.
Great for
Images, video, JS/CSS, public API responses.
Watch out
Personalized data must not be cached for everyone.
How data gets into the cache
| Pattern | How it works | When |
|---|---|---|
| Cache-aside (lazy loading) | App checks the cache; on a miss it reads the DB and stores the result | The default for most apps |
| Read-through | The cache itself loads from the DB on a miss | When a library or managed cache supports it |
| Write-through | Every write goes to the cache and the DB together | Data that is read right after it's written |
| Write-back (write-behind) | Writes go to the cache and are flushed to the DB later | Very high write rates where losing a few seconds is acceptable |
async function getUser(id) {
const cached = await redis.get(`user:${id}`);
if (cached) return JSON.parse(cached); // hit
const user = await db.users.findById(id); // miss
await redis.set(`user:${id}`, JSON.stringify(user), "EX", 300);
return user;
}Invalidation: the hard part
A cache is a copy, and copies go stale. You need a rule for when a cached value stops being valid.
- TTL (time to live): every entry expires after N seconds. Simple and safe; data can be stale for up to N seconds.
- Explicit invalidation: when the data changes, delete or update the cache key. Fresh, but easy to forget one place.
- Versioned keys:
profile:42:v7. Changing the version makes old entries unused.
When the cache is full, an eviction policy decides what goes: LRU (least recently used) is the common default, LFU (least frequently used) keeps long-term favourites.
When to cache, and when not to
Cache it
- Read far more often than written
- Expensive to compute or fetch
- Fine if it's a few seconds old (feeds, counts, catalogs)
Think twice
- Must always be exact (bank balance at payment time)
- Changes on almost every request
- Rarely read twice, so the hit ratio would be low
Key takeaways
- 01A cache trades freshness for speed by serving copies close to the user.
- 02Caches live at every layer: browser, CDN, proxy, app memory, Redis, database.
- 03Cache-aside with a TTL is the default; add explicit invalidation for data that must update fast.
- 04Measure the hit ratio: a cache that rarely hits only adds complexity.
Check your understanding
1 of 3
What is a cache?
Related concepts
Read-heavy vs write-heavy
A read-heavy part is read far more than it changes (a video page); a write-heavy part receives a constant flood of new data (view counts, analytics). Each one needs different tools.
7 min read →Precomputing values
Precomputing means doing the expensive work at write time (or on a schedule) and storing the result, so every read is a cheap lookup instead of a fresh calculation.
7 min read →Read replicas
A read replica is a copy of the database that receives every change from the primary and answers read queries, so you can add read capacity without touching writes.
7 min read →CDN
A CDN is a cache spread around the world. Users download images, video, scripts and even pages from the nearest edge server; only the first request in each region goes all the way to your origin.
6 min read →