RetainBestCache — Implement and make it thread-safe, identify race conditions, explain locking strategy

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-10-22

Problem Statement

Designing a cache system that retains the best N elements based on a custom ranking function. The system must support concurrent access, and the design should focus on thread safety, race condition avoidance, and locking strategies.


✅ Functional Requirements


1.Cache Operations
•put(key, value, score): Insert an element into the cache with a score representing its “goodness”.
•get(key): Retrieve the value associated with the key.
•getTopK(): Retrieve top-K elements based on the score.
2.Capacity Management
•Cache has a fixed maximum capacity N.
•When inserting a new element beyond capacity:
•Evict the element with the lowest score.
3.Thread Safety
•Multiple threads can call put and get simultaneously.
•Avoid race conditions that could corrupt internal structures.
4.Optional Features
•Support updating scores of existing elements.
•Expiration of elements (TTL).
•Custom eviction policies in addition to score-based.


🔐 Constraints & Assumptions


•Focus on LLD, concurrency, and locking strategy.
•Elements have unique keys.
•Scores are numeric (integer or float).
•Single-machine environment (no distributed caching required).


🧱 Key Components & Classes


1.CacheItem Class
1 2class CacheItem { 3public: 4 string key; 5 string value; 6 double score; 7};
1.RetainBestCache Class
•Maintains a fixed-size cache and keeps top N elements.
1 2class RetainBestCache { 3private: 4 int capacity; 5 map<string, CacheItem> cacheMap; // key -> CacheItem 6 priority_queue<CacheItem, vector<CacheItem>, CompareScore> minHeap; // lowest score on top 7 mutex cacheMutex; // protects cacheMap and minHeap 8public: 9 RetainBestCache(int capacity); 10 11 void put(string key, string value, double score); 12 string get(string key); 13 vector<CacheItem> getTopK(); 14};
1.CompareScore Class
•Used to maintain min-heap based on score.
1 2class CompareScore { 3public: 4 bool operator()(CacheItem a, CacheItem b) { 5 return a.score > b.score; // min-heap: lowest score at top 6 } 7};


🔄 Example Workflow


1.Thread A calls put("k1", "v1", 90) → lock acquired → item inserted → if capacity exceeded, evict lowest score → unlock.
2.Thread B calls get("k2") → lock acquired → retrieve value → unlock.
3.Thread C calls getTopK() → lock acquired → return snapshot of top elements → unlock.


🧪 Expected Deliverables


•Class diagram showing CacheItem, RetainBestCache, and CompareScore.
•Implementation of put, get, getTopK methods with thread-safety.
•Test cases:
•Concurrent put operations
•Concurrent get and put operations
•Correct eviction of lowest-score item when capacity exceeded
•Retrieval of top-K elements


💡 Discussion Points / Trade-offs


1.Locking Strategy
•Use a single mutex for simplicity → may cause contention under high concurrency.
•Fine-grained locks (e.g., separate locks for map and heap) → more complex but better concurrency.
2.Race Conditions
•Concurrent put may corrupt heap → always lock before modifying heap.
•Concurrent getTopK and put → ensure snapshot or consistent state using locks.
3.Performance vs Complexity
•Min-heap ensures O(log N) insertion and eviction → efficient for top-N cache.
•Alternative: balanced BST (e.g., std::set) → also maintains sorted order.
4.Extensibility
•Allow custom comparison functions for different scoring strategies.
•Add optional TTL or background cleanup thread.


Solution

Comments