Design an In-Memory Cache
The data-structure flavoured round — an LRU cache with O(1) reads and writes, eviction and expiry behind interfaces, and how to make it thread-safe without one big lock.
"Implement an LRU cache" is a coding puzzle. "Design a caching library" is an LLD round: the same data structure, but now with a swappable eviction rule, expiry, statistics, a loader, and the threading question. Interviewers like it because it's small enough to finish and has a real algorithmic core.
A cache keeps recently used answers in memory so you don't have to recompute or refetch them. It's deliberately small, so something must be thrown out when it fills up. LRU — least recently used — means the thing you haven't touched for longest goes first.
#1 · Requirements (0–4)
Ask first: a library inside one program, or a cache server? bounded by number of entries or by memory? do entries expire? is the eviction rule fixed?
Assume: in-process library, bounded by entry count, expiry supported, rule swappable.
What it must do
get(key),put(key, value),remove(key),clear().- Fixed capacity — when full, throw something out according to the rule.
- Optional expiry time per entry.
- Optional loader: on a miss, work the value out and keep it.
- Hit and miss counts, and a way to be told when something is evicted.
Qualities that shape the design
getandputmust be O(1) — constant time regardless of size. This is the point of the exercise.- Safe for many threads at once, without funnelling everything through one lock.
- Adding a new eviction rule must not change the cache class.
#2 · The core structure (4–14)
Here's the insight the problem exists to test.
- A hash map finds a key instantly, but knows nothing about order.
- A linked list can reorder instantly, but finding something means walking it.
So use both, and have the map point at nodes inside the list.
map: key → node doubly linked list, most recent first
┌──────────────┐ head (just used) tail (evict me next)
│ "a" → ●──────┼──▶ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐
│ "b" → ●──────┼──▶ │ a │◀─▶│ d │◀─▶│ c │◀─▶│ b │
│ "c" → ●──────┼──▶ └──────┘ └──────┘ └──────┘ └──────┘
│ "d" → ●──────┼──▶ ▲ ▲
└──────────────┘ │ │
get("a") moved it here thrown out first
get(k): look up in the map O(1) → unlink the node O(1) → put at front O(1)
put(k): insert at front; if too big, unlink the tail and drop it from the mapWhy the list must be doubly linked: to remove a node from the middle in constant time you need to know the node before it. With a singly linked list, get becomes O(n) and the whole design falls apart. Say that — it's the one-line justification interviewers wait for.
class Node<K, V> {
K key; V value; // key kept so eviction can clean the map
long expiresAtNanos; // 0 = never
Node<K, V> prev, next;
}#3 · Interfaces (14–22)
interface Cache<K, V> {
Optional<V> get(K key);
void put(K key, V value);
void put(K key, V value, Duration ttl);
void remove(K key);
CacheStats stats();
}
/** Varies 1: which entry to throw out when full. */
interface EvictionPolicy<K> {
void recordAccess(K key); // called on every get and put
void recordInsert(K key);
Optional<K> evict(); // which key to remove
}
/** Varies 2: what counts as expired. */
interface ExpiryPolicy {
boolean isExpired(CacheEntry<?> entry, Instant now);
}
/** Varies 3: what to do on a miss. */
interface CacheLoader<K, V> { V load(K key); }
/** Varies 4: who wants to know something was evicted. */
interface EvictionListener<K, V> {
void onEvicted(K key, V value, EvictionCause cause);
}Now the rules become independent classes:
LruPolicy— the linked list above. Using something moves it to the front; eviction takes from the back.LfuPolicy— least frequently used. Keep a use count per key, and group keys by count so you can find the coldest (least-used) one in constant time. Mention that the naive version (a map of counts, scanned to find the smallest) is O(n).FifoPolicy— insertion order only. A plain queue.TinyLfuPolicy— if you want to sound current: a small, approximate counter of how often each key has been requested recently sits in front of an LRU. A new key only gets into the cache if it's been asked for more often than the entry it would push out — so a key requested once and never again can't evict something popular. This is what the Caffeine library (the standard Java cache) does. One sentence, no more.
Say this: "The cache owns the storage and the map; the policy owns the ordering. Swapping LRU for LFU is a constructor argument, and the cache class never knows which it got."
#4 · Expiry — check on read, sweep in the background (22–28)
Optional<V> get(K key) {
Node<K, V> node = map.get(key);
if (node == null) { stats.miss(); return loadIfPossible(key); }
if (expiry.isExpired(node, clock.instant())) { // checked when read
removeInternal(node, EvictionCause.EXPIRED);
stats.miss();
return loadIfPossible(key);
}
policy.recordAccess(key);
stats.hit();
return Optional.of(node.value);
}The design point, and it transfers everywhere: expiry is checked when something is read, so correctness never depends on a timer having fired. A background sweeper is then only an optimisation — it reclaims memory held by entries nobody reads — rather than something the design relies on. Say that split out loud.
The alternative worth naming: a queue ordered by expiry time, which evicts precisely but costs you a second ordering structure to maintain on every write. For a cache, checking on read plus random sampling is the better trade. Random sampling is what Redis does: every so often, check a handful of random keys and delete the expired ones — cheap, and no extra structure to keep in order.
#5 · Making it thread-safe (28–36)
Start with the honest simple answer, then improve it. That sequence is itself the right way to answer.
Level 1 — one lock. synchronized on every method. Correct, easy to explain, and it funnels all traffic through a single gate. Fine at low concurrency; say you'd start here and measure.
Level 2 — split it into segments. Divide the keys into N independent buckets, each with its own map, list and lock. A key's bucket is decided by its hash. Now N threads working on different keys never wait for each other. The cost is that anything about the whole cache — total size, which entry is least recently used overall — would need every bucket's lock. So instead each bucket gets its own capacity and evicts its own least-recently-used entry, which may not be the oldest in the whole cache. This is how ConcurrentHashMap used to work and how most real caches still bound memory.
class StripedCache<K, V> implements Cache<K, V> {
private final Segment<K, V>[] segments; // each: map, list, own lock
private Segment<K, V> segmentFor(K key) {
return segments[spread(key.hashCode()) & (segments.length - 1)];
}
// one short lock, on this key's segment only
public Optional<V> get(K key) { return segmentFor(key).get(key); }
}Level 3 — the reading problem. Even with segments, plain LRU turns every read into a write, because reading moves the entry to the front of the list. So every reader needs the lock, and readers queue up behind each other even though none of them is changing any data.
The production answer: record reads into a buffer and apply them in batches. A read just notes "key X was used" in a ring buffer — a fixed-size array that wraps around, which threads can append to without taking a lock — and returns immediately. One maintenance task then empties the buffer and does all the reordering under a single lock acquisition. Recency becomes slightly approximate and throughput goes up enormously. That's what Caffeine does, and knowing it is a genuine differentiator.
#6 · Extensions
"Bound it by memory, not entry count."
"Add a
Weigherthat sizes an entry; the cache tracks total weight and evicts until it's under the limit. Same structure, different accounting — and it's another injected interface rather than a change to the core."
"Read-through caching."
"That's the
CacheLoader. The subtlety is the stampede: a thousand simultaneous misses on the same key shouldn't cause a thousand loads. One load per key, with everyone else waiting on the same result.computeIfAbsentwith a future does it: the first caller puts a 'result coming soon' placeholder in the map and starts the load; everyone else finds the placeholder and waits on it."
"Now make it distributed."
"Different problem, and I'd say so. The data structure stops being the interesting part; placement and invalidation become it. Consistent hashing to decide which node holds a key, and the hard question is invalidation — making sure no node keeps serving an old copy after the real data has changed. See Distributed Cache — but I'd check the interviewer wants that zoom level first."
"How would you test it?"
"Deterministic unit tests for the policy with an injected clock: put three entries, read the first, insert a fourth, assert the second was evicted. Then a threading test — many threads hammering overlapping keys, asserting size never exceeds capacity — run thousands of times."
#Check yourself
What is the core LRU data structure?Show answer
Why must the list be doubly linked?Show answer
Why does each node store its own key?Show answer
How do you make the eviction rule swappable?Show answer
Where should expiry be checked?Show answer
Name the three levels of making a cache thread-safe.Show answer
Why is trading precision for concurrency nearly free in an LRU?Show answer
How do you stop a cache stampede on read-through?Show answer
#What to carry forward
- Map plus doubly linked list gives O(1) get and put; nodes carry their keys.
- Eviction, expiry, loading and listeners are separate interfaces.
- Check expiry on read; background sweeping is only an optimisation.
- Concurrency: one lock, then segments, then batched read buffers.
- Know which rules are soft (recency) and trade their precision for throughput.