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.
- Need something? Check the notebook first.
- It’s there? That’s a cache hit. Done, fast.
- It’s not there? That’s a cache miss. Go to the library, then write the answer in the notebook.
- Notes get old, so each one has an expiry time, called a TTL (time to live). After that, it’s erased.
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:
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?”
- 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
- 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.
- It buys speed, protection, lower cost and room under API limits.
- Caches live in layers: browser, CDN, application cache, database, operating system. You mostly control the CDN and the app cache.
- The core trade-off is fresh vs fast. Choose each TTL by asking how stale the data may be.
- Cache data that is read often, changes rarely and is costly to get. Skip it for data that must be exactly right, right now.
- 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