Keep a copy of popular data in a fast place, so you do not fetch it from the slow place every time.
A cache is a fast, small place where we keep a copy of data that people ask for again and again. Next time, we answer from the copy and skip the slow work.
Caching means saving the result of slow work (a database query, a calculation, a file download) so we can reuse it. The saved copy is kept in something faster or closer to the user.
A request passes many places. Each one can keep a copy.
| Where | What it keeps | Example |
|---|---|---|
| Browser | Images, scripts, styles, API answers | Your browser skips downloading the logo again |
| CDN | Static files and sometimes pages, in many cities | A video chunk served from a nearby city |
| App memory | Small, hot objects inside one server | A list of countries loaded once |
| Distributed cache | Data shared by many app servers | User sessions, product details in Redis |
| Database | Recently read pages and query plans | The database keeps hot rows in RAM |
| CPU | Tiny, super-fast copies of memory | L1, L2, L3 caches (you do not manage these) |
Each step down is much slower but much bigger and cheaper. Caching is about staying high on this ladder. The numbers are rough and change with hardware.
Times are illustrative (cache 1 ms, database 50 ms). Real numbers depend on your hardware and network.
Average time = hit ratio ร cache time + (1 โ hit ratio) ร database time.
| Hit ratio | Average time (cache 1 ms, database 50 ms) | Database requests per 1000 |
|---|---|---|
| 0% | 50 ms | 1000 |
| 50% | 25.5 ms | 500 |
| 90% | 5.9 ms | 100 |
| 99% | 1.5 ms | 10 |
| Term | Meaning in easy words |
|---|---|
| Cache | A fast, small store that keeps copies of data |
| Hit / Miss | The data was / was not in the cache |
| Hit ratio | Share of requests answered by the cache |
| TTL | Time to live: how long a cached copy is allowed to live before it expires |
| Eviction | Removing an item to make room when the cache is full |
| Invalidation | Removing or updating a cached item because the real data changed |
| Stale data | A cached copy that no longer matches the real data |
| Cold cache | An empty cache, so almost every request is a miss |
| Warm cache | A cache that already holds the popular items |
| Key | The name used to find an item in the cache |
| Locality of reference | The habit of programs to reuse the same or nearby data |
| Choice | We gain | We lose |
|---|---|---|
| Bigger cache | More hits | More memory cost |
| Longer TTL | More hits, less database load | Staler data |
| Shorter TTL | Fresher data | More misses |
| Cache closer to the user | Lower latency | Harder to invalidate |
| Cache the whole page | Biggest speed-up | Less flexible, one change can ruin it all |