KatInterview

Concurrent Least-Recently-Used Cache with Constant-Time Operations

Data Structure DesignModel answer
MediumModel answerData Structure Designlru-cachehash-mapdoubly-linked-list

Last updated

Build a fixed-capacity cache with O(1) lookup, update and eviction by recency, then make it safe for many threads and state exactly what consistency it guarantees.

Concurrent Least-Recently-Used Cache with Constant-Time Operations

You are asked to build a small in-memory cache that holds at most capacity entries, where capacity is a positive integer. It supports two operations:

  • get(key): if the key is stored, return its value and treat the key as the most recently used one. If it is not stored, return a clearly defined "miss" result (for example -1, None, or an empty Optional).
  • put(key, value): if the key already exists, replace its value and treat it as the most recently used. Otherwise insert it as the most recently used entry. If this insertion would push the size above capacity, remove the entry that was used least recently.

Both operations must run in O(1) average time.

Part 1: Single-threaded design

Describe the data structures you would use and the invariants they maintain. Walk through the tricky cases: an empty cache, a cache with one entry, updating an existing key, a capacity of 1, and an insertion that triggers eviction.

Part 2: Concurrent callers

Now suppose many threads call get and put on the same instance at the same time. Explain how you would make it safe. In your answer:

  • State the consistency guarantee you are offering.
  • Identify the exact linearization point of get, put, and eviction.
  • Discuss alternatives to a single lock and what they cost.
  • Explain how you would test the result.

Questions worth settling first

  • Are keys and values immutable? Can a value be null?
  • Is strict linearizability required, or is approximate recency acceptable in exchange for throughput?
  • Does an evicted value need cleanup (closing a handle, notifying a listener)?
  • Is contention on one instance actually measured, or is a single lock likely enough?

Hints

Hint 1

Pair a hash map from key to node with a doubly linked list ordered by recency. Ask which structure gives O(1) lookup and which gives O(1) removal and reinsertion at a known position.

Hint 2

A `get` hit changes the recency order, so it mutates shared state. That is why a plain read-write lock does not let hits run in parallel. Think about what a single mutex must protect: the map, the list, and the size, together.

Hint 3

Sentinel head and tail nodes remove most null-pointer branches (empty, one element, capacity one). For scaling beyond one lock, think about sharding by key hash and what global-recency guarantee you give up when you do.