Caching
Keep a copy of often-needed data somewhere fast, so you don't redo expensive work.
What is it?
Some operations are expensive: a complex database query, a slow calculation, a call to a faraway service. Redoing that work every time the same result is needed is wasteful.
Caching stores a copy of the result somewhere fast (often memory) so later requests can reuse it instead of recomputing it.
Explain like I'm 10
It's like keeping a jug of cold brew in the fridge instead of brewing a fresh pot for every cup. Grabbing a cup is faster; you just have to refill the jug now and then.
Examples
A simple cache in front of a slow lookup
const cache = new Map();
async function getUser(id) {
if (cache.has(id)) {
return cache.get(id); // fast — no database call
}
const user = await database.query("SELECT * FROM users WHERE id = ?", [id]);
cache.set(id, user);
return user;
}How it works
Before doing expensive work, the system checks the cache:
- Cache hit: the data is there and is returned immediately. - Cache miss: the expensive work runs and the result is stored in the cache for next time.
Cached data usually gets an expiration time so it doesn't stay stale forever.
Request comes in
↓
Is it in the cache?
↓yes ↓no
return cached do expensive work
value ↓
store result in cache
↓
return resultWhy does it exist?
Caching greatly reduces load on slow or expensive resources (like databases) and makes responses feel instant. The cost is sometimes serving slightly outdated data, which is usually fine for data that doesn't change every second.
When to use it
Use caching when the same expensive result is requested again and again and doesn't need to be perfectly fresh every time: a product page, a popular search, a computed report.
When not to use it
Don't cache data that changes constantly and must always be exact, like a live account balance mid-transaction. If you must, keep the cache lifetime very short and invalidate it whenever the underlying data changes.
Common mistakes
Caching fast-changing data without a short enough expiration, so users see stale information.
Forgetting to invalidate (clear) a cached value when the underlying data changes.
Putting sensitive or user-specific data in a shared cache without keeping it separate per user.
Practice exercises
- Easy:
Explain the difference between a 'cache hit' and a 'cache miss'.
- Medium:
Add an expiration time to the cache example above, so cached values are only reused for 60 seconds.
- Hard:
Describe a real case where stale cached data could cause a user-facing problem, and how you'd reduce the risk.
Interview questions
What is caching, in simple terms?
Storing a copy of a result somewhere fast, so repeated requests don't redo expensive work.
What is cache invalidation, and why is it considered hard?
Removing or updating cached data once it's no longer accurate. It's hard because you must reliably track every way a cached value can become stale.
What's a trade-off caching introduces?
It can serve slightly outdated ('stale') data for a while, in exchange for much faster responses and less load on the underlying system.
What is the cache-aside (lazy-loading) pattern?
The app checks the cache first. On a miss, it reads from the data source itself, writes the result into the cache, then returns it. The cache only holds what's been requested, and the app (not the cache) owns this logic.
What is write-through caching, and how does it differ from cache-aside in when data enters the cache?
In write-through, every write updates the cache and the underlying store together in one operation, so the cache always has the latest value. In cache-aside, data only enters the cache on a later read after a miss; a write alone doesn't populate it.
What is write-back (write-behind) caching, and what risk does it introduce that write-through avoids?
Writes go to the cache and are confirmed right away; the write to the underlying store happens later, asynchronously. It's faster, but if the cache crashes before that write finishes, the data is lost. Write-through avoids this by confirming only once both are durably updated.
What is "write-around" caching, and when would you use it?
Writes go straight to the underlying store and skip the cache; the cache fills later on reads (like cache-aside). It suits data written once and rarely re-read soon after, so the cache doesn't fill with values nobody requests.
What is cache stampede (thundering herd), and give a concrete scenario where it happens.
When a popular key expires or is evicted, many concurrent requests miss at once and all hit the data source to recompute the same value. For example, a busy product page's entry expires just as a traffic spike hits, sending thousands of identical queries for the same row to the database.
Name two mitigations for cache stampede.
A lock ("single-flight") so only one request recomputes a missing value while others wait for its result. Or random jitter on TTLs so many entries don't expire at the same instant.
What's the tradeoff in choosing a very short TTL versus a very long one?
A short TTL keeps data fresher but causes more misses, pushing load back onto the underlying system and shrinking caching's benefit. A long TTL maximizes hits and load reduction but serves stale data for longer after the data changes.
What is "stale-while-revalidate," and what problem does it solve?
When a cached value expires, the request still gets the stale value immediately while a background request refreshes it. The user doesn't wait on the slow recompute; the cost is that one response is slightly outdated.
What is negative caching, and why cache the absence of something?
Caching the fact that a lookup found nothing (e.g. "no user with this id"), so repeated requests for the same missing value don't keep hitting the expensive system just to hear 'not found'. Useful when misses are frequent, like repeated lookups of invalid or deleted ids.
What's the difference between LRU and LFU eviction policies, and when would LFU beat LRU?
LRU (Least Recently Used) evicts what hasn't been accessed for the longest time. LFU (Least Frequently Used) evicts what has been accessed the fewest times overall. LFU wins when a truly popular item goes briefly unused: LRU might evict it in favor of a rarely used item that was touched more recently.
What happens if a cache runs out of memory and no eviction policy is deliberately chosen?
Most caches fall back to a default eviction policy (often LRU) rather than refusing writes or crashing. But relying on an unchosen default means you never decided which data to keep, and something important can be silently evicted under memory pressure.
What's the difference between a local (in-process) cache and a distributed cache like Redis, and what does each trade off?
A local cache lives in one server's memory: very fast with no network hop, but only that server sees it and it's lost on restart. A distributed cache is a separate shared service all servers use: consistent across servers, but it adds a network round trip and another dependency to run.
Scenario: 10 app servers each keep their own local in-memory cache. What consistency problem does this create, and how would a distributed cache change it?
Each server can hold a different, separately stale version of the same key, so a user's answer depends on which server handles the request. A shared distributed cache gives every server the same view, at the cost of a network call instead of a local memory read.
What is cache key design, and why does a poorly designed key silently break caching correctness?
The key must capture everything that affects the result. If two logically different requests (different filters, users or locales) map to the same key, one can silently get the other's result. That's a correctness bug, not just a performance one.
Scenario: an API endpoint takes query params for pagination and filters. How would you design the cache key, and what happens if you get it wrong?
Include every param that changes the response (page number, page size, each filter value), normalized into a consistent order. Get it wrong (e.g. key only on the path) and a page 2 request could get page 1's cached response, or one user's filtered results could leak into another user's request.
Why does adding a cache sometimes make debugging production issues harder?
Bugs can become intermittent and depend on cache state. The same request can behave differently on a hit versus a miss, or fail only after data changed but before the cache caught up, which is harder to reproduce than one consistent code path.
What is cache warming, and when is it necessary?
Filling a cache with expected data before real traffic arrives, instead of waiting for misses to fill it. Useful after a deploy, a cache restart or before an expected traffic spike, so the system isn't hit by a wave of cold-cache misses.
Scenario: a freshly deployed, empty distributed cache goes live right as a traffic surge hits. What could go wrong, and how would you prevent it?
Every request misses at once, so the whole surge lands on the database or service just when it's least ready, possibly overwhelming it. Warm the cache beforehand, or ramp traffic up gradually, so a cold cache doesn't meet peak load.
What's the difference between invalidating a cache entry and simply letting it expire via TTL?
Invalidation is an immediate removal or update triggered by a known data change, so the cache is corrected right away. TTL expiry is passive and time-based: unless you also invalidate, the entry can be served stale for up to the full TTL after the data changes.
Scenario: an e-commerce product's price is updated in the database, but the cache isn't explicitly invalidated. What could go wrong, and for how long?
Customers can keep seeing (and buying at) the old price until the TTL expires, possibly for the whole TTL window. That's why price-sensitive writes usually pair a short TTL with explicit invalidation on update instead of relying on TTL alone.
What is "cache coherence," and why is it harder in a multi-server or multi-region setup?
Cache coherence means every cache holding a copy of the same data agrees. Across many servers or regions, invalidating one cache doesn't invalidate the others, so you need a way to spread the change everywhere (like a pub/sub invalidation broadcast), and that takes time.
How does application-level caching differ from HTTP/CDN caching in where each sits in the request path?
CDN/HTTP caching sits in front of the app, often close to the user, and can answer without the request reaching your servers. App-level caching sits inside your infrastructure: it skips expensive internal work (like a database query), but the request still has to reach your server.
Why can caching mask an underlying performance problem rather than truly solving it?
If a query is slow because of a missing index or poor data model, caching hides it only for hits. Every miss and every uncached path still pays the full cost, and the problem returns as soon as the cache is cleared, overwhelmed or bypassed.
What is a lock-based ("single-flight") approach to preventing stampede, and how does it work mechanically?
On a miss, the first request takes a lock (or marker) saying "I'm recomputing this", does the work, fills the cache and releases the lock. Other requests for the same key see the lock and wait for that result, or briefly serve a stale value, instead of each redoing the work.
Scenario: a cache uses a 24-hour TTL and is also manually invalidated on writes. What can still go wrong if the invalidation has a race condition with a concurrent read?
A read can fetch the old value at nearly the same moment a write invalidates the cache, then win the race and re-cache the old value right after the invalidation. That stale value then stays for up to the full 24-hour TTL, because nothing triggers another invalidation until the next write.
Why is caching a poor fit for data with strict consistency requirements, like a bank balance mid-transaction — and what's an alternative if you must speed up reads there?
Any cache can lag the true value, which is unacceptable when a stale read could let someone spend money that isn't there. Instead, speed up the read path itself (better indexes, a fast replica kept synchronously consistent) rather than trading correctness for speed.
What's the relationship between cache hit ratio and total system load, and what does a "good" hit ratio depend on?
Each hit is a request the underlying system never handles, so a higher hit ratio directly cuts its load. What's "good" depends on how often the workload repeats requests: if nearly every request is for unique data, no tuning gives a high hit ratio.
Follow-up: your cache's hit ratio unexpectedly drops from 95% to 40%. What would you check?
Whether the cache was cleared or restarted (cold cache). Whether TTLs were shortened or a deploy changed cache keys, so requests no longer match existing entries. Whether traffic shifted toward unique requests. Whether memory pressure is evicting entries early.
What is consistent hashing, and why does a distributed cache often use it when adding or removing nodes?
Consistent hashing places keys and cache nodes on the same ring; each key belongs to the next node around it. Adding or removing a node only moves the keys near that node. With naive hash(key) % nodeCount, changing the node count remaps almost every key and causes a mass cache miss.
Common misconception: "the cache is just an optimization, it can't be a source of bugs." Why is this wrong?
A cache has its own state (what's cached, for how long, under what key) that can drift from the source of truth. Stale reads, a bad key leaking one user's data to another, or a stampede overwhelming the backend are real cache-caused bugs, not just lost performance.
Scenario: two concurrent requests both miss the cache for the same key at the same moment, with no stampede protection. Walk through what happens under cache-aside.
Both see a miss, both go to the data source and do the full expensive work, and both write nearly the same result into the cache. The second write is redundant, but the real cost is that the underlying system took two hits (or many more under heavy concurrency) for what should have been one.