SkillSprout
Chapter 3 · Lesson 1
Intermediate
10 min read

Caching

Overview

A cache is a small, fast copy of data kept close to whoever needs it, so most requests never reach the slow, expensive source. Reading from memory takes about 1 millisecond over the network; a typical database query takes 10 to 50 milliseconds. If 90% of reads can be answered from memory, the database sees one tenth of the traffic and users see much lower latency.

Caching is the single most common optimization in system design interviews, and also the most common source of subtle bugs: stale data, stampedes and hot keys. This lesson covers where to put a cache, how data gets in and out of it, and how to keep it correct enough.

Detailed Notes

What is it?

A cache stores the result of an earlier computation or read so that the next identical request can be answered faster. It lives in fast storage, usually RAM, and is always disposable: if the cache is wiped, the system is slower but still correct, because the original data (the source of truth) lives somewhere else, usually a database.

Three words you will use constantly:

  • Cache hit: the data was in the cache. Fast.
  • Cache miss: the data was not in the cache, so we read the source of truth and usually store the result for next time. Slow.
  • Hit rate (or hit ratio): hits divided by total requests. A 95% hit rate means 95 of every 100 reads are served from memory.

Caches exist at many layers: the browser, a CDN (covered in the next lesson), an application-level in-process cache, and a shared cache cluster such as Redis or Memcached (both are in-memory key-value stores). In interviews, "add a cache" almost always means a shared cache cluster between the application servers and the database.

Why do we need it?

Two reasons: latency (how long one request takes) and load (how many requests the database must absorb).

Suppose a cache read costs 1 ms and a database read costs 20 ms. A miss costs both lookups: 1 ms to check the cache, then 20 ms for the database, 21 ms total.

text
average latency = hit_rate x 1 ms + (1 - hit_rate) x 21 ms

hit rate  0%  ->  21.0 ms   (every read pays both)
hit rate 50%  ->  11.0 ms
hit rate 90%  ->   3.0 ms
hit rate 99%  ->   1.2 ms

The load effect is even more dramatic. At 10,000 reads per second:

text
90% hit rate -> 1,000 reads/s reach the database
99% hit rate ->   100 reads/s reach the database

Going from 90% to 99% looks like a 9-point gain, but it cuts database load by 10x. This is why interviewers ask about hit rate: small changes near the top matter enormously.

What Hit Rate Does to Latency and Database Load
Estimation

Request load

1 mscache read
given
20 msdatabase read
given
21 mscost of a miss
1 + 20
3.0 msaverage at 90% hits
0.9x1 + 0.1x21
1.2 msaverage at 99% hits
0.99x1 + 0.01x21

50% hit rate

5,000 reads/s

reach the database, 11 ms average

Barely helps. Fix key design or size.

90% hit rate

1,000 reads/s

reach the database, 3 ms average

A common minimum target.

99% hit rate

100 reads/s

reach the database, 1.2 ms average

Database is almost idle. Worth the memory.
Key point. The last few points of hit rate are the most valuable: 90% to 99% means 10x less database load.

Cache read 1 ms, database read 20 ms, so a miss costs 21 ms. Traffic is 10,000 reads per second.

Caching works because real traffic is skewed. A few items (a trending product, a celebrity profile) get most of the requests. This is the 80/20 rule: roughly 20% of the data serves 80% of the traffic. You rarely need to cache everything, only the hot part.

How does it work?

Where data comes from: caching strategies

Cache-aside (lazy loading) is the default. The application owns the logic:

  1. Read from the cache.
  2. On a hit, return it.
  3. On a miss, read the database, write the result into the cache (with an expiry), return it.

Writes go to the database, then the cache entry is deleted (invalidated) so the next read reloads fresh data. Pros: only data that is actually requested gets cached; a cache outage only slows you down. Cons: the first read of each item is slow, and there is a short window where cache and database disagree.

Cache-Aside: Miss Then Hit
Request flow
App serverCacheDatabase1GET product:422miss~1 ms3SELECT product 424row~20 ms5SET product:42, TTL 10m6GET product:42 (next user)7hit: row~1 ms, no database

The application owns the logic. The first read fills the cache; the second is served from memory.

Read-through is cache-aside with the loading logic moved into the cache layer: the application only talks to the cache, and the cache fetches from the database on a miss. Same behaviour, less application code.

Write-through: every write goes to the cache and the database together, and the write is acknowledged only after both succeed. Reads are always fresh. The cost is slower writes (two stores) and caching data that may never be read.

Write-back (write-behind): the write goes to the cache only and is acknowledged immediately; the cache flushes to the database later in batches. Writes are very fast and many updates to one key collapse into one database write. The risk is data loss: if the cache node dies before flushing, acknowledged writes are gone. Use it for data you can afford to lose a few seconds of, such as view counters.

Write Strategies: Aside, Through and Back
Comparison

Cache-aside

app updates DB, deletes key

  1. 1

    Write to the database

    source of truth first

  2. 2

    Delete the cache key

    do not update it

  3. 3

    Next read misses

    reloads fresh data

  • Only hot data is cached
  • Cache failure is survivable
  • Short stale window
  • First read is slow

Best default for read-heavy data

Write-through

cache and DB written together

  1. 1

    Write to the cache

  2. 2

    Cache writes the database

    synchronously

  3. 3

    Acknowledge the client

    after both succeed

  • Reads always fresh
  • No data loss
  • Slower writes
  • Caches data never read

When freshness matters more than write speed

Write-back

cache first, DB later

  1. 1

    Write to the cache only

    ack immediately

  2. 2

    Buffer changes

    merge repeated writes

  3. 3

    Flush to DB in batches

    every few seconds

  • Fastest writes
  • Fewer database writes
  • Data lost if cache dies before flush

Counters and metrics, not payments

Key point. Default to cache-aside. Use write-back only where losing a few seconds of writes is acceptable.

They differ in who talks to the database and when a write is acknowledged.

Eviction: what to throw out when memory is full

A cache is smaller than the data set, so when it fills up it must evict (remove) something.

  • LRU (least recently used): evict the item not touched for the longest time. The best general default because recent use predicts future use.
  • LFU (least frequently used): evict the item with the fewest accesses. Better when a few items are permanently popular, but old popular items can linger after they stop being popular.
  • FIFO (first in, first out): evict the oldest inserted item. Simple but ignores usage.
  • TTL (time to live): every entry carries an expiry time, for example 10 minutes. This is not a replacement for LRU; it is a freshness bound that works alongside it.

Invalidation: keeping the cache correct

There is a famous saying that the two hard things in computing are naming and cache invalidation. The practical options:

  • TTL only: accept that data may be stale for up to the TTL. Simple and robust. A 60-second TTL on a product page is usually fine.
  • Delete on write: when the database row changes, delete the cache key. Prefer delete over update: if two writers race, updating the cache can leave the older value stored forever, while a delete simply forces a fresh read.
  • Event-driven: the database publishes a change event and a subscriber deletes the key. More moving parts, but it works across services.

Even with delete-on-write there is a race: a reader misses, reads the old row, a writer updates the row and deletes the key, then the reader stores the old value. A short TTL is your safety net. Always combine invalidation with a TTL.

Failure modes you must name

  • Cache stampede (thundering herd): a very popular key expires, and thousands of concurrent requests all miss at the same instant and hit the database together. Fixes: request coalescing (only one request per key rebuilds it while others wait), adding random jitter to TTLs so keys do not expire together, and refreshing hot keys before they expire.
  • Cache penetration: requests for keys that do not exist (for example random IDs from an attacker) always miss and always hit the database. Fixes: cache the "not found" result for a short time, or put a Bloom filter in front (covered in the probabilistic data structures lesson).
  • Hot key: one key receives so much traffic that the single cache node holding it is overloaded. Fixes: keep a copy in each application server's local memory for a few seconds, or store several copies under keys like item:42#1, item:42#2 and pick one at random.
  • Cache node failure: with plain hash(key) % N placement, losing a node remaps almost every key and the database is flooded. Use consistent hashing (from the partitioning lesson) so only the failed node's share of keys moves.

Interview tip. The most common mistake is saying "I'll add Redis" without saying what is cached, the key, the TTL, and how it is invalidated. Name all four. Another is forgetting that a cache is not durable: never make it the only place data lives unless you have deliberately chosen write-back.

Real-world example

An e-commerce product page. Product details change a few times a day but are read thousands of times per second. The service caches product:{id} with a 10-minute TTL (plus up to 60 seconds of random jitter). When a merchant edits a product, the update service writes to the database and deletes the key. Inventory counts are different: they change on every purchase, so the page does not cache them, or caches them for only 2 to 3 seconds. Different data, different freshness, different TTL.

System design example

You design a news-feed read API doing 50,000 reads/s at peak on a database that comfortably serves 5,000 reads/s. You need at least a 90% hit rate. Plan:

  1. Cache-aside with Redis, key feed:{user_id}, TTL 5 minutes with jitter.
  2. Size the cache: 100 million users x 2 KB per feed is 200 GB for everyone, but only the 20% active in a given hour matter, so about 40 GB, which fits on a handful of nodes. Place keys with consistent hashing.
  3. On a new post, delete the affected feed keys (or let the short TTL handle it, if a minute of staleness is acceptable).
  4. Protect against stampedes with coalescing for viral accounts.
  5. Monitor hit rate, evictions and p99 latency. If the hit rate falls below target, the cache is too small or the TTL too short.

Interview discussion. "I'll use cache-aside: read the cache, on a miss read the database and fill the cache with a TTL. On writes I delete the key rather than update it, to avoid races. I'd target a 95%+ hit rate, which cuts database traffic 20x, and I'd add TTL jitter and request coalescing so a popular key expiring doesn't stampede the database."

Trade-off thinking. Every minute you add to a TTL raises the hit rate and lowers cost, but increases staleness. Write-back gives the fastest writes but risks loss; write-through is safer but slower. Pick per data type: user profile (minutes of staleness OK), account balance (probably do not cache), counters (write-back OK).

Key interview takeaway

Say what you cache, the key, the TTL and the invalidation rule. Quantify the benefit with hit rate (90% to 99% cuts database load 10x). Default to cache-aside with LRU and TTL, then volunteer the failure modes: stampede, penetration, hot keys and node loss.

Real World Example

A product page caches product:{id} for 10 minutes plus random jitter. Editing a product writes to the database and deletes the key. Stock counts are cached for only 2 to 3 seconds because they change on every purchase.

Common Interview Questions

Finished this lesson?

0 of 44 lessons done · 0% of the course