Design Flexible In-Memory Cache with customizable capacity + eviction policies
Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2025-06-18
Problem Statement
You are asked to design a flexible, in-memory caching system that supports:
•Customizable capacity limits (per instance or per application).
•Pluggable eviction policies (e.g., LRU, LFU, FIFO, custom strategies).
•High performance (low-latency reads and writes).
•Thread safety for concurrent access.
•Optional persistence / distributed support for scaling.
✅ Functional Requirements
1.Basic Operations
•get(key) → value
•put(key, value) with eviction if needed.
•delete(key) (optional).
2.Configurable Capacity
•Max number of items OR max memory usage.
3.Eviction Policies (pluggable)
•Support LRU, LFU, FIFO out of the box.
•Allow custom eviction strategy via interface.
4.Metrics & Monitoring
•Cache hit ratio, eviction count, memory usage.
❌ Non-Functional Requirements
•Performance: O(1) get/put for common policies (LRU/LFU).
•Concurrency: Thread-safe access under high read/write loads.
•Scalability: Should support multi-instance deployment (optional for distributed cache).
•Extensibility: Easy to add new eviction policies.
•Reliability: Must avoid memory leaks and uncontrolled growth.
🧱 Core Components
1.Cache Interface
•Defines core methods: get, put, delete, size.
2.Eviction Policy Manager
•Abstract strategy interface:
•onAccess(key)
•onInsert(key)
•evict() → keyToRemove.
•Concrete policies: LRU (linked list + hashmap), LFU (min-heap + hashmap), FIFO (queue).
3.Storage Layer
•HashMap (key → value).
•Augmented with metadata (e.g., frequency count, last access time).
4.Capacity Controller
•Enforces memory/size limits.
•Triggers eviction when limits are exceeded.
5.Metrics Collector
•Tracks cache hits, misses, evictions.
6.Concurrency Control
•Read-write locks or concurrent data structures.
•For highly concurrent loads, consider segment-based cache (like ConcurrentHashMap).
7.Optional Distributed Layer
•Consistent hashing across multiple nodes.
•Replication for fault tolerance.
🔄 Flow Example (LRU)
1.Client calls put(K, V).
2.Cache inserts into HashMap.
3.EvictionPolicyManager updates access-order list.
4.If capacity exceeded → evict() removes least-recently-used entry.
5.On get(K) → Cache returns value & updates metadata in eviction manager.
⚖️ Trade-offs to Discuss
•Eviction Policy Choice
•LRU = fast, general-purpose.
•LFU = good for skewed workloads, but more complex.
•FIFO = simplest, but least efficient for caching.
•Concurrency Strategy
•Global lock = simpler, but can bottleneck.
•Sharded/segmented cache = better scalability.
•Memory vs Performance
•Metadata (frequency counts, timestamps) increases memory usage.
•Trade-off between memory footprint and eviction precision.
•Standalone vs Distributed
•In-memory single-node = ultra-low latency, but limited by RAM.
•Distributed = scalable, but introduces network latency & consistency issues.
🧪 Open Discussion Points
•How to extend design to support TTL (time-to-live) expiration?
•How to scale into a Redis-like distributed cache?
•Should cache be write-through or write-back when paired with DB?
•How to make eviction asynchronous without blocking client requests?
👉 This HLD is a classic cache design problem (interviewers often test flexibility, pluggable policies, concurrency, and trade-offs).