KatInterview

Build a Thread-Safe In-Memory Cache with TTL Expiry

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencyttlheap

Last 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) — Store value under key. If ttl_seconds is given, the entry becomes invalid after that many seconds. Calling set on an existing key overwrites it (including its TTL).
  • get(key) — Return the stored value if the key exists and has not expired. Return None otherwise. An expired key should be removed from storage on access.
  • delete(key) — Remove the entry and return True if it existed, False if not.

Requirements

  1. All operations must be safe when called from multiple threads simultaneously.
  2. Memory must not grow without bound when large numbers of keys expire but are never accessed again. Explain and implement a solution for this.
  3. 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 value is None — 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.