Concurrent Cache with Deduplication and Safe Expiry
Data Structure DesignModel answerLast 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, andfetch - 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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
A robust solution requires two layers: thread-safe access to cached values and per-key coordination for ongoing loads.
Part 1: Core Synchronization
State Structure:
Maintain three coordinated pieces of state:
- Value storage:
Map<Key, Entry>whereEntrycontains{value, expiryTime, generation} - Load coordination:
Map<Key, LoadState>tracking in-progress fetches - Global or striped lock: protects both maps
The generation counter prevents stale completions from overwriting newer data.
Linearization Points:
get: Read completes when lock is released after checking expirationput: Write becomes visible when lock is released after updating both value and generationdelete: Removal is linearized at lock release after map removal and generation incrementfetch: See Part 2
Lock Granularity:
Start with a single lock for correctness. Optimize later with:
- Read-write lock (many readers, exclusive writers)
- Striped locking (partition keyspace across 16-256 locks)
- Lock-free reads for hot paths if values are immutable
Critical: expiration checks and map updates must happen atomically within the same lock section to prevent returning stale data.
Part 2: Fetch and Request Deduplication
High-Level Strategy:
When fetch(key, loader, ttl) is called:
- Acquire lock and check for unexpired cached value → return if present
- Check if another thread is already loading this key:
- If yes: wait on a condition variable or future
- If no: mark key as "loading" and record current generation
- Release lock and invoke loader (slow I/O outside critical section)
- Reacquire lock:
- Verify generation hasn't changed (no delete/put occurred)
- On success: store result and notify waiters
- On failure: remove loading marker and propagate error
- Return result or throw exception
LoadState Object (per key):
class LoadState {
final long generation;
final CompletableFuture<Value> result;
final int waiterCount;
}
Alternative: use a semaphore or condition variable instead of a future.
Pseudocode:
Value fetch(Key key, Loader loader, Duration ttl) {
lock.lock();
try {
// Fast path: return cached value if fresh
Entry entry = cache.get(key);
if (entry != null && entry.expiryTime > now()) {
return entry.value;
}
// Check for in-flight load
LoadState state = loadStates.get(key);
if (state != null) {
long gen = state.generation;
Future<Value> future = state.result;
lock.unlock();
try {
return future.get(); // blocks until loader completes
} finally {
lock.lock();
// Cleanup if we're the last waiter
if (--state.waiterCount == 0 && loadStates.get(key) == state) {
loadStates.remove(key);
}
}
}
// This thread will load
long currentGen = getGeneration(key);
CompletableFuture<Value> future = new CompletableFuture<>();
loadStates.put(key, new LoadState(currentGen, future, 1));
} finally {
lock.unlock();
}
// Execute loader outside lock
Value value;
try {
value = loader.load(key);
} catch (Exception e) {
lock.lock();
try {
loadStates.remove(key);
future.completeExceptionally(e);
} finally {
lock.unlock();
}
throw e;
}
// Publish result if still relevant
lock.lock();
try {
if (getGeneration(key) == currentGen) {
cache.put(key, new Entry(value, now() + ttl, currentGen));
}
loadStates.remove(key);
future.complete(value);
return value;
} finally {
lock.unlock();
}
}
Key Design Decisions:
-
Generation tracking: Increment on every
putanddelete. The loading thread checks if generation changed before publishing—prevents overwriting newer data. -
Error handling: Loader exceptions are not cached. All waiting threads receive the same exception. A subsequent fetch will retry the loader.
-
Timeout: Wrap loader invocation with timeout enforcement. On timeout, treat as failure and notify waiters.
-
Delete during load: Incrementing generation on delete causes the loader's result to be discarded when it completes. Waiters get the computed value but it's not cached.
-
Cleanup: Remove LoadState when the last waiter completes to prevent memory leaks from abandoned entries.
Common Mistakes:
- Holding the global lock while executing the loader (serializes all cache operations)
- Not checking generation before publishing (stale loads clobber fresh data)
- Caching errors (causes persistent failures until expiration)
- Forgetting to notify waiters on error (threads hang forever)
- Race between expiration check and value read (returns stale data)
Complexity:
- Time: O(1) for cache hit, O(loader time) for miss, first request per key waits for loader, subsequent requests wait for the first
- Space: O(unique keys) for cache + O(keys being loaded) for coordination state
Advanced Considerations:
- Stale-while-revalidate: Return expired value immediately, reload in background
- Negative caching: Cache "not found" results with shorter TTL
- Cancellation: If all waiters abandon a key, cancel the loader
- Distributed caching: Replace in-memory coordination with Redis locks or distributed futures