Design In-Memory Cache
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-08-29
Problem Statement
Design and implement an in-memory caching system that temporarily stores frequently accessed data to reduce database load and improve response times. The cache should support configurable eviction policies, thread-safety, and high performance under concurrent access.
Functional Requirements
1.<span></span>Basic Operations
2.<span></span>put(key, value) → Store a value against a key.
3.<span></span>get(key) → Retrieve value for a key, if present.
4.<span></span>delete(key) → Remove a key from the cache.
5.<span></span>Capacity Management
6.<span></span>Cache has a maximum size (in terms of entries or memory).
7.<span></span>On reaching capacity, eviction should be triggered.
8.<span></span>Eviction Policies (configurable)
9.<span></span>LRU (Least Recently Used) → Remove least recently accessed entry.
10.<span></span>LFU (Least Frequently Used) → Remove least frequently accessed entry.
11.<span></span>FIFO (First In First Out) → Remove the oldest entry.
12.<span></span>TTL (Time-To-Live)
13.<span></span>Entries may have an optional expiration time.
14.<span></span>Expired entries should be invalidated automatically or lazily during access.
15.<span></span>Concurrency
16.<span></span>Cache should support thread-safe reads/writes.
17.<span></span>Must minimize lock contention for high performance.
18.<span></span>Performance
19.<span></span>Cache operations should work in O(1) time for both get and put.
20.<span></span>Eviction should not degrade under high load.
Non-Functional Requirements
1.<span></span>Scalability → Support large number of entries.
2.<span></span>Extensibility → Easy to add new eviction policies.
3.<span></span>Fault Tolerance → Handle cache misses gracefully by fetching from source (optional).
4.<span></span>Monitoring → Track hit ratio, eviction count, memory usage.
Deliverables
1.<span></span>HLD:
2.<span></span>Component diagram (Cache API layer, Eviction Manager, Expiry Manager, Storage Layer).
3.<span></span>Sequence diagram for get and put operations with eviction.
4.<span></span>LLD:
5.<span></span>Class diagram (Cache, Node, EvictionPolicy, LRUCache, LFUCache).
6.<span></span>Method signatures for put, get, delete, evict.
7.<span></span>Data structures used (e.g., HashMap + Doubly Linked List for LRU).