Here is a conceptual design for a system implementing a thread-safe cache with LRU (Least Recently Used) eviction and TTL (Time To Live) support.
High-Level Design
The system requires a key-value store that automatically manages its size by evicting the least recently used items when it hits capacity, and invalidates items that have exceeded their time-to-live.
Key Components:
- Hash Map (Dictionary): Stores the actual key-value pairs for O(1) access.
- Doubly Linked List: Maintains the order of element usage.
- Head: Most recently used.
- Tail: Least recently used.
- Timestamps: Associated with each entry to track expiration.
- Lock/Mutex: To ensure thread safety during read/write operations.
Data Structures
class CacheItem:
Key: Any
Value: Any
CreatedAt: Timestamp
TTL: Duration
Prev: Pointer[CacheItem]
Next: Pointer[CacheItem]
- Map:
HashMap<Key, CacheItem>
- List:
DoublyLinkedList (Sentinel Head and Tail nodes simplify logic)
Core Algorithms
1. Get(key)
- Check Existence: Look up
key in the Hash Map.
- If missing: Return
None / Cache Miss.
- If found:
- Check TTL: If
CurrentTime > Item.CreatedAt + Item.TTL:
- Evict the item (remove from Map and List).
- Return
None.
- Update LRU: Move the item to the front of the Doubly Linked List (mark as recently used).
- Return:
Item.Value.
2. Put(key, value, ttl)
- Check Existence: Look up
key in Hash Map.
- If exists:
- Update
Value, TTL, and CreatedAt.
- Move item to front of List.
- If new:
- Check Capacity: If
Map.Size >= MaxCapacity:
- Evict LRU: Remove the item at the tail of the List.
- Remove corresponding key from Map.
- Create new
CacheItem.
- Add to Map.
- Add to front of List.
Refinements & Edge Cases
- Lazy vs. Active Expiration:
- Lazy (described above): TTL is checked only when
Get is called. This is simple but "dead" items take up memory until they are either accessed or pushed out by the LRU limit.
- Active: A background thread periodically scans for expired items. This ensures memory is freed faster but adds CPU overhead.
- Thread Safety: A global lock (Mutex) is the simplest approach. For higher performance, consider sharding the cache (splitting it into N smaller caches with separate locks) to allow concurrent access.
Implementation (Python)
Here is a thread-safe implementation using a simplified approach.
import time
import threading
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int, default_ttl: int = 0):
self.capacity = capacity
self.default_ttl = default_ttl # 0 means no expiration
self.cache = OrderedDict()
self.lock = threading.RLock()
def get(self, key: str):
with self.lock:
if key not in self.cache:
return None
value, expiry = self.cache[key]
# Check if expired (Lazy Eviction)
if expiry is not None and time.time() > expiry:
self.cache.pop(key)
return None
# Move to end (Most Recently Used)
self.cache.move_to_end(key)
return value
def put(self, key: str, value: any, ttl: int = None):
with self.lock:
# Determine expiration time
# If ttl is passed, use it; else use default; if 0, no expiry.
effective_ttl = ttl if ttl is not None else self.default_ttl
expiry = None
if effective_ttl > 0:
expiry = time.time() + effective_ttl
# If key exists, delete it first to update order and value
if key in self.cache:
del self.cache[key]
# Check capacity
elif len(self.cache) >= self.capacity:
# Evict LRU (first item in OrderedDict)
self.cache.popitem(last=False)
# Insert new item
self.cache[key] = (value, expiry)
def cleanup(self):
"""
Optional method to proactively clean up expired items
Useful if the cache is large and 'get' operations are infrequent.
"""
with self.lock:
current_time = time.time()
# Identify keys to remove
keys_to_remove = [
k for k, (_, expiry) in self.cache.items()
if expiry is not None and current_time > expiry
]
for k in keys_to_remove:
self.cache.pop(k)
```</think>
Here is a design for a high-performance, thread-safe Cache system that supports **Time-To-Live (TTL)** and **Least Recently Used (LRU)** eviction.
### 1. High-Level Architecture
The system relies on three main components working in concert:
1. **Concurrency Primitive:** A Read-Write Lock to ensure thread safety.
2. **Storage Layer:** A Hash Map for $O(1)$ key lookups.
3. **Eviction Policy:** A Doubly Linked List to track usage order (LRU).
### 2. Data Structures
To support the requirements efficiently, we define the following structures:
#### A. The Cache Item (Node)
Every key-value pair is wrapped in a node object. This node acts as the "glue" between the storage and the eviction policy.
* **Key:** The cache key.
* **Value:** The stored data.
* **ExpiresAt:** Timestamp (epoch) when this item becomes invalid.
* **Prev/Next:** Pointers for the Doubly Linked List.
#### B. The Hash Map
* Maps `Key -> Node`.
* Allows retrieval of a value in $O(1)$ time.
#### C. The Doubly Linked List
* **Head:** The most recently used (MRU) item.
* **Tail:** The least recently used (LRU) item.
* **Operations:** Moving a node to the head or removing the tail is $O(1)$.
---
### 3. Logic & Algorithms
#### A. Read Operation (GET)
1. **Acquire Read Lock:** Allow concurrent reads.
2. **Lookup:** Find the Node in the Hash Map.
3. **Miss:** If not found, release lock and return `null`.
4. **Hit & Check TTL:**
* If `CurrentTime >= Node.ExpiresAt`: The data is stale. Remove the node from the Hash Map and Linked List. Release lock and return `null` (Cache Miss).
* **Lazy Eviction:** This check ensures expired items are removed only when accessed.
5. **Update LRU:** Promote the Node to the **Head** of the Linked List (mark as recently used).
6. **Return:** Return the Node's value.
#### B. Write Operation (SET)
1. **Acquire Write Lock:** Block other readers/writers.
2. **Check Capacity:**
* If the Cache is full (Size == Capacity), perform **LRU Eviction**:
* Remove the **Tail** Node from the Linked List.
* Remove the corresponding Key from the Hash Map.
3. **Create/Update Node:**
* If the key already exists, update the Value and TTL, then move to Head.
* If new, create a new Node with `ExpiresAt = CurrentTime + TTL`.
4. **Insert:** Add to Hash Map and push to the **Head** of the Linked List.
5. **Release Lock.**
---
### 4. System Implementation (Python)
Here is a robust implementation demonstrating the logic.
```python
import time
import threading
from collections import OrderedDict
class CacheItem:
def __init__(self, key, value, ttl):
self.key = key
self.value = value
self.expires_at = time.time() + ttl if ttl else float('inf')
# Doubly Linked List Pointers
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache_map = {} # Key -> CacheItem
# Dummy Head and Tail for simplifying Linked List operations
self.head = CacheItem(None, None, 0) # Most Recently Used
self.tail = CacheItem(None, None, 0) # Least Recently Used
self.head.next = self.tail
self.tail.prev = self.head
# Thread safety
self.lock = threading.RLock()
def _remove_node(self, node):
"""Removes a node from the Linked List."""
prev_node = node.prev
next_node = node.next
prev_node.next = next_node
next_node.prev = prev_node
def _add_to_head(self, node):
"""Adds a node right after the Head (MRU position)."""
node.next = self.head.next
node.prev = self.head
self.head.next.prev = node
self.head.next = node
def get(self, key):
with self.lock:
if key not in self.cache_map:
return None
node = self.cache_map[key]
# 1. Check TTL (Lazy Eviction)
if time.time() > node.expires_at:
self._remove_node(node)
del self.cache_map[key]
return None
# 2. Update LRU: Move to Head
self._remove_node(node)
self._add_to_head(node)
return node.value
def put(self, key, value, ttl=3600):
with self.lock:
if key in self.cache_map:
# Update existing
node = self.cache_map[key]
node.value = value
node.expires_at = time.time() + ttl
self._remove_node(node)
self._add_to_head(node)
else:
# Check Capacity (Eviction)
if len(self.cache_map) >= self.capacity:
# Remove LRU (node before Tail)
lru_node = self.tail.prev
self._remove_node(lru_node)
del self.cache_map[lru_node.key]
# Insert New
new_node = CacheItem(key, value, ttl)
self.cache_map[key] = new_node
self._add_to_head(new_node)
5. Advanced Considerations
If this system were designed for extreme scale (e.g., millions of requests/sec), the design would change slightly:
- Sharding: Instead of one global lock, the cache would be split into N shards (e.g., 16 or 32 separate cache instances). A key
user:1 would map to Shard 3. This reduces lock contention significantly.
- TTL Eviction Strategy:
- In the design above, we use Lazy Eviction (checking TTL on Read).
- Issue: If data is written but never read again, expired items fill the cache, potentially evicting valid data.
- Solution: A background "Janitor" thread (or goroutine) that periodically iterates the map and cleans up expired items.
- Approximated LRU: To save memory on pointer overhead, systems like Redis use a probabilistic LRU (sampling a small subset of keys and evicting the best candidate) rather than a precise Doubly Linked List.