This design outlines a persistent, multi-tenant cache layer called FairPersistentCache. It provides:
Persistence: All data is durably stored on disk (using RocksDB for key-value storage with WAL for crash recovery).
Invalidation: Explicit per-key/namespace invalidation, TTL-based eviction, and optional versioning for conflict resolution.
Fairness: Multi-tenant support with hard memory quotas per namespace (e.g., tenant/user). Each namespace has its own partitioned in-memory LRU cache. Eviction is local to the namespace, preventing any tenant from starving others. Disk usage is soft-limited via admission control counters.
Key Features:
Hybrid storage: Fast in-memory LRU for hot items + persistent disk for cold items.
Automatic memory eviction using LRU within namespace quotas.
Lazy loading: Memory populated on access.
Scalable to millions of keys via prefix-based namespacing (e.g., user123:key1).
Thread-safe with per-namespace locks.
Assumptions:
Backed by RocksDB (or similar embeddable KV store like BadgerDB).
Implemented in Go/Python for simplicity (pseudocode in Python-like syntax).
Memory quota enforced strictly; disk quota soft (reject puts if over global limit).
No strong consistency guarantees (cache is eventually consistent).
counters/: ns:size → total disk bytes for NS quota; global:size → global disk bytes.
Data Structures
python
@dataclass
class Metadata:
value: bytes # In-memory only (hot items)
size: int # Bytes
accesses: int # Hit count
last_access: float # Unix timestamp
ttl_expiry: Optional[float] # Unix timestamp
version: int # For invalidation (increment on put)
class Namespace:
def __init__(self, quota_bytes: int):
self.quota_bytes: int = quota_bytes
self.memory: Dict[str, Metadata] = {} # full_key → Metadata
self.lru: OrderedDict[str, Metadata] = OrderedDict() # LRU order
self.current_mem_size: int = 0
self.lock: Lock = Lock() # Per-NS concurrency
class FairPersistentCache:
def __init__(self, db_path: str, default_quota: int = 100_000_000): # 100MB default
self.data_db = RocksDB(db_path + "/data") # Durable writes
self.meta_db = RocksDB(db_path + "/meta")
self.counter_db = RocksDB(db_path + "/counters")
self.namespaces: Dict[str, Namespace] = {} # Lazy init
self.global_max_disk: int = 1_000_000_000_000 # 1TB soft limit
API
python
class FairPersistentCache:
# Get value (loads to memory if cold)
get(ns: str, key: str) -> Optional[bytes]
# Put/update with optional TTL (seconds) and version bump
put(ns: str, key: str, value: bytes, ttl: Optional[int] = None) -> bool # True if accepted
# Explicit invalidation (by key or prefix/ns)
invalidate(ns: str, key: Optional[str] = None) -> int # Keys removed
invalidate_prefix(ns: str, prefix: str) -> int
# Stats
stats(ns: Optional[str] = None) -> Dict # Hits, size, etc.
set_quota(ns: str, quota_bytes: int) -> None
Key Operations (Pseudocode)
Get
python
def get(self, ns: str, key: str) -> Optional[bytes]:
full_key = f"{ns}:{key}"
ns_cache = self._get_or_create_ns(ns)
with ns_cache.lock:
if full_key in ns_cache.memory:
meta = ns_cache.memory[full_key]
if self._is_expired(meta):
self._invalidate_internal(ns_cache, full_key, meta)
return None
self._update_lru(ns_cache, meta)
return meta.value
# Cold miss: Load from disk
meta_ser = self.meta_db.get(full_key)
if not meta_ser:
return None
meta = deserialize(meta_ser)
if self._is_expired(meta):
self._invalidate_internal(ns_cache, full_key, meta)
return None
value = self.data_db.get(full_key)
meta.value = value
meta.accesses += 1
meta.last_access = time.time()
# Admit to memory (evict if needed)
ns_cache.memory[full_key] = meta
ns_cache.lru[full_key] = meta
ns_cache.current_mem_size += meta.size
self._evict_if_needed(ns_cache)
return value
Put
python
def put(self, ns: str, key: str, value: bytes, ttl: Optional[int] = None) -> bool:
full_key = f"{ns}:{key}"
size = len(value)
expiry = time.time() + ttl if ttl else None
# Check disk quota (atomic counter)
current_ns_size = int(self.counter_db.get(f"{ns}:size") or 0)
current_global = int(self.counter_db.get("global:size") or 0)
if current_ns_size + size > self._get_quota(ns) or current_global + size > self.global_max_disk:
return False # Reject for fairness/disk pressure
meta = Metadata(value, size, 0, time.time(), expiry, version=1) # Bump version
# Durable write (atomic tx if supported)
self.data_db.put(full_key, value)
self.meta_db.put(full_key, serialize(meta))
self._increment_counter(ns, size)
self._increment_counter("global", size)
# Invalidate old version if exists
ns_cache = self._get_or_create_ns(ns)
with ns_cache.lock:
old_meta = ns_cache.memory.pop(full_key, None)
if old_meta:
ns_cache.current_mem_size -= old_meta.size
if full_key in ns_cache.lru:
del ns_cache.lru[full_key]
# Admit new to memory
ns_cache.memory[full_key] = meta
ns_cache.lru[full_key] = meta
ns_cache.current_mem_size += size
self._evict_if_needed(ns_cache)
return True
Eviction (Fair, Per-NS LRU)
python
def _evict_if_needed(self, ns_cache: Namespace):
while ns_cache.current_mem_size > ns_cache.quota_bytes and ns_cache.lru:
victim_key = next(iter(ns_cache.lru)) # LRU head
victim_meta = ns_cache.lru.pop(victim_key)
del ns_cache.memory[victim_key]
ns_cache.current_mem_size -= victim_meta.size
# Note: Value/metadata stay on disk (cold eviction)
Invalidation
python
def invalidate(self, ns: str, key: Optional[str] = None) -> int:
count = 0
ns_cache = self.namespaces.get(ns)
if not ns_cache:
return 0
with ns_cache.lock:
if key:
full_key = f"{ns}:{key}"
meta = ns_cache.memory.pop(full_key, None)
if meta:
ns_cache.current_mem_size -= meta.size
if full_key in ns_cache.lru:
del ns_cache.lru[full_key]
self.data_db.delete(full_key)
self.meta_db.delete(full_key)
self._decrement_counter(ns, meta.size if meta else 0)
count = 1
else:
# Bulk: Invalidate entire NS (use prefix iterator in prod)
for full_key in list(ns_cache.memory):
# ... delete logic
count += 1
return count
Helpers
_is_expired(meta): return meta.ttl_expiry and time.time() > meta.ttl_expiry
Locks: Fine-grained per-namespace RWLock (readers for get, writers for put/invalidate).
Durability: RocksDB WAL ensures fsync on writes. Batch puts for bulk ops.
Recovery: On startup, counters rebuilt by scanning counters/ (fast). Memory empty (repopulates lazily).
Monitoring: Expose Prometheus metrics (hit rate, eviction count per NS).
Trade-offs & Extensions
Feature
Pro
Con
Alternative
Per-NS LRU
Strong fairness, no HoL blocking
Memory overhead (~8B/key)
Global weighted LRU (e.g., W-TinyLFU)
Disk Quota
Soft admission
No hard enforcement
Filesystem quotas
TTL
Simple invalidation
Clock drift
Heartbeat pub/sub
Versioning
Optimistic updates
+4B overhead
Leases
Scalability: Horizontal via sharding (consistent hash on ns:key). Prod Cost: RocksDB ~$0.01/GB/month on SSD.
This design balances performance (sub-ms gets), persistence, and fairness. Implement in Go for prod (use go-lru + rocksdb-go). Let me know if you need full code or tweaks!