Build a Thread-Safe In-Memory Cache with TTL Expiry
Data Structure DesignModel answerLast updated
Design and implement a concurrent key-value store that supports optional per-entry expiration, lazy eviction, and background memory reclamation.
Background
In-memory caches sit on the hot path of almost every production system. A well-built one must be fast, safe under concurrent access, and leak-free even when cached entries are never touched again.
Task
Implement a class KeyValueCache in Python with the following interface:
class KeyValueCache:
def set(self, key: str, value: Any, ttl_seconds: float | None = None) -> None: ...
def get(self, key: str) -> Any: ...
def delete(self, key: str) -> bool: ...
Method contracts
set(key, value, ttl_seconds)— Storevalueunderkey. Ifttl_secondsis given, the entry becomes invalid after that many seconds. Callingseton an existing key overwrites it (including its TTL).get(key)— Return the stored value if the key exists and has not expired. ReturnNoneotherwise. An expired key should be removed from storage on access.delete(key)— Remove the entry and returnTrueif it existed,Falseif not.
Requirements
- All operations must be safe when called from multiple threads simultaneously.
- Memory must not grow without bound when large numbers of keys expire but are never accessed again. Explain and implement a solution for this.
- Use monotonic time for expiry calculations.
Example
cache = KeyValueCache()
cache.set("session:42", {"user": "alice"}, ttl_seconds=2)
print(cache.get("session:42")) # {"user": "alice"}
# --- 3 seconds later ---
print(cache.get("session:42")) # None
cache.set("config", "v1") # no expiry
cache.delete("config") # True
cache.delete("config") # False
Edge cases to address
- What happens when
ttl_seconds <= 0? - What if
valueisNone— is it distinguishable from a cache miss? - A key is overwritten with a different TTL while a background sweep is in flight. Is the new value safe?
- How do you prevent the background thread from holding the lock for an unbounded time?
Hints
Hint 1
Store expiry as an absolute monotonic timestamp (time.monotonic() + ttl) rather than a relative duration. One comparison then tells you whether an entry is live.
Hint 2
A single threading.Lock around all mutations is sufficient to start. For the memory-leak problem, pair lazy eviction in get() with a daemon thread that walks a min-heap of (expires_at, key) pairs and deletes entries in bounded batches.
Hint 3
The heap can hold outdated entries — for example when a key is overwritten. Before deleting a key during a sweep, verify that the timestamp stored in the heap matches the timestamp currently in the dictionary. If they differ, the heap entry is stale and should be skipped.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core data structure is a dictionary mapping key -> (value, expires_at), where expires_at is either an absolute monotonic timestamp or None for entries with no expiry. Expiration is handled two complementary ways:
- Lazy eviction —
getchecks the timestamp on every read and removes the entry if it is stale. This guarantees correctness regardless of whether a background sweep has run. - Active eviction — A daemon thread periodically drains a min-heap of
(expires_at, key)pairs, deleting keys whose time has passed. This reclaims memory for keys that are written and then never read again.
Using only lazy eviction leaks memory. Using only active eviction leaves a correctness gap between sweeps. Using both is the standard approach (Redis does the same thing, with random sampling instead of a heap).
Why time.monotonic()?
Wall-clock time (time.time()) can jump forward or backward when NTP adjusts the system clock. Monotonic time never goes backward, so TTL calculations are always accurate.
Thread safety
A single threading.Lock wraps every read and write. The check-and-delete inside get must happen atomically — if the check and the delete were separate lock acquisitions, two threads could both see an expired entry and race to delete it (harmless but sloppy) or, worse, a third thread could insert a fresh value between the check and the delete, causing the new value to be incorrectly evicted.
Stale heap entries
When a key is overwritten, its old heap entry is not removed (there is no efficient way to find it in an arbitrary heap position). The sweeper therefore checks: "does the expires_at in the heap match the expires_at currently in the dict?" If not, the heap entry is stale and is simply discarded. This makes overwrites and deletes completely safe.
Heap compaction
Each set with a TTL pushes one entry onto the heap. If the same key is overwritten many times, stale entries accumulate. When the heap exceeds roughly twice the number of live entries, the sweeper rebuilds it from the dictionary. This is O(n) but rare, so it is amortized.
Complexity
| Operation | Time | Notes |
|---|---|---|
get | O(1) avg | dict lookup + one comparison |
set | O(log h) | heap push when TTL is given |
delete | O(1) avg | heap entry cleaned up lazily |
| sweep batch | O(k log h) | k expired entries popped |
| heap compaction | O(n) | amortized, triggered rarely |
Space: O(n + h). Compaction keeps h within O(n).
Edge cases
ttl_seconds <= 0— entry is immediately expired;getreturnsNone. (Real memcached treats0as "no expiry" — worth stating your convention aloud.)value is None— indistinguishable from a miss under this API. Offer acontains(key)method or a sentinel if the interviewer raises it.- One timer per key — a common mistake. Creating a
threading.Timerfor each entry spawns thousands of threads and does not scale.
Implementation
import heapq
import threading
import time
from typing import Any, Optional
class KeyValueCache:
def __init__(
self,
sweep_interval: float = 1.0,
sweep_batch: int = 1000,
) -> None:
# key -> (value, expires_at | None)
self._data: dict[str, tuple[Any, Optional[float]]] = {}
# min-heap of (expires_at, key); may contain stale entries
self._heap: list[tuple[float, str]] = []
self._lock = threading.Lock()
self._sweep_batch = sweep_batch
self._stop = threading.Event()
self._sweeper = threading.Thread(
target=self._sweep_loop,
args=(sweep_interval,),
daemon=True,
)
self._sweeper.start()
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def set(self, key: str, value: Any, ttl_seconds: Optional[float] = None) -> None:
expires_at = (
time.monotonic() + ttl_seconds if ttl_seconds is not None else None
)
with self._lock:
self._data[key] = (value, expires_at)
if expires_at is not None:
heapq.heappush(self._heap, (expires_at, key))
def get(self, key: str) -> Any:
with self._lock:
entry = self._data.get(key)
if entry is None:
return None
value, expires_at = entry
if expires_at is not None and time.monotonic() >= expires_at:
del self._data[key] # lazy eviction
return None
return value
def delete(self, key: str) -> bool:
with self._lock:
return self._data.pop(key, None) is not None
def close(self) -> None:
"""Stop the background sweep thread cleanly."""
self._stop.set()
self._sweeper.join()
# ------------------------------------------------------------------
# Active eviction
# ------------------------------------------------------------------
def _sweep_loop(self, interval: float) -> None:
while not self._stop.wait(interval):
self._purge_expired()
def _purge_expired(self) -> None:
with self._lock:
now = time.monotonic()
popped = 0
while self._heap and self._heap[0][0] <= now and popped < self._sweep_batch:
expires_at, key = heapq.heappop(self._heap)
entry = self._data.get(key)
# Only evict if this heap entry still matches the live record.
if entry is not None and entry[1] == expires_at:
del self._data[key]
popped += 1
# Compact when stale heap entries dominate.
if len(self._heap) > 2 * len(self._data) + 64:
self._heap = [
(exp, k)
for k, (_, exp) in self._data.items()
if exp is not None
]
heapq.heapify(self._heap)
Follow-up: LRU eviction with a capacity cap
Replace the plain dict with an OrderedDict. On every get hit call move_to_end(key). On every set, insert or move the key to the end; if len > capacity, call popitem(last=False) to evict the least-recently-used entry. All operations remain O(1).