KatInterview

Concurrent Cache with Deduplication and Safe Expiry

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencycachingsynchronization

Last updated

Implement thread-safe cache retrieval that deduplicates simultaneous requests for identical keys while maintaining parallelism across distinct keys.

You're building a time-based cache that supports a retrieval method fetch(key, loader, ttl). When called, this method should:

  • Return any unexpired cached value immediately
  • If no valid entry exists, invoke the provided loader function to compute the value
  • Store successful results with the given time-to-live
  • Return the computed or cached value
  • Never cache loader failures or exceptions

The challenge: many threads may simultaneously request the same key. Your design must prevent redundant loader invocations (the "thundering herd" problem) while allowing requests for different keys to proceed in parallel.

Requirements

  • Loaders are expensive: they may take 100ms+ and can fail, timeout, or throw exceptions
  • Requests for distinct keys should execute concurrently without blocking each other
  • The cache provides standard operations: put, get, delete, and fetch
  • Keys can be modified or removed while a loader is running
  • Assume values are immutable after publication

Design Questions to Explore

  • When multiple threads request the same missing key, should they all wait for one shared loader execution?
  • If a key is deleted mid-fetch, what should happen to threads waiting on that load?
  • How do you prevent a stale loader (from an old generation) from overwriting a newer value?
  • What are the linearization points for each cache operation?

What to Cover

Part 1: Core Synchronization Model

Define how you'll protect the cache's internal state (values, expiration times, eviction metadata). Identify the atomic transition points for each operation and explain lock granularity.

Part 2: Request Coalescing Strategy

Show how to deduplicate concurrent fetches for the same key without holding locks during I/O. Handle these scenarios:

  • Loader succeeds
  • Loader fails or times out
  • Key is deleted or updated while load is in progress
  • A slow loader completes after a newer value has been written

Your solution should address generation tracking, error propagation, and cleanup of abandoned loads.

Hints

Hint 1

Think about separating coordination state from cached data—use per-key objects to track in-flight loads

Hint 2

The thread executing the loader must release the main lock before calling the slow I/O operation

Hint 3

Track a version or generation number to detect when a load has become stale