1. Understand the Goal: The user wants a system design for a cache that supports two specific features:
* LRU (Least Recently Used) Eviction Policy: When the cache is full, the item that hasn't been used for the longest time should be removed.
* TTL (Time To Live) Support: Items in the cache should expire and be removed automatically after a certain duration.
-
Analyze the Requirements & Constraints:
- Core Functionality: Get(key), Put(key, value).
- Eviction Policy: LRU (requires tracking usage order).
- Expiration: TTL (requires tracking time and cleaning up expired items).
- Concurrency: (Implicit in "system design") likely needs to handle concurrent requests.
- Scale: (Implicit) should be efficient (O(1) for operations ideally).
-
Determine the Core Data Structures:
- To support O(1) Get/Put:
- Hash Map (Dictionary):
Map<Key, Node> allows O(1) access to the cache entry.
- To support LRU:
- Doubly Linked List: Allows moving nodes to the head and removing from the tail in O(1).
- Structure: Head (Most Recently Used) <-> ... <-> Tail (Least Recently Used).
- To support TTL:
- Each node needs to store
expiration_time.
- We need a mechanism to remove expired items. There are two main approaches:
- Lazy Expiration: Check TTL on access (Get/Put). If expired, treat as a miss and delete.
- Active (Proactive) Expiration: A background thread (or separate structure) cleans up expired keys periodically or precisely.
-
Refine the TTL Strategy:
- Lazy approach: Simple. When
get(key) is called, check current_time < expiration_time.
- Problem: "Zombie" keys fill up memory if never accessed again.
- Active approach: Use a
PriorityQueue (Min-Heap) or a SortedSet ordered by expiration time.
- Trade-off: Updating TTL or accessing a key might require updating the heap (O(logN)), slightly impacting standard LRU performance. Or, just rely on Lazy for access and a background cleaner for memory reclamation.
- Selected Approach for this design: Hybrid.
- Lazy: Check on Get/Put.
- Active (Background Janitor): Run a periodic task to clean up expired entries to free memory. This keeps the design robust without slowing down the hot path to O(logN).
-
Drafting the Architecture:
-
Class CacheItem:
key, value
prev, next (for Doubly Linked List)
expires_at (timestamp)
-
Class LRUCache:
capacity: max items.
map: Hash map for storage.
head, tail: Pointers for the DLL.
lock: Mutex for thread safety (crucial for system design questions).
janitor: Background goroutine/thread.
-
Detailed Logic:
-
Code Structure (Python or Java or Go?):
- Python is easiest for pseudocode/logic demonstration. I will use a clear OOP style.
-
Addressing Edge Cases & Advanced Topics:
- Concurrency:
ReentrantLock or ReadWriteLock.
- Memory limits vs Count limits: The prompt implies count (standard LRU), but worth noting.
- Lazy vs Active cleanup: I will implement Lazy (on access) + Background cleanup.
-
Structuring the Response:
- High-Level Design: Explain the components (Hash Map + Doubly Linked List + TTL tracking).
- Data Structures: Define the Node and the Map.
- Algorithms: Walk through
Get and Set with TTL logic.
- Expiration Strategies: Explain Lazy vs. Active.
- Concurrency: Explain Locking strategies.
- Code Example: Provide a working implementation (Python is usually best for readability).
-
Refining the Code Implementation (Self-Correction during drafting):
- DLL Management: Need helper methods
_add_node(node) and _remove_node(node) to keep the main logic clean.
- TTL: Default TTL? Or required per item? Let's assume a default TTL or per-item TTL.
- The "Janitor": Implementing a separate thread adds complexity to the code example. I will describe the logic and perhaps include a simplified version or comments indicating where the thread runs.
-
Final Polish:
- Make sure to mention Time Complexity: O(1) for Get/Put.
- Make sure to mention Thread Safety.
(Self-Correction on TTL cleanup):
If I strictly follow LRU, I remove the tail.
However, if the tail has 10 minutes left but a node in the middle is expired, strictly moving the middle node to head doesn't help memory if the cache is full.
Refined Strategy: Before evicting the LRU tail to make space for a new item, we should ideally try to find any expired item to delete first to avoid throwing away valid data. But finding any expired item is O(N) or requires a Heap.
Pragmatic approach: Just do Lazy Expiration (delete if accessed) + Periodic Cleanup (random sampling or iterating from tail). For the Put operation specifically, if we need to make space, standard LRU is the safest path to guarantee performance.
Let's write the solution following this structure.
- Concept: Hash Map + DLL.
- TTL Logic:
- Check on access.
- Background cleanup (to prevent memory leaks from unaccessed expired keys).
- Code: Python implementation.
Let's check the code logic:
get(key):
if key in map:
node = map[key]
if node.expired: remove(node); return None
move_to_head(node)
return node.value
return None
put(key, value, ttl):
if key in map:
update node
move_to_head
else:
if full: remove_tail()
create node
add_to_head
map[key] = node
This looks solid. I will generate the response now.
Here is a comprehensive design for an LRU Cache with TTL support. This design ensures O(1) time complexity for both Get and Set operations.
1. High-Level Architecture
To satisfy the requirements, we combine three distinct concepts:
- Hash Map (Dictionary): Provides O(1) access to cache items by key.
- Doubly Linked List: Maintains the order of elements to implement the LRU (Least Recently Used) eviction logic.
- Lazy Expiration (TTL): Instead of actively polling to remove expired items (which consumes CPU), we check the expiration time of an item only when it is accessed or when the cache is full.
2. Data Structures
The Cache Item (Node)
Each entry in the cache is represented by a Node object.
Node {
Key
Value
Timestamp: Expiration time (Unix timestamp)
Prev: Pointer to previous Node
Next: Pointer to next Node
}
The Cache System
LRUCache {
Capacity: Integer
Map: HashMap<Key, Node>
Head: Pointer to Node (Most Recently Used)
Tail: Pointer to Node (Least Recently Used)
Lock: Mutex/Semaphore for thread safety
}
3. Algorithmic Logic
A. Accessing Data (Get Operation)
- Lookup: Check the Hash Map for the key. If not found, return "Miss".
- Check TTL: If found, compare
Current Time vs Node.Timestamp.
- If
Current Time > Node.Timestamp:
- Delete: Remove the node from the Linked List and Hash Map.
- Return "Miss" (Expired).
- Update LRU: If valid, move the node to the Head of the Linked List (marking it Most Recently Used).
- Return: Return the value.
B. Storing Data (Set Operation)
- Check Existence: Check if the Key already exists.
- If Yes: Update the Value, update the Timestamp, and move the node to the Head.
- If No:
2. Capacity Check: If the cache is full, we must evict.
3. Eviction Strategy:
* Look at the Tail (LRU item).
* Optimization: If the Tail is expired, remove it immediately. If the Tail is not expired, remove it anyway (standard LRU behavior).
* Repeat until space is available or cache is empty.
4. Insertion: Create a new Node with the current Time + TTL. Add it to the Hash Map and insert it at the Head of the Linked List.
4. Implementation (Python)
Here is a thread-safe implementation using a custom Doubly Linked List and a Dictionary.
import time
import threading
class Node:
"""
Doubly Linked List Node.
"""
def __init__(self, key, value, ttl_seconds):
self.key = key
self.value = value
self.expires_at = time.time() + ttl_seconds if ttl_seconds else float('inf')
self.prev = None
self.next = None
class LRUCacheTTL:
def __init__(self, capacity):
self.capacity = capacity
self.cache = {} # Map key -> Node
self.head = Node(0, 0, 0) # Dummy head
self.tail = Node(0, 0, 0) # Dummy tail
self.head.next = self.tail
self.tail.prev = self.head
self.lock = threading.RLock() # For thread safety
def _remove(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 (Most Recently Used position)."""
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
def _is_expired(self, node):
return time.time() > node.expires_at
def get(self, key):
"""
Get item. Returns None if missing or expired.
Complexity: O(1)
"""
with self.lock:
if key not in self.cache:
return None
node = self.cache[key]
# Lazy Expiration Check
if self._is_expired(node):
self._remove(node)
del self.cache[key]
return None
# Move to front (LRU logic)
self._remove(node)
self._add_to_head(node)
return node.value
def set(self, key, value, ttl_seconds):
"""
Set item.
Complexity: O(1)
"""
with self.lock:
if key in self.cache:
# Update existing
node = self.cache[key]
node.value = value
node.expires_at = time.time() + ttl_seconds
self._remove(node)
self._add_to_head(node)
else:
# Create new
new_node = Node(key, value, ttl_seconds)
self.cache[key] = new_node
self._add_to_head(new_node)
# Eviction if over capacity
if len(self.cache) > self.capacity:
self._evict()
def _evict(self):
"""
Evict LRU item.
Note: In a more complex system, we might loop to find an expired item first,
but standard LRU evicts the tail regardless of TTL to guarantee O(1).
"""
lru_node = self.tail.prev
if lru_node != self.head: # Don't remove dummy head
self._remove(lru_node)
del self.cache[lru_node.key]
def cleanup(self):
"""
Optional: Explicitly scan and remove expired items.
Useful if the cache is large and many items are never accessed again (zombie data).
Complexity: O(N)
"""
with self.lock:
current = self.head.next
while current != self.tail:
next_node = current.next
if self._is_expired(current):
self._remove(current)
del self.cache[current.key]
current = next_node
5. Design Considerations & Trade-offs
1. Eviction Strategy (Standard vs. TTL-aware)
- Current Implementation: When the cache is full, it evicts the LRU item (Tail).
- Alternative: When full, iterate from Tail to find an expired item to evict first. Only evict a valid item if no expired items exist.
- Pros: Keeps valid data longer.
- Cons: In the worst case (no items expired), iteration takes O(N), breaking the O(1) guarantee. The simple approach (evict LRU regardless) is preferred for consistent performance.
2. Cleanup Strategy (Lazy vs. Active)
- Lazy (Used here): We only remove expired items when
Get or Set touches them.
- Pro: Zero overhead when the system is idle.
- Con: If you set 1 million keys with a 1-minute TTL, and never touch them again, they stay in memory for hours, causing a memory leak.
- Active (Background Worker): You can run a background thread (Janitor) that calls
cleanup() every X seconds.
- Pro: Prevents memory leaks from "zombie" keys.
- Con: Introduces CPU overhead and requires careful locking.
3. Thread Safety
The implementation uses a threading.RLock (Reentrant Lock). This ensures that if Set calls evict, which calls remove, we don't deadlock. For high-throughput systems, a ReadWriteLock is often better (allow many concurrent Reads, but exclusive Writes).