Caching Fundamentals and Cache Layers
Learn where caches live (client, CDN, application, database), what makes data cacheable, and how to measure a cache by hit ratio.
Beginner · about 2 hours · difficulty 2/5
Learn first: Latency Numbers and Performance Metrics, Content Delivery Networks (CDNs)
A cache keeps a copy of data in a faster place so you do not recompute or refetch it. Caching is often the single biggest performance win in a design, and also a common source of bugs.
Where caches live
- Client: browser HTTP cache, mobile app local storage.
- CDN / edge: static files and public responses near users.
- Application, in process: a small LRU map inside each server. Fastest, but each instance has its own copy.
- Distributed cache: Redis or Memcached shared by all servers.
- Database: buffer pools and query caches inside the database itself.
What to cache
Good candidates are read-heavy, expensive to compute and tolerant of a little staleness: product pages, user profiles, feed fragments, configuration, results of slow aggregations. Poor candidates: data that changes on every request, or data where a stale read costs money (wallet balance at payment time).
Measuring a cache
- Hit ratio: hits / (hits + misses). A cache with 30 percent hits may cost more than it saves.
- Latency on hit vs miss.
- Memory and eviction rate.
Access patterns usually follow a power law: a small set of keys gets most traffic, which is why caches work.
TTLs and staleness
Every cached item should have a TTL unless you have a reliable invalidation path. Pick TTLs from business tolerance: menu prices maybe 1 minute, restaurant photos maybe a day.
Pitfalls
- Caching without a plan for invalidation.
- Treating the cache as the source of truth; it can be flushed at any moment.
- Caching personalised data under a shared key.
You are ready to move on when you can name the cache layers a request passes through in a typical web app and decide, for five pieces of data, whether to cache them and with what TTL.
Key concepts
- Client and browser caching
- In-process cache
- Distributed cache
- Hit ratio
- TTL and staleness
- Power-law access patterns
Mini project
Add a Redis cache in front of a slow endpoint (simulate a 300 ms query). Expose hit ratio and latency metrics, run a load test with a Zipf-like key distribution, and graph the improvement.
Check yourself
Why might a cache with a 20 percent hit ratio make a system slower overall?
Free resources
- The System Design Primer: cache (GitHub)
- Caching overview (AWS)
- HTTP caching (MDN)