Caching questions in a technical test rarely stop at adding Redis. Interviewers want to see that you can justify a cache with numbers, pick the right layer, choose a write pattern, and explain what happens to correctness when data changes. This guide covers the concepts behind strong answers: when a cache is worth its complexity, where it should live, how reads and writes flow through it, how expiration and explicit invalidation work, the race conditions that serve stale data, how to survive a stampede, HTTP caching, and eviction. Every example uses invented systems: a seat-booking service, a bookshop catalogue, a food-delivery menu API. The code is TypeScript because the ideas apply in any language.
Study order
If time is short, go in this order.
- Cache-aside, read-through, write-through and write-behind
Cache-aside and its write path come up in almost every caching question; everything else builds on it.
- Race conditions that leave stale data
Explaining the slow-reader race and its fixes is what separates senior answers from junior ones.
- TTLs, jitter and stale-while-revalidate
TTLs are the safety net behind every strategy, and jitter and stale-while-revalidate are common follow-ups.
- Explicit invalidation: delete, events and versioned keys
You need a concrete plan for derived keys, events and group invalidation when TTLs alone are too slow.
- Cache stampedes and request coalescing
Stampedes are the most frequent production failure caused by caches and a favourite scenario question.
- When a cache is worth it
Justifying a cache with hit ratio and staleness budget shows judgement, not just tooling knowledge.
- Where to cache: from browser to database
Choosing between in-process, distributed and edge caching drives how hard invalidation becomes.
- HTTP caching: Cache-Control, ETags and CDN purges
Web and API roles expect precise knowledge of Cache-Control, ETags and CDN purging.
- Eviction policies and memory sizing
Less central to invalidation, but sizing and policy choice explain many hit ratio problems.
When a cache is worth it
A cache trades freshness and operational complexity for latency and load reduction. It pays off when reads heavily outnumber writes, the same keys are requested repeatedly, the underlying computation or query is expensive, and the business can tolerate data being slightly out of date for a known window.
The number that decides whether a cache helps is the hit ratio. Expected latency is roughly hitRatio * hitCost + (1 - hitRatio) * (hitCost + missCost), because a miss pays for the cache lookup and the origin call. With a low hit ratio the cache adds latency, memory and a new failure mode while saving almost nothing.
In an interview, state the staleness budget explicitly. A bookshop's product description can be minutes old; an account balance used to approve a payment cannot come from a cache at all. Also check whether a cheaper fix exists first: a missing index, an N+1 query or an oversized payload are often the real problem.
TypeScript
type Profile = { hitRatio: number; hitMs: number; missMs: number };
function expectedLatency(p: Profile): number {
return p.hitRatio * p.hitMs + (1 - p.hitRatio) * (p.hitMs + p.missMs);
}
// Orchard Books product page: DB query 40 ms, cache lookup 1 ms
const noCache = expectedLatency({ hitRatio: 0, hitMs: 0, missMs: 40 });
const popular = expectedLatency({ hitRatio: 0.9, hitMs: 1, missMs: 40 });
const longTail = expectedLatency({ hitRatio: 0.2, hitMs: 1, missMs: 40 });
console.log(noCache, popular.toFixed(1), longTail.toFixed(1)); // 40 "5.0" "33.0"A 90% hit ratio cuts average latency by about 8x; a 20% hit ratio barely helps and still costs memory.
Traps
- Caching data whose correctness matters at decision time, such as balances or inventory used to confirm a purchase. Read those from the source of truth.
- Adding a cache before measuring. Without a baseline you cannot prove the hit ratio or the latency gain.
- Forgetting that a cache becomes a dependency: if the whole fleet now relies on it to stay under database capacity, a cache outage is a database outage.
Where to cache: from browser to database
Caches stack up along the request path: browser, CDN or reverse proxy, in-process memory inside each app instance, a shared distributed cache such as Redis or Memcached, and finally the database's own buffer pool and query caches. Each layer closer to the user is faster and cheaper per hit but harder to invalidate.
In-process caches are nanoseconds away and need no network, but every instance holds its own copy, so after a write some instances serve the old value until they are told or until a short TTL expires. A distributed cache gives one shared copy and survives deploys, at the cost of a network round trip and serialization.
A common production design is two tiers: a tiny in-process L1 with a TTL of a few seconds for very hot keys, backed by a shared L2. Invalidation deletes from L2 and broadcasts a message so every instance drops its L1 entry; the short L1 TTL bounds the damage if a message is lost.
TypeScript
type L1Entry = { value: string; expiresAt: number };
class TwoTierCache {
private l1 = new Map<string, L1Entry>();
constructor(private l2: Map<string, string>, private l1TtlMs = 5000) {}
get(key: string): string | undefined {
const local = this.l1.get(key);
if (local && local.expiresAt > Date.now()) return local.value;
const shared = this.l2.get(key);
if (shared !== undefined) {
this.l1.set(key, { value: shared, expiresAt: Date.now() + this.l1TtlMs });
}
return shared;
}
// Called locally and by a pub/sub listener on every instance
dropLocal(key: string): void {
this.l1.delete(key);
}
invalidate(key: string): void {
this.l2.delete(key);
this.dropLocal(key);
// in production: publish("cache-invalidate", key) to the other instances
}
}
const shared = new Map([["menu:basil-row", "{\"items\":42}"]]);
const instanceA = new TwoTierCache(shared);
console.log(instanceA.get("menu:basil-row"));
instanceA.invalidate("menu:basil-row");
console.log(instanceA.get("menu:basil-row")); // undefinedIn-process L1 in front of a shared L2, with invalidation hitting both.
Traps
- Using an in-process cache with a long TTL behind a load balancer: users bounce between instances and see values flip back and forth.
- Caching personalised responses at a CDN without the right Vary or private directives, leaking one user's data to another.
- Forgetting that pub/sub invalidation is fire-and-forget in many systems; always keep a TTL as a safety net.
Cache-aside, read-through, write-through and write-behind
Cache-aside is the default: the application checks the cache, on a miss loads from the database and populates the cache, and on a write updates the database then deletes the cache key. The application owns all the logic, and the cache only holds data that has actually been requested.
Read-through moves the miss-handling into a cache library or service that knows how to load from the origin. Write-through writes to the cache and the database synchronously in the same operation, so the cache is always warm for recently written keys but every write pays both costs. Write-behind writes to the cache and flushes to the database asynchronously, which absorbs write bursts but can lose acknowledged writes if the cache node dies before flushing.
For the interview, know why cache-aside writes usually delete rather than update the key: deletion is idempotent and avoids two concurrent writers leaving the older value in cache. The next reader repopulates from the source of truth.
TypeScript
type Seat = { id: string; price: number };
class MemoryCache {
private store = new Map<string, { value: string; expiresAt: number }>();
async get(key: string): Promise<string | null> {
const e = this.store.get(key);
if (!e || e.expiresAt <= Date.now()) {
this.store.delete(key);
return null;
}
return e.value;
}
async set(key: string, value: string, ttlSeconds: number): Promise<void> {
this.store.set(key, { value, expiresAt: Date.now() + ttlSeconds * 1000 });
}
async del(key: string): Promise<void> {
this.store.delete(key);
}
}
const db = new Map<string, Seat>([["A12", { id: "A12", price: 85 }]]);
const cache = new MemoryCache();
const seatKey = (id: string) => `seat:v1:${id}`;
async function getSeat(id: string): Promise<Seat | undefined> {
const hit = await cache.get(seatKey(id));
if (hit) return JSON.parse(hit) as Seat;
const seat = db.get(id);
if (seat) await cache.set(seatKey(id), JSON.stringify(seat), 60);
return seat;
}
async function updatePrice(id: string, price: number): Promise<void> {
const seat = db.get(id);
if (!seat) return;
db.set(id, { ...seat, price }); // 1. write the source of truth
await cache.del(seatKey(id)); // 2. then invalidate
}
async function main() {
console.log(await getSeat("A12")); // price 85, now cached
await updatePrice("A12", 95);
console.log(await getSeat("A12")); // price 95, reloaded
}
main();Cache-aside for a seat-booking service: read populates, write updates the database and deletes the key.
Traps
- Deleting the cache key before writing the database: a reader can repopulate the old value in the gap.
- Invalidating inside a database transaction that later rolls back, or before commit; invalidate after the commit succeeds.
- Choosing write-behind for data you cannot afford to lose, such as orders or payments.
- Not caching negative results, so repeated lookups for non-existent IDs always hit the database.
TTLs, jitter and stale-while-revalidate
A TTL is the simplest invalidation strategy and the safety net for every other one. It bounds how long any wrong value can survive, whatever bug or lost message caused it. Pick it from the staleness budget: if the business accepts a menu being two minutes out of date, a TTL of 120 seconds needs no other invalidation at all.
Identical TTLs are dangerous when many keys are written at once, for example after a deploy or a bulk import: they all expire in the same second and the database takes the full load. Adding random jitter of around 10% spreads expirations out.
Stale-while-revalidate splits an entry's life into fresh and stale windows. While fresh, serve it. While stale, serve it immediately and refresh it in the background. Past the stale window, treat it as a miss. Users rarely wait on a slow origin, and the refresh happens once rather than on every request.
TypeScript
function jitteredTtl(baseSeconds: number, spread = 0.1): number {
const delta = baseSeconds * spread;
return Math.round(baseSeconds - delta + Math.random() * 2 * delta);
}
type Entry<T> = { value: T; freshUntil: number; staleUntil: number };
function makeEntry<T>(value: T, freshSec: number, staleSec: number): Entry<T> {
const now = Date.now();
return {
value,
freshUntil: now + jitteredTtl(freshSec) * 1000,
staleUntil: now + (freshSec + staleSec) * 1000,
};
}
function classify<T>(e: Entry<T>, now = Date.now()): "fresh" | "stale" | "expired" {
if (now < e.freshUntil) return "fresh";
if (now < e.staleUntil) return "stale"; // serve, refresh in background
return "expired"; // treat as a miss
}
const menu = makeEntry({ restaurant: "Basil Row" }, 120, 30);
console.log(classify(menu)); // "fresh"
console.log(classify(menu, Date.now() + 140_000)); // "stale"
console.log(classify(menu, Date.now() + 200_000)); // "expired"Jittered TTLs avoid synchronized expiry; fresh/stale windows let you serve fast while refreshing.
Traps
- Setting keys with no TTL at all, so any missed invalidation leaves wrong data forever.
- Using one fixed TTL for millions of keys loaded together, creating a periodic load spike when they expire.
- Picking TTLs by gut feel instead of from how stale the product owner says the data may be.
Explicit invalidation: delete, events and versioned keys
When the staleness budget is smaller than a reasonable TTL, the writer must invalidate. The direct way is deleting the key right after the write. That works when the writer knows every key derived from the data, which gets hard once you cache list pages, search results and aggregates built from the same rows.
Event-driven invalidation decouples writers from cache keys: writes emit an event, or a change-data-capture stream reads the database log, and a consumer maps each change to the keys it affects. Reading the database log catches writes from scripts and other services that never call your invalidation code.
Versioned or namespaced keys invalidate a whole group in O(1). Store a version counter per namespace and include it in every key; bumping the counter makes all old keys unreachable, and they disappear through TTL or eviction. This suits cases like a restaurant updating its whole menu, where deleting hundreds of keys individually would be slow and racy.
TypeScript
const store = new Map<string, string>();
const nsKey = (ns: string) => `ns:${ns}`;
const currentVersion = (ns: string) => Number(store.get(nsKey(ns)) ?? "1");
const itemKey = (ns: string, id: string) => `${ns}:v${currentVersion(ns)}:${id}`;
function invalidateNamespace(ns: string): void {
// In Redis this is a single atomic INCR
store.set(nsKey(ns), String(currentVersion(ns) + 1));
}
const ns = "menu:basil-row";
store.set(itemKey(ns, "dish-7"), "Pesto gnocchi 14.50");
console.log(store.get(itemKey(ns, "dish-7"))); // "Pesto gnocchi 14.50"
invalidateNamespace(ns); // the restaurant republished its menu
console.log(store.get(itemKey(ns, "dish-7"))); // undefined: old key is orphanedBumping a namespace version invalidates every key in the group without enumerating them.
Traps
- Forgetting derived keys: invalidating
product:42but not the category listing or search page that embeds it. - Versioned keys without a TTL: orphaned old versions pile up until memory eviction kicks in and pushes out useful keys.
- Relying on application code for invalidation when other services or migrations write to the same tables; CDC catches those writes.
Race conditions that leave stale data
The classic cache-aside race: reader R misses and reads version 1 from the database. Writer W then commits version 2 and deletes the key. R, still holding version 1, writes it into the cache. The cache now holds stale data until the TTL expires, even though invalidation ran correctly. It needs a slow reader, so it is rare but real under load.
Updating instead of deleting has its own race: two writers commit 1 then 2 to the database but their cache writes land as 2 then 1. Read replicas add another: after a delete, a reader repopulates from a replica that has not yet applied the write.
Mitigations, roughly from simple to strong: keep a short TTL so stale entries self-heal; a delayed second delete a few hundred milliseconds after the write, which reduces but does not eliminate the window; read from the primary when repopulating right after a write; and version-checked writes, where every row carries a monotonically increasing version and the cache only accepts a value newer than what it holds, done atomically, for example with a Lua script in Redis. Leases, where the cache hands out a token on a miss and rejects a set whose token was invalidated, solve the slow-reader case directly.
TypeScript
type Row = { id: string; stock: number; version: number };
const cache = new Map<string, Row>();
// Must run atomically in a real cache (e.g. a Redis Lua script)
function setIfNewer(row: Row): boolean {
const current = cache.get(row.id);
if (current && current.version >= row.version) return false;
cache.set(row.id, row);
return true;
}
// Writer's CDC event carries the committed row
console.log(setIfNewer({ id: "sku-77", stock: 9, version: 42 })); // true
// Slow reader finally writes what it loaded earlier
console.log(setIfNewer({ id: "sku-77", stock: 12, version: 41 })); // false, rejected
console.log(cache.get("sku-77")); // { id: "sku-77", stock: 9, version: 42 }Version-checked writes stop a slow reader from overwriting a newer value.
Traps
- Claiming that delete-after-write is fully consistent; the slow-reader race still exists, so always mention a TTL bound or versioning.
- Implementing compare-and-set as a separate get then set from the application, which reintroduces the race the check was meant to prevent.
- Repopulating from a lagging read replica immediately after a write.
Cache stampedes and request coalescing
A stampede, or thundering herd, happens when a hot key expires or is invalidated and hundreds of concurrent requests miss at the same moment. Each one runs the same expensive query, and the origin can fall over exactly when the cache was supposed to protect it. Cold starts after a cache flush or restart produce the same effect across every key.
Within one process, coalesce requests with single-flight: the first miss starts the load and stores the pending promise; everyone else awaits that same promise. Across a fleet, take a short distributed lock such as Redis SET key NX PX 5000; the holder recomputes while others briefly serve the stale value or wait and retry.
A third option avoids the synchronized miss altogether: probabilistic early expiration. Each reader recomputes early with a probability that rises as expiry approaches and as the recomputation cost grows, so usually one request refreshes the value before it expires. Stale-while-revalidate gives a similar effect.
TypeScript
const inFlight = new Map<string, Promise<string>>();
function singleFlight(key: string, load: () => Promise<string>): Promise<string> {
const existing = inFlight.get(key);
if (existing) return existing;
const p = load().finally(() => inFlight.delete(key));
inFlight.set(key, p);
return p;
}
let dbCalls = 0;
const loadLeaderboard = async () => {
dbCalls++;
await new Promise((r) => setTimeout(r, 50)); // slow aggregate query
return "top10:...";
};
async function main() {
const requests = Array.from({ length: 500 }, () =>
singleFlight("leaderboard:weekly", loadLeaderboard),
);
await Promise.all(requests);
console.log(dbCalls); // 1
}
main();500 concurrent misses for the same key trigger one database query.
Traps
- Single-flight in memory only protects one instance; 40 instances can still send 40 identical queries.
- Distributed locks without an expiry: if the holder crashes, nobody can refresh the key.
- Flushing the entire cache during an incident and sending the full read load to a database sized for the cache-protected load.
HTTP caching: Cache-Control, ETags and CDN purges
HTTP caching happens in browsers, CDNs and reverse proxies, controlled by response headers. Cache-Control: max-age sets freshness for all caches, s-maxage overrides it for shared caches like CDNs, private keeps responses out of shared caches, and no-store forbids storing at all. no-cache is often misread: it allows storing but requires revalidation before each reuse.
Validators make revalidation cheap. The server sends an ETag; the client later sends If-None-Match, and if the resource is unchanged the server replies 304 Not Modified with no body. You still pay a round trip, but not the payload.
Invalidating at the edge is the hard part. You cannot reach into users' browsers, so long-lived browser caching works best with fingerprinted URLs such as app.3f9c1a.js, where new content gets a new URL. For CDNs, use the provider's purge API, ideally by tag or surrogate key so one write can purge every page that contains a given product.
TypeScript
import { createServer } from "node:http";
import { createHash } from "node:crypto";
const menu = JSON.stringify({ restaurant: "Basil Row", items: 42 });
const etag = `"${createHash("sha1").update(menu).digest("base64url")}"`;
createServer((req, res) => {
// Browsers: 60 s; CDN: 300 s; serve stale up to 30 s while refreshing
res.setHeader("Cache-Control", "public, max-age=60, s-maxage=300, stale-while-revalidate=30");
res.setHeader("ETag", etag);
if (req.headers["if-none-match"] === etag) {
res.statusCode = 304;
res.end();
return;
}
res.setHeader("Content-Type", "application/json");
res.end(menu);
}).listen(8080);Separate browser and CDN lifetimes, plus an ETag for cheap revalidation.
Traps
- Using
no-cachewhen you meantno-storefor sensitive responses. - Long
max-ageon non-fingerprinted URLs: a CDN purge cannot clear copies already in users' browsers. - Caching authenticated responses as
public, or forgettingVaryon headers that change the body, such asAccept-Encodingor language.
Eviction policies and memory sizing
Eviction decides what to drop when the cache is full, which is different from expiration. LRU drops the least recently used key and suits workloads where recent access predicts future access. LFU drops the least frequently used key and resists one-off scans that would flush a pure LRU cache. FIFO and random eviction are simpler and sometimes good enough.
Know your cache's actual policy. Redis approximates LRU and LFU by sampling keys rather than keeping an exact ordering, and its maxmemory-policy choices include allkeys-lru, allkeys-lfu, the volatile-* variants that only evict keys with a TTL, and noeviction, which rejects writes once memory is full.
Size the cache from the working set, not from the dataset. Monitor hit ratio, eviction rate and memory: a rising eviction rate with a falling hit ratio means the working set no longer fits. An LRU is easy to build in O(1) per operation with a hash map plus a doubly linked list; in JavaScript a Map already keeps insertion order, which makes it a few lines.
TypeScript
class LruCache<K, V> {
private map = new Map<K, V>();
constructor(private readonly capacity: number) {}
get(key: K): V | undefined {
if (!this.map.has(key)) return undefined;
const value = this.map.get(key) as V;
this.map.delete(key); // move to most-recent position
this.map.set(key, value);
return value;
}
set(key: K, value: V): void {
if (this.map.has(key)) {
this.map.delete(key);
} else if (this.map.size >= this.capacity) {
const oldest = this.map.keys().next().value as K;
this.map.delete(oldest);
}
this.map.set(key, value);
}
}
const covers = new LruCache<string, string>(2);
covers.set("isbn-1", "cover1.jpg");
covers.set("isbn-2", "cover2.jpg");
covers.get("isbn-1"); // isbn-1 is now most recent
covers.set("isbn-3", "cover3.jpg"); // evicts isbn-2
console.log(covers.get("isbn-2")); // undefinedAn O(1) LRU using Map insertion order.
Traps
- Using a
volatile-*policy while most keys have no TTL, so nothing is evictable and writes start failing. - Confusing eviction with invalidation: eviction removes data for space, never because it is wrong.
- Letting a batch job scan millions of keys through an LRU cache, pushing out the hot set; consider LFU or bypassing the cache for scans.
Common questions
Short answers to the usual doubts.
Should a write update the cache or delete the key?
Default to deleting. Deletion is idempotent and avoids two concurrent writers leaving the older value cached. Update-on-write makes sense when you can attach a version and reject older writes atomically, or when the key is so hot that a miss after every write would hurt.
Is it ever possible to get strong consistency from a cache in front of a database?
Not with plain cache-aside. You can make staleness rare and bounded with short TTLs, version-checked writes and leases, but reads that must be correct at decision time, such as confirming stock or charging money, should go to the source of truth.
How do I pick a TTL in an interview answer?
Start from the staleness the business tolerates, then check the hit ratio it produces given how often keys are requested. Add jitter, and keep a TTL even when you also invalidate explicitly so any bug or lost event heals itself.
What metrics show that a cache is healthy?
Hit ratio per key pattern, cache latency, eviction rate, memory usage, origin load and the rate of stale reads if you can detect them. A sudden hit ratio drop usually points to a key format change, a flush or a working set that outgrew memory.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Caching: when, where and how to invalidateTake the test
- LRU cacheSolve the exercise