Design an LRU/LFU cache and an in-memory KV store

"Design an LRU cache" is one of the most common coding questions in LLD rounds. It looks small, but it tests data structures (O(1) operations), clean class design, thread safety and edge cases. The usual follow-ups are LFU, expiry (TTL) and "now make it a key-value store". This lesson builds all of it step by step, using the process from the LLD approach lesson. The caching lesson explains when to use LRU or LFU. Here we build them.

1. Requirements and Assumptions

  • get(key) returns the value or nothing, and counts as a use.
  • put(key, value) inserts or updates. If the cache is full, it evicts one entry first.
  • Both operations must be O(1) on average.
  • Fixed capacity, counted in entries (a size in bytes comes later as an extension).
  • Eviction policy: LRU first, then LFU, and the design must allow more.
  • Optional expiry per entry (TTL), and it must be safe with many threads.
  • Out of scope: persistence and distribution across machines.

2. The Key Idea: Two Structures Working Together

One structure cannot do both jobs in O(1):

  • A hash map finds an entry by key in O(1), but has no idea which entry is oldest.
  • A list ordered by recent use knows which is oldest, but finding a key in it takes O(n).

Combine them. The map stores key → node, and the nodes form a doubly linked list ordered from most to least recently used. With a pointer to the node, we can remove it from the middle in O(1) (that needs the prev link, which is why the list is doubly linked) and move it to the front. The least recently used entry is always the last node.

3. LRU Cache

Two dummy nodes (sentinels) at the head and tail remove all the "is the list empty?" checks.

public class LruCache<K, V> {
    private class Node {
        K key; V value; Node prev, next;
        Node(K key, V value) { this.key = key; this.value = value; }
    }

    private final int capacity;
    private final Map<K, Node> map = new HashMap<>();
    private final Node head = new Node(null, null);   // most recent side
    private final Node tail = new Node(null, null);   // least recent side

    public LruCache(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException("capacity must be positive");
        this.capacity = capacity;
        head.next = tail;
        tail.prev = head;
    }

    public Optional<V> get(K key) {
        Node node = map.get(key);
        if (node == null) return Optional.empty();
        moveToFront(node);
        return Optional.of(node.value);
    }

    public void put(K key, V value) {
        Objects.requireNonNull(key);
        Objects.requireNonNull(value);
        Node node = map.get(key);
        if (node != null) {                       // update
            node.value = value;
            moveToFront(node);
            return;
        }
        if (map.size() == capacity) {             // evict the least recently used
            Node lru = tail.prev;
            unlink(lru);
            map.remove(lru.key);
        }
        node = new Node(key, value);
        map.put(key, node);
        addToFront(node);
    }

    private void moveToFront(Node n) { unlink(n); addToFront(n); }

    private void unlink(Node n) {
        n.prev.next = n.next;
        n.next.prev = n.prev;
    }

    private void addToFront(Node n) {
        n.next = head.next;
        n.prev = head;
        head.next.prev = n;
        head.next = n;
    }
}

Points to say while writing:

  • The node stores its key. When we evict the tail node we need the key to remove it from the map too. This is the most common bug.
  • Why not java.util.LinkedList? It is doubly linked, but its nodes are private, so the map cannot hold a pointer to one. Removing a given element means searching for it, which is O(n). That is why we write our own Node.
  • Null values are rejected, so Optional.empty() always means "not in the cache".
  • Java also gives you LinkedHashMap with access order and removeEldestEntry, which is an LRU in 5 lines. Mention it, then say you will build it by hand to show the idea. Many interviewers ban it.

4. LFU Cache in O(1)

LFU evicts the entry used the fewest times. A sorted structure by count would cost O(log n). The O(1) trick is to group keys into buckets by frequency:

  • entries: key → value and its count.
  • buckets: count → the keys with that count, in the order they reached it (oldest first). A LinkedHashSet gives O(1) add, remove and "first".
  • minFreq: the lowest count that exists, which tells us the bucket to evict from.
public class LfuCache<K, V> {
    private static class Entry<V> {
        V value; int freq = 1;
        Entry(V value) { this.value = value; }
    }

    private final int capacity;
    private int minFreq;
    private final Map<K, Entry<V>> entries = new HashMap<>();
    private final Map<Integer, LinkedHashSet<K>> buckets = new HashMap<>();

    public LfuCache(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException("capacity must be positive");
        this.capacity = capacity;
    }

    public Optional<V> get(K key) {
        Entry<V> e = entries.get(key);
        if (e == null) return Optional.empty();
        touch(key, e);
        return Optional.of(e.value);
    }

    public void put(K key, V value) {
        Objects.requireNonNull(key);
        Objects.requireNonNull(value);
        Entry<V> e = entries.get(key);
        if (e != null) { e.value = value; touch(key, e); return; }
        if (entries.size() == capacity) evict();
        entries.put(key, new Entry<>(value));
        buckets.computeIfAbsent(1, f -> new LinkedHashSet<>()).add(key);
        minFreq = 1;                              // a new key always has count 1
    }

    private void touch(K key, Entry<V> e) {      // move key from bucket f to f+1
        LinkedHashSet<K> set = buckets.get(e.freq);
        set.remove(key);
        if (set.isEmpty()) {
            buckets.remove(e.freq);
            if (minFreq == e.freq) minFreq++;
        }
        e.freq++;
        buckets.computeIfAbsent(e.freq, f -> new LinkedHashSet<>()).add(key);
    }

    private void evict() {
        LinkedHashSet<K> set = buckets.get(minFreq);
        K victim = set.iterator().next();         // oldest key among the least used
        set.remove(victim);
        if (set.isEmpty()) buckets.remove(minFreq);
        entries.remove(victim);
    }
}

When several keys tie on the lowest count, the one that reached it earliest goes first. That is LRU used as the tie-breaker, which interviewers expect you to state.

5. LRU vs LFU, Traced

Aspect LRU LFU
Evicts Not used for the longest time Used the fewest times
Good when Recent use predicts next use (most workloads) Popularity is stable and one-time scans must not flush the cache
Weakness A big scan pushes out the whole hot set Old favorites stay forever after they stop being used. New items start at count 1 and can be evicted at once.
Extra state per entry Two list pointers A count and a bucket slot
All operations O(1) O(1)

The same operations on a cache of capacity 2 (shown for each cache as the keys it holds):

Step LRU (most recent first) LFU (key:count)
put(1, A) [1] 1:1
put(2, B) [2, 1] 1:1, 2:1
get(1) [1, 2] 1:2, 2:1
put(3, C) Evicts 2. [3, 1] Evicts 2 (lowest count). 1:2, 3:1
get(2) Miss Miss
put(4, D) Evicts 1 (least recent). [4, 3] Evicts 3 (count 1). 1:2, 4:1

The last step is the difference: LRU drops key 1 because it was not touched lately, while LFU keeps it because it was used twice.

6. From Cache to In-Memory KV Store

Now the interviewer wants a general store: any eviction policy, TTL, a delete operation, easy to test. Keep the data in one place and move the "who do we evict" question into a strategy.

classDiagram
    class KvStore {
        -Map data
        -int capacity
        +get(key) Optional
        +put(key, value, ttl)
        +delete(key)
        +sweepExpired()
    }
    class EvictionPolicy {
        <<interface>>
        +onInsert(key)
        +onAccess(key)
        +onRemove(key)
        +victim() Optional
    }
    class LruPolicy
    class LfuPolicy
    class Entry {
        <<record>>
        +value
        +expiresAtMillis
    }
    KvStore --> EvictionPolicy
    LruPolicy ..|> EvictionPolicy
    LfuPolicy ..|> EvictionPolicy
    KvStore "1" *-- "0..*" Entry

The store owns the data and the capacity rule. The policy only tracks order or counts and names a victim. LRU and LFU from sections 3 and 4 become two implementations of the same interface. Adding a new policy touches no store code.

public interface EvictionPolicy<K> {
    void onInsert(K key);
    void onAccess(K key);
    void onRemove(K key);
    Optional<K> victim();
}

public class LruPolicy<K> implements EvictionPolicy<K> {
    private final LinkedHashMap<K, Boolean> order = new LinkedHashMap<>(16, 0.75f, true);
    public void onInsert(K key) { order.put(key, true); }
    public void onAccess(K key) { order.get(key); }          // access order moves it to the end
    public void onRemove(K key) { order.remove(key); }
    public Optional<K> victim() { return order.keySet().stream().findFirst(); }
}

public class KvStore<K, V> {
    private record Entry<V>(V value, long expiresAtMillis) {
        boolean expired(long now) { return expiresAtMillis != 0 && now >= expiresAtMillis; }
    }

    private final Map<K, Entry<V>> data = new HashMap<>();
    private final EvictionPolicy<K> policy;
    private final int capacity;
    private final LongSupplier clock;                       // injected, so tests control time
    private final ReentrantLock lock = new ReentrantLock();

    public KvStore(int capacity, EvictionPolicy<K> policy, LongSupplier clock) {
        if (capacity <= 0) throw new IllegalArgumentException("capacity must be positive");
        this.capacity = capacity; this.policy = policy; this.clock = clock;
    }

    public Optional<V> get(K key) {
        lock.lock();
        try {
            Entry<V> e = data.get(key);
            if (e == null) return Optional.empty();
            if (e.expired(clock.getAsLong())) { remove(key); return Optional.empty(); }   // lazy expiry
            policy.onAccess(key);
            return Optional.of(e.value());
        } finally { lock.unlock(); }
    }

    public void put(K key, V value, Duration ttl) {          // ttl null means no expiry
        Objects.requireNonNull(key); Objects.requireNonNull(value);
        if (ttl != null && (ttl.isZero() || ttl.isNegative()))
            throw new IllegalArgumentException("ttl must be positive");
        lock.lock();
        try {
            boolean exists = data.containsKey(key);
            if (!exists && data.size() >= capacity) {
                sweepExpired();                                // free expired entries first
                if (data.size() >= capacity) policy.victim().ifPresent(this::remove);
            }
            long expiresAt = ttl == null ? 0 : clock.getAsLong() + ttl.toMillis();
            data.put(key, new Entry<>(value, expiresAt));
            if (exists) policy.onAccess(key); else policy.onInsert(key);
        } finally { lock.unlock(); }
    }

    public void delete(K key) {
        lock.lock();
        try { remove(key); } finally { lock.unlock(); }
    }

    public void sweepExpired() {
        lock.lock();
        try {
            long now = clock.getAsLong();
            data.entrySet().stream().filter(e -> e.getValue().expired(now))
                .map(Map.Entry::getKey).toList().forEach(this::remove);
        } finally { lock.unlock(); }
    }

    private void remove(K key) { data.remove(key); policy.onRemove(key); }
}

7. Expiry (TTL)

Each entry stores an absolute expiry time. Two mechanisms work together:

  • Lazy expiry: when get finds an expired entry, it removes it and reports a miss. Cheap, and always correct for readers.
  • Background sweep: a scheduled task calls sweepExpired() now and then, so entries nobody reads do not hold memory forever. A full scan costs O(n) while holding the lock, so large stores sample a few keys with TTLs per run instead (this is what Redis does, see the Redis lesson).
  • When the store is full, remove expired entries before evicting a live one. That is what put does above.
  • The clock is a LongSupplier, so tests move time forward without sleeping.

8. Thread Safety

With many threads, a plain HashMap and a linked list will corrupt. Even get writes (it moves the entry), so a read-write lock does not help. Options, in the order to try them:

  • One lock around every operation (as in the store above). Simple and correct. Fine until profiling shows contention. Say this first.
  • Striping: split into N independent caches (shards) by hash(key) % N, each with its own lock and capacity/N. Threads on different shards do not block each other. The cost is that LRU becomes "per shard" approximate.
  • Approximate LRU: record accesses in a buffer and apply them in batches (Caffeine does this), or sample a few keys and evict the oldest (Redis does this). Reads become nearly lock-free.
  • Avoid a fancy lock-free list. It is easy to get wrong and usually not worth it in an interview. The concurrency lesson covers locks in more depth.

Check-then-act is a trap. If a caller does if (get(k).isEmpty()) put(k, load()), two threads can both load. Offer one atomic method such as getOrLoad(key, loader) that holds the lock (or a per-key lock) while loading, so only one thread runs the loader. This is the cache stampede problem from the caching lesson, at small scale.

9. Errors and Edge Cases

  • Invalid arguments throw: capacity of 0 or less, null key or value, zero or negative TTL (IllegalArgumentException or NullPointerException).
  • A miss is a normal result, so get returns Optional.empty(), not an exception and not null.
  • Capacity 1: every new key evicts the previous one. It must still work.
  • Updating an existing key never evicts, and it counts as a use.
  • An expired entry must not count as a hit or occupy a slot that blocks a new key.
  • Deleting must also remove the key from the policy, or the policy later names a victim that is gone.
  • Large values: a count-based capacity can run out of memory. See extensions.

10. Testing

class KvStoreTest {
    private final AtomicLong now = new AtomicLong(1_000);
    private KvStore<String, String> store(int capacity) {
        return new KvStore<>(capacity, new LruPolicy<>(), now::get);
    }

    @Test
    void evictsLeastRecentlyUsed() {
        var s = store(2);
        s.put("a", "1", null); s.put("b", "2", null);
        s.get("a");                                   // a is now the most recent
        s.put("c", "3", null);                        // evicts b
        assertTrue(s.get("b").isEmpty());
        assertEquals("1", s.get("a").orElseThrow());
    }

    @Test
    void entryExpiresAfterTtl() {
        var s = store(2);
        s.put("a", "1", Duration.ofSeconds(10));
        now.addAndGet(9_999);
        assertTrue(s.get("a").isPresent());
        now.addAndGet(1);                             // exactly 10 seconds
        assertTrue(s.get("a").isEmpty());
    }

    @Test
    void expiredEntriesAreRemovedBeforeEvictingLiveOnes() {
        var s = store(2);
        s.put("a", "1", Duration.ofSeconds(1)); s.put("b", "2", null);
        now.addAndGet(1_000);
        s.put("c", "3", null);                        // a expired, so b must survive
        assertEquals("2", s.get("b").orElseThrow());
    }
}

Also name these without writing them all: update does not evict, capacity 1, delete then re-insert, LFU tie-break by oldest, and a multi-thread test that runs many threads on a small store and checks that size never exceeds capacity.

11. Extensions the Interviewer May Ask

  • Size in bytes: give each entry a weight and evict until total weight fits. Change the capacity check, not the policy interface.
  • Better policies: 2Q, LRU-K or TinyLFU (used by Caffeine) resist scans and one-time items. They are new EvictionPolicy classes.
  • Loading and write-through: pass a loader function, and call the database on a miss (cache-aside), with single-flight loading.
  • Listeners and stats: notify on eviction, and count hits, misses and evictions to report the hit rate.
  • Persistence: periodic snapshots plus an append-only log, as in the storage engines lesson.
  • Distributed: spread keys over nodes with consistent hashing and add replicas. That moves to HLD, as in the key-value store case and the Redis lesson.

12. Common Pitfalls

  • Using a list or array for ordering, so a hit costs O(n).
  • A singly linked list. You cannot unlink a middle node in O(1).
  • Forgetting to store the key in the node, so eviction cannot remove it from the map.
  • Not updating the order on put of an existing key.
  • Updating the map but not the policy on delete or expiry, leaving stale state.
  • An LFU where minFreq is not reset to 1 on insert, or not moved up when its bucket empties.
  • Locking only writes, so concurrent reads corrupt the order.
  • Using System.currentTimeMillis() inside the class, which makes TTL impossible to test.
  • Returning null for a miss when null could also be a stored value.

13. Interview Questions and Answers

1. Why a hash map plus a doubly linked list for LRU?

The map gives O(1) lookup by key. The list keeps entries in order of use, so the least recent is at the tail. Each map value points to its list node, so a hit can unlink the node and move it to the front in O(1). It must be doubly linked so a node can be removed from the middle without searching.

2. How do you get LFU in O(1)?

Keep a map from key to value and count, a map from count to the keys with that count (in insertion order), and the minimum count. A hit moves the key from bucket f to f+1 and updates the minimum if bucket f became empty. Eviction takes the oldest key in the minimum bucket.

3. When would you choose LFU over LRU?

When popularity is stable and the cache must survive scans of seldom-used data, such as a catalog of products where the best sellers stay hot. LRU is the safer default when access patterns shift over time. Real caches often use a mix, such as TinyLFU with an LRU window.

4. How do you make it thread safe?

Start with one lock around every operation, because even reads change the order. If contention shows up, stripe the cache into independent shards or use an approximate policy with batched updates. Add an atomic load-if-absent method so concurrent misses do not run the loader many times.

5. How do you implement TTL?

Store an absolute expiry time per entry. Expire lazily on read, and run a background sweep (or sampling) for entries that nobody reads. Remove expired entries before evicting live ones. Inject a clock so tests can move time.

6. How would you test it?

Unit tests with a fake clock for the key behaviors: eviction order, update without eviction, capacity 1, TTL boundary, delete, and LFU tie-breaks. Then a concurrent test with many threads that checks capacity is never exceeded and no exceptions occur.

7. How does this differ from Redis, and how would you scale it?

Redis is a networked server with many data types, persistence and replication. It uses approximate LRU and LFU by sampling to save memory and time. To scale my store past one machine, I would shard keys with consistent hashing, replicate for availability, and keep each node's store as designed here.