The user wants a design for a "persistent cache layer with invalidation and fairness". This is a classic system design question.
1. Deconstruct the Requirements:
Persistent: Data survives restarts. It's not just in-memory (RAM). It needs to be backed by disk or a persistent store.
Cache Layer: Fast access. Usually sits between the application and a slower backing store (database).
Invalidation: Data changes or expires, so the cache needs to know when to evict or update entries. This implies cache coherence strategies (TTL, explicit invalidation, write-through, etc.).
Fairness: This is the tricky part. What does "fairness" mean in the context of a cache?
Multi-tenancy: Preventing a "noisy neighbor" (one tenant using all space).
Access Patterns: Ensuring frequently accessed items don't get evicted by a one-time scan (LRU usually handles this, but maybe there's a "fair use" policy).
Resource Allocation: CPU/Memory shares for different clients.
Interpretation: I will focus on multi-tenancy fairness (preventing one user/namespace from dominating the cache capacity) as that is the most common system design interpretation of "fairness" in caching.
2. High-Level Architecture:
I need a layered architecture.
Client: The application using the cache.
In-Memory Layer (L1): For ultra-fast access (optional but good for "cache" design).
Persistent Storage (L2): The core requirement. SSD/Disk based (e.g., RocksDB, SQLite, or a custom log-structured merge tree).
Eviction/Policy Manager: Handles LRU/LFU and Fairness.
Invalidation Manager: Handles updates/deletes.
3. Component Design Details:
Storage Engine (Persistence):
How to persist? Hash map + Log is common (Bitcask style) or LSM Trees (RocksDB).
Choice: LSM Tree (Log-Structured Merge Tree) is standard for high-write persistence. Let's use a Key-Value Store interface.
Optimization: Use a buffer pool (in-memory) to batch writes to disk.
Fairness Strategy:
Problem: If User A spams 1M keys and User B has 100 hot keys, User B shouldn't be evicted.
Solution: Weighted or Partitioned Caching.
Approach 1: Static Partitions (Simple, but inefficient).
Approach 2: Dynamic Quotas / Slab allocation (Memcached slabs, but with limits).
Approach 3: Admission Control + Elastic Quotas (Redis maxmemory-policy + separate pools).
Selected Design:Bounded Partitions per Tenant. Each tenant gets a guaranteed min and a shared max. We need an eviction policy that respects these boundaries (e.g., a modified LRU that scopes eviction to a tenant's bucket first).
Invalidation Strategy:
TTL (Time To Live): Basic.
Explicit Invalidation (DELETE): API driven.
Event-based (Write-through/Write-behind): If the DB updates, cache invalidates.
Design: Support TTL + Explicit API. For distributed systems, we'd need Pub/Sub, but I'll stick to a single node design first, then mention distribution.
4. Deep Dive: The "Fairness" Algorithm:
Let's refine the Fairness aspect.
Concept: "Fair LRU" or "LRU with Memory Limits per Namespace".
Mechanism:
Map each key to a TenantID (or Namespace).
Track global memory usage.
Track per-tenant memory usage.
Eviction Policy:
If global limit reached:
Identify the "greedy" tenant (over their fair share).
Evict from the greedy tenant's LRU list.
If no greedy tenant (everyone is under share), evict from Global LRU.
High-Level Architecture: Diagram description (In-memory vs. On-disk).
Key Components:
Storage Engine (Persistence): How data is stored (LSM/WAL).
Fairness Module: The algorithm for equitable resource usage.
Invalidation Engine: TTL and event handling.
Data Flow: Read/Write paths.
Handling "Fairness" (The core unique requirement): Detailed algorithm (e.g., Token Bucket or Weighted LRU).
Scalability & Distribution (Bonus): How to shard this.
Refining the Fairness Algorithm (Self-Correction):
Standard LRU is unfair. A scanner flushes the cache.
Solution:Segmented LRU (SLRU) + Dynamic Quotas.
Protected Queue: Items accessed > 1 time.
Probationary Queue: Items accessed 1 time.
Fairness: Enforce limits on the Probationary queue for specific tenants. A tenant cannot fill the "Protected" queue unless they have historical data.
Actually, a simpler, robust approach for a design interview is Hierarchical Timers / Two-Level Eviction:
Global Eviction (LRU).
Per-Tenant Caps (Hard limit).
When Global is full, find the tenant with the highest usage relative to their weight, and evict their LRU item. This ensures no tenant hogs the cache.
Let's stick to the Persistent aspect too. The cache needs to be restart-safe.
This implies the index (hash map of keys) must be persisted or reconstructable.
Option A: Checkpointing the Hash Map to disk periodically.
Option B: Storing keys in the SSTable (LSM tree) alongside values.
Option B is more standard (RocksDB model).
Drafting the Content:
Title: Persistent Cache with Fairness (The "FairCache" System).
Storage: Hybrid (RAM Index + Disk Data).
Why: RAM is fast for lookups, Disk is cheap for persistence.
Structure: Key-Value store.
Fairness: "Dynamic Weighted Eviction".
Tenants have weights (priority).
Usage > Weighted Share = Target for Eviction.
Invalidation:
Lazy (on read check TTL).
Active (Hook on write).
Let's refine the "Fairness" explanation.
Fairness prevents the "Cache Stampede" or "Noisy Neighbor".
Mechanism: Cache Quotas.
Assign Max_Bytes per namespace.
If Namespace_A > Limit_A, evict from A specifically.
If Global > Global_Limit, evict from the namespace with the highest (current_usage / quota) ratio.
Let's refine Persistence.
To make it "Persistent" implies we don't lose data on restart.
We need a Write Ahead Log (WAL).
Write operation: Append to Log -> Update Memory Index -> Return OK.
Startup: Read Log -> Rebuild Memory Index.
Persistence Layer: Append-Only Log (Bitcask style) or LSM Tree. Let's go with Bitcask (Append-Only Log) for simplicity and speed in a cache context, merging/compacting periodically to reclaim space.
Fairness Manager: Tracks Namespace -> Size. Enforces limits during writes/eviction.
Invalidation: TTLs embedded in log.
Checking Constraints:
Persistent? Yes, Log on disk.
Cache? Yes, in-memory index for speed.
Fairness? Yes, namespace-aware eviction.
Invalidation? Yes, TTL + explicit delete (tombstone in log).
This looks solid. I will structure the output clearly with diagrams (using text) and detailed logic.
Self-Correction on "Fairness":
Is it fair to block writes? No. It's a cache.
If a tenant exceeds quota, we don't reject the write, we just force an eviction of their oldest data immediately to make room.
Actually, if the disk is full, we must reject.
So: Write -> Check Quota -> If Over, Evict Self -> Write to Log.
Final Polish:
Make sure to mention the trade-offs.
Bitcask requires keeping all keys in RAM. If key space is massive, this fails.
Alternative: LSM-Tree (RocksDB) which allows paging keys to disk.
I will propose a LSM-Tree based approach as it's more scalable for general "Persistent Cache" requirements than Bitcask, though slightly slower for point lookups.
Wait, the prompt asks for a "Cache Layer". Usually, caches prioritize speed. Bitcask (key-in-RAM, value-on-Disk) is standard for high-throughput disk-backed caches (like Riak). I will stick to the Key-in-RAM model as it makes the Fairness/LRU implementation much more performant (don't want to do random disk I/O just to find the LRU item).
Plan:
Architecture Overview (The Box).
Persistence Strategy (The Disk).
Fairness & Eviction Algorithm (The Logic).
Invalidation Mechanism (The Cleanup).
API & Data Flow.
Trade-offs.
Let's write it out.
Invalidation:
TTL is easy.
What about distributed invalidation? The prompt doesn't explicitly ask for distributed, but a "layer" usually implies it might be shared. I'll add a small section on "Distributed Mode" using a message bus (e.g., Redis Pub/Sub or Kafka) for cache coherence, just to be thorough.
Fairness Metric:
Define G(key) = Global usage.
Define L(key) = Local (tenant) usage.
Eviction Logic: Minimize Cost. Cost could be Age (LRU). But constrained by Tenant_Limit.
Algorithm: Weighted-LRU. Every item has a score. Items from heavy tenants get their score penalized (artificially age faster).
Actually, "Dynamic Weighted Eviction" is better.
Maintain a global LRU (Min-Heap based on Access Time).
Maintain TenantUsage map.
On Eviction:
Pop from Global LRU.
Check: Is this tenant over their limit?
If Yes -> Evict.
If No (but Global is full) -> Evict anyway (Global pressure).
Better yet:
If Global is full, find the tenant with (Usage / Quota) max.
Evict that tenant's LRU item.
This guarantees fairness.
This is the most robust design. I will proceed with this.
Component 2: The Fairness Engine (The core innovation)
Component 3: Invalidation Layer (TTL & Events)
Read/Write Workflows
Scalability considerations
Let's generate the response.
Designing a persistent cache layer requires balancing three competing goals: Speed (Cache performance), Durability (Persistence), and Equity (Fairness).
Below is a comprehensive design for a system we will call "FairDisk-Cache".
1. Architectural Overview
We will use a Log-Structured Merge (LSM) Tree architecture (similar to RocksDB or LevelDB) as the base. This provides high write throughput and persistence. We will layer a custom in-memory index and a "Usage Governor" on top to handle the specific requirements of fairness and invalidation.
To ensure the cache is persistent, we cannot rely solely on RAM.
Storage Format:SSTables (Sorted String Tables).
Data is written sequentially to disk. This minimizes disk seeks and maximizes IOPS.
In-Memory Structure (MemTable):
Incoming writes are stored in a sorted structure (like a Skip List) in RAM.
This acts as a write-back buffer.
Write Ahead Log (WAL):
Before an item is confirmed as "added," it is appended to a WAL file on disk. This ensures that if the power fails before the MemTable is flushed to an SSTable, the data can be recovered upon restart.
Compaction:
A background process merges SSTables to remove deleted/expired data and free up disk space.
3. The Fairness Layer (The Core Challenge)
In a shared cache, a "noisy neighbor" (one user/tenant querying massive amounts of data) can evict the hot data of other users. We need to enforce fairness.
A. Namespace & Quotas
Every cache key is namespaced (e.g., tenant_id:key).
Logic: The cache tracks the total bytes used per tenant_id.
Policy: Define a max_bytes_per_tenant.
Enforcement: If a tenant tries to write data that exceeds their quota, the cache immediately triggers an eviction of that tenant's oldest data (internal LRU) to make room, or rejects the write.
B. Weighted LRU (Least Recently Used)
Standard LRU is unfair because a scanner (reading data once) can flush a hotspot (data read often).
Algorithm:LRU-K or Adaptive Replacement Cache (ARC).
Implementation:
We split the cache into two lists: Probationary (new items) and Protected (items accessed more than once).
New keys go to Probationary.
If a key is hit while in Probationary, it moves to Protected.
Eviction happens from the tail of Probationary first.
C. Fair Eviction Strategy (The "Fair Gate")
When the global memory is full, who gets evicted?
Global vs. Local pressure: We do not evict purely globally. We prioritize evicting data from tenants who are consuming more than their fair share of the global capacity.
Formula: When an eviction is needed, calculate a "greedy score" for active tenants:
Score = (Current_Usage / Fair_Share_Quota)
Evict from the Tenant with the highest Score.
4. Invalidation Layer
Invalidation must be fast. Scanning disk files to invalidate a key is too slow.
A. Lazy Invalidation (Bloom Filters)
We do not delete data from disk immediately. Instead, we mark it as invalid.
Bloom Filter per SSTable: Every SSTable has a Bloom Filter (a probabilistic memory structure) telling us if a key might be inside.
Tombstones: When Delete(key) is called, we write a "Tombstone" entry to the MemTable and WAL.
Read Path: When reading, we check the MemTable first. If a Tombstone exists, we return "Not Found" without checking the disk.
B. Active Invalidation (TTL & Events)
TTL (Time To Live): Expiration is handled during the Compaction phase. If a key is expired, the compactor simply drops it from the new merged file.
Event-Driven Invalidation: If the cache is distributed, we use a Pub/Sub channel (e.g., Redis Pub/Sub or Kafka) to broadcast Invalidate(tenant_id, key) messages to all nodes in the cluster.
5. Detailed Workflows
Write Path (Set)
Input:Key, Value, TenantID.
Fairness Check: Check TenantUsage[TenantID]. If > Quota, trigger InternalEvict(TenantID).
Logging: Append command to WAL (Disk).
Memory: Insert into MemTable and update Global LRU.
Ack: Return Success.
Read Path (Get)
Input:Key, TenantID.
Memory Check: Look in MemTable.
If Found (Value): Return.
If Found (Tombstone): Return "Not Found".
Bloom Filter Check: Check Bloom Filters of on-disk SSTables to locate potential files.
Disk Read: Read block from SSTable (cached in OS Page Cache).
Promotion: Update the key's position in the LRU list (move to "Protected").
Protects "hot" data; protects tenants from each other.
Slightly higher memory overhead to track metadata.
Invalidation
Tombstones + Bloom Filters
Non-blocking writes; O(1) delete.
Deleted data occupies disk until Compaction runs.
8. Implementation Stack Recommendation
If building this from scratch:
Language: Rust or C++ (for memory safety and low-level I/O control).
Storage Engine: Use RocksDB as the base KV store (handles persistence/compaction).
Fairness Wrapper: Wrap RocksDB with a Proxy that handles the "Fairness Governor" logic (counting bytes per tenant and rejecting/evicting based on quotas).
Concurrency: Use Arc<Mutex> (Rust) or ReadWriteLock (C++) for the shared Fairness Tracker.