Design an in-memory cache with custom eviction policy

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2023-12-12

Problem Statement

Designing an in-memory cache system that stores key-value pairs for fast access. The cache must support a pluggable eviction policy (e.g., LRU, LFU, FIFO, or custom strategies), since memory is limited and old entries may need to be evicted.


Functional Requirements (FR)


Basic Cache Operations


•put(key, value) → Insert or update an entry in the cache.
•get(key) → Retrieve value for a given key.
•delete(key) → Remove an entry from the cache.
•size() → Return the number of items currently in cache.


Eviction Policies


•Cache should support different eviction policies such as:

LRU (Least Recently Used)

LFU (Least Frequently Used)

FIFO (First-In-First-Out)

•Allow plugging in a custom eviction policy without modifying the core cache logic.


Capacity Constraints


•The cache has a fixed maximum capacity.
•When capacity is exceeded, eviction policy decides which entry to remove.


Thread-Safety


•Cache must handle concurrent access by multiple threads safely.


Performance


•Reads and writes should be O(1) or close to O(1) where possible.


Non-Functional Requirements (NFR)


•Extensibility: Easy to add new eviction strategies.
•Scalability: Handle large number of cache operations per second.
•Reliability: Must not return stale or incorrect data.
•Maintainability: Clean modular design following SOLID principles.


Core Entities & Attributes


Cache<K, V>


•capacity, evictionPolicy, storage (Map<Key, Value>)
•Methods: put(key, value), get(key), delete(key), size()


EvictionPolicy<K> (interface/abstract class)


•Methods:
•keyAccessed(key) – called on every get/put.
•evictKey() – returns which key to evict.


Concrete Eviction Policies


•LRUEvictionPolicy → uses Doubly Linked List + HashMap.
•LFUEvictionPolicy → uses frequency map + min-heap.
•FIFOEvictionPolicy → uses Queue.


CacheEntry<K, V>

•key, value, timestamp, frequency (for LFU).


APIs / Operations


•Cache<K, V> cache = new Cache<>(capacity, new LRUEvictionPolicy<>());
•cache.put("A", 1)
•cache.get("A") → 1
•cache.put("B", 2)
•If full, evictionPolicy.evictKey() decides which key to remove.


Advanced Features (Optional / Bonus)


•Time-to-live (TTL) expiry per entry.
•Write-through or write-back strategy for persistence.
•Metrics/monitoring (hit rate, miss rate, eviction count).
•Sharded cache for distributed systems.


Solution

Comments