Design a Mem Cache System with eviction policies (LRU, LFU, etc.)

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-06-04

Problem Statement

Design an in-memory caching system that can store key-value pairs with a configurable capacity. When the cache reaches its maximum capacity, it should evict items based on different eviction strategies like LRU (Least Recently Used), LFU (Least Frequently Used), or FIFO.


Functional Requirements


1.Cache Operations
•put(key, value) → Insert or update a key-value pair in the cache.
•get(key) → Retrieve the value for a given key (returns null/None if not found).
•delete(key) → Remove a key-value pair from the cache.
2.Eviction Policies
•Support LRU: Evict the least recently accessed key.
•Support LFU: Evict the least frequently accessed key.
•(Optional) FIFO: Evict the oldest inserted key.
3.Capacity Management
•Cache must not exceed its maximum capacity.
•On reaching capacity, apply the selected eviction strategy automatically.
4.Configurable Policy
•Cache should allow plug-and-play eviction policies (Strategy Pattern).


Non-Functional Requirements


•Thread-safety → support concurrent get and put operations.
•Performance → O(1) time complexity for get and put.
•Scalability → should be extensible for new policies.


Edge Cases


•get(key) on missing key → return null/None.
•put(key, value) for an existing key → update value and policy metadata.
•Cache initialized with capacity 0 → no entries allowed.
•Policy switch at runtime (optional).


Design Hints


•Key Classes / Interfaces
•Cache<K, V> → main cache class with capacity and eviction policy.
•EvictionPolicy<K> (interface) → defines onGet(key), onPut(key), evictKey() methods.
•LRUEvictionPolicy<K> → implements LRU using Doubly Linked List + HashMap.
•LFUEvictionPolicy<K> → implements LFU using Min Heap / Frequency Map + HashMap.
•Node<K, V> → represents cache entry with metadata (frequency, timestamp, etc.).
•Data Structures
•HashMap → O(1) lookup of cache entries.
•Doubly Linked List → maintain recency for LRU.
•Min-Heap / TreeMap → maintain frequency for LFU.
•Design Patterns
•Strategy Pattern → eviction policies are interchangeable.
•Factory Pattern → create cache with chosen policy.
•Decorator Pattern (optional) → for adding metrics/logging.


Example Flow


1.Create cache with capacity = 3, eviction policy = LRU.
2.put(1, "A"), put(2, "B"), put(3, "C") → cache full.
3.get(1) → mark 1 as most recently used.
4.put(4, "D") → evicts 2 (least recently used).
5.If policy = LFU, it would evict the least frequently accessed key instead.


Evaluation Areas


•Clean OOP design with interfaces for eviction policies.
•Efficient get/put with O(1) or near-O(1) performance.
•Correct eviction behavior for different policies.
•Extensibility to add new eviction strategies without modifying core cache logic.


Solution

Comments