Caching explained: what a cache is, why it matters and what can go wrong

A cache keeps a copy of slow-to-get data somewhere fast, so you don't fetch it again and again. Learn how a cache hit and miss work, where caches live, the one trade-off behind every cache, and the four ways a cache can hurt you.

A person sits at a desk with an open notebook labelled 'cache, about 1 ms'. Far away, at the end of a long dotted path, stands a library building labelled 'database, 10 to 100 ms'. A short green arrow goes from the person to the notebook; a long grey arrow goes to the library. A banner at the top says 'Check the notebook first', and a note by the library says 'Not in the notebook? Walk to the library, then write it down.'
Fig. 1 — A cache is a notebook on your desk. You still have the library, but you only walk there when the notebook doesn't have the answer.

Imagine a restaurant where every order means driving to the farm for vegetables. The food would be great, and it would take two hours. Real kitchens keep the common things close at hand, and only go to the farm when they run out.

A system without a cache works like that farm trip. Every request goes all the way to the database, an outside API, or a heavy calculation, even when the answer was the same a second ago.

A cache is the fix. It keeps a copy of data somewhere fast, usually in memory, so the next request can skip the slow trip.

Here’s how big the gap is:

Where the data comes from Rough time
Memory on the same machine ~0.0001 ms (100 nanoseconds)
A cache server like Redis, over the network ~0.5–1 ms
A database query ~5–50 ms
An outside API ~50–200 ms
“Caching trades memory for speed. You keep a copy close by, and accept that the copy might be a little out of date.”

This article opens the Performance & caching (deep) thread. We’ll start with the basics: how a cache works, where it lives, and what can go wrong.

How a cache works: hit or miss

Think of a cache as a notebook on your desk, and the database as a library across town.

  1. Need something? Check the notebook first.
  2. It’s there? That’s a cache hit. Done, fast.
  3. It’s not there? That’s a cache miss. Go to the library, then write the answer in the notebook.
  4. Notes get old, so each one has an expiry time, called a TTL (time to live). After that, it’s erased.
A flow diagram. A request arrives at the app. The app asks the cache for product:42. Top path, cache hit: the cache returns the product in about 1 ms and the app replies. Bottom path, cache miss: the cache has nothing, so the app queries the database, which takes about 20 ms, then stores the result in the cache with a TTL of 1 hour, and replies. A note says the next request for product:42 will be a hit.
A hit is a quick answer from the cache. A miss goes to the database once, then saves the answer for everyone after.

In code, it’s only a few lines. This pattern is called cache-aside, because the app checks the cache on the side before going to the database:

// Java · Spring Boot + Redis
public Product getProduct(Long id) {
    String key = "product:" + id;

    Product cached = redis.opsForValue().get(key);
    if (cached != null) return cached;              // hit: about 1 ms

    Product product = productRepo.findById(id)      // miss: go to the database
        .orElseThrow(() -> new NotFoundException("Product not found"));

    redis.opsForValue().set(key, product, Duration.ofHours(1));  // save it, with a TTL
    return product;
}

If 95% of requests are hits, the database sees only 1 request in 20. A database that was running at 90% CPU can drop to around 10%.

What a cache really buys you

Speed is the obvious win, but there are four:

  • Speed. Answers in about a millisecond instead of tens of milliseconds.
  • Protection. In a flash sale, 100,000 people open the same product page at 12:00. With a cache, the first request loads the product and the rest are served from memory. The database barely notices.
  • Lower cost. Fewer database reads means a smaller database and fewer read replicas.
  • Staying inside API limits. If a weather API allows 1,000 calls an hour and you have 10,000 users, cache each city’s weather for 30 minutes. Now you make one call per city, not one per user.

Where caches live

Caches aren’t one thing in one place. A single request can pass through several, each closer to the user than the next:

Five layers from the user to the disk, drawn as steps. 1, browser cache, on the user's device, for images, CSS and JavaScript, no network trip at all. 2, CDN, edge servers around the world, for static files and some pages, about 10 to 50 ms. 3, application cache such as Redis or Memcached, for query results, sessions and computed data, about 1 ms, and you have full control. 4, database cache, inside the database, for recently used data and query plans. 5, operating system cache, in the server's memory, for recently read files, managed automatically. Green tags mark the CDN and the app cache as the two layers you control. An arrow notes that the closer a layer is to the user, the faster it is.
The closer to the user, the faster the answer, and the less control you have over it.

As the designer, you mostly control two layers: the CDN (for static files) and the application cache like Redis (for data). The browser, database and operating system caches help too, but they mostly look after themselves.

The one trade-off: fresh or fast

Every cache has the same weakness: the copy can go stale. The database changes, and the cache doesn’t know.

So every caching decision comes down to one question:

“How old can this data be before something goes wrong?”
A horizontal scale from 'always fresh, slow' on the left to 'very fast, may be stale' on the right. Markers along it: no cache, short TTL of seconds, medium TTL of minutes, long TTL of hours, and days. Examples placed under each: stock prices and bank balances need seconds or no cache; user profiles are fine for minutes; product descriptions are fine for hours; logos and CSS are fine for days.
Pick the TTL from how stale the data is allowed to be, not from how fast you want to go.
  • Stock prices and bank balances: seconds matter. Use a very short TTL, or don’t cache.
  • User profiles: a few minutes old is fine.
  • Product descriptions: hours are fine.
  • Logos, CSS, images: days are fine.

When to cache, and when not to

A cache helps when:

  • the same data is read many times,
  • it rarely changes,
  • it’s slow or expensive to get,
  • and a little staleness is acceptable.

Skip the cache when:

  • the data changes all the time (the copy is stale the moment you save it),
  • every read is different, like unique search queries, so you never get a hit,
  • you need it exactly right, right now, like a bank balance,
  • or it’s already fast and rarely read.

A simple rule of thumb: if data is read 10 times or more for every write, it’s a good candidate. If it’s read fewer than 2 times per write, a cache will mostly add trouble.

And you can’t cache everything anyway. A 1 TB database with a 16 GB cache can hold under 2% of the data. That’s fine, because a small slice of hot data usually takes most of the traffic.

What breaks, and how to fix it

A cache is one more moving part, and it brings its own failures:

What breaks What you see The fix
The cache server dies Every request falls through to the database at once, and the database goes down too Treat cache errors as a miss, not a crash. Add a circuit breaker so a dead cache is skipped quickly. Run Redis with a replica
A popular key expires (cache stampede) 1,000 requests miss at the same moment and all hit the database for the same row Let only one request reload it (a short lock with SETNX), while the others wait briefly or get the old value
Stale data breaks business rules An admin cuts a price from ₹100 to ₹50, but the cache still says ₹100, and customers are charged the wrong amount Delete the cache entry when you write to the database. For money, use a very short TTL or read straight from the database
The cache fills memory Redis runs out of memory and crashes, or rejects writes Always set a TTL, and set a memory limit with an eviction policy: maxmemory 2gb and maxmemory-policy allkeys-lru (drop the least recently used keys)

Here’s the first fix in code. The cache is a helper, so if it’s down, the app should still work:

// Java · if Redis is down, go to the database instead of failing
Product cached = null;
try {
    cached = redis.opsForValue().get(key);
} catch (Exception e) {
    log.warn("Cache unavailable, reading from database", e);
}
if (cached != null) return cached;
return productRepo.findById(id).orElseThrow();

Puzzle 1: the discount nobody can see

The prices changed in the database, but nobody cleared the cache. Customers were reading old copies until their 1-hour TTL ran out.

That’s why it was hard to spot: there was no cache in testing, admins skipped the cache, and the bug fixed itself after an hour.

The fix: whenever you change data, also remove its cached copy. For a change that touches every product, a neat trick is to put a version in the key, like product:v2:42. Bump it to v3, and every old entry is simply never read again, and expires on its own. (Avoid Redis’s KEYS product:* to find and delete them: on a big cache it blocks Redis while it scans.)

Puzzle 2: the cache that took the site down

The new cache was empty. Every request was a miss, so all of today’s traffic, ten times what the database was built for, hit the database at once. It fell over.

Once you rely on a cache, the cache is part of your capacity, not just a speed-up. The fix: never put an empty cache in front of real traffic. Warm it first by loading the most popular items (say, the top 1,000 products) before traffic arrives, and move traffic over gradually.

Key takeaways

  1. A cache keeps a copy of slow data somewhere fast. A hit is answered from the copy; a miss goes to the source and saves the answer.
  2. It buys speed, protection, lower cost and room under API limits.
  3. Caches live in layers: browser, CDN, application cache, database, operating system. You mostly control the CDN and the app cache.
  4. The core trade-off is fresh vs fast. Choose each TTL by asking how stale the data may be.
  5. Cache data that is read often, changes rarely and is costly to get. Skip it for data that must be exactly right, right now.
  6. Plan for failure: a dead cache, a stampede, stale data and full memory. Once you depend on a cache, it’s part of your capacity.

This opens the Performance & caching (deep) thread. We know what a cache is. Next, we’ll look at caching strategies: cache-aside, read-through, write-through and write-back, and how each keeps the cache and the database in step.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.