Designing a Distributed In-Memory Caching Tier
System DesignModel answerLast updated
Design a scalable, resilient distributed in-memory cache shared by backend services, covering memory management, partitioning, failover, and database protection.
Architect a shared, multi-tenant distributed in-memory cache used by backend microservices to offload read traffic from underlying datastores.
Functional Requirements
- Core Operations: Provide key-value primitives:
GET(key),SET(key, value, ttl=None),DELETE(key), and atomic operations such asCOMPARE_AND_SWAP(key, old_val, new_val). - Opaque Data: Keys and values are uninterpreted byte sequences.
- Dynamic Topology: Support expanding or shrinking the cluster capacity with minimal remapping of existing entries.
- Fault Tolerance: Tolerate single-node failures without losing overall service availability or exposing backend databases to excessive read surges.
System Assumptions & Constraints
- Data Volatility: The cache is a volatile layer. Data loss is acceptable, but return of stale data must be strictly bounded and predictable.
- Scope: Primary design targets a single-region deployment; multi-region extension can be discussed as a follow-up.
Key Discussion Areas
Part 1: API Semantics & Single-Node Architecture
- Define key operations, including batch reads, optional time-to-live (TTL), and atomic writes.
- Detail the layout of data in memory on a single node, managing lock contention, memory overhead, and allocation fragmentation.
- Explain eviction algorithms (e.g., LRU derivatives) and expiry mechanisms under high concurrency.
- Provide back-of-the-envelope scale calculations (RAM per node, cluster footprint, bandwidth).
Part 2: Partitioning, Topology, & Fault Tolerance
- Compare client-side routing against proxy-based routing topologies.
- Describe the key distribution scheme (e.g., Consistent Hashing with virtual nodes) and explain how topology updates occur without causing widespread cache misses.
- Detail the consensus/membership management approach and failure detection.
- Detail replication mechanisms (e.g., primary-backup) and explain potential data loss scenarios during node failover.
Part 3: Data Freshness & Datastore Protection
- Define the consistency model and trace the lifetime of an update/invalidation path versus read-fills.
- Address race conditions where out-of-order asynchronous fills overwrite fresh invalidation events.
- Architect mechanisms to mitigate system-wide failure modes: Hot Keys, Thundering Herds (Cache Stampedes), and Cold Starts.
Hints
Hint 1
Divide the design into node-level memory mechanics, distributed partitioning/replication, and backend safeguard patterns.
Hint 2
Address the read-fill race condition using lease tokens (generation identifiers) issued during a cache miss.
Hint 3
Protect the database during key expiry spikes by combining single-flight request coalescing with probabilistic early expiration.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
System Design: Distributed In-Memory Caching Tier
1. High-Level Requirements & Scale Estimation
Requirements Matrix
- Data Operations:
GET(key),SET(key, val, ttl),DELETE(key),COMPARE_AND_SWAP(key, old_val, new_val, ttl), and batchMULTI_GET(keys). - Multi-Tenancy: Namespace-based isolation with configurable memory quotas per service tenant.
- Latency Target: Sub-millisecond $P_{99}$ latency for payloads up to 10 KB.
- Availability: $99.99%$ uptime during node crashes or rolling maintenance events.
Capacity Estimation
- Global Throughput: 10 Million QPS (90% Reads, 10% Writes).
- Target Working Set: 1 Billion keys.
- Average Key Size: 64 Bytes.
- Average Value Size: 1 KB.
- Raw Data Volume: $$\text{Raw Memory} = 1\times 10^9 \times (64 + 1024) \text{ bytes} \approx 1.088 \text{ TB}$$
- Node Metadata & Overhead: ~128 bytes per entry for indexing pointers, eviction queues, and expiry metadata $\rightarrow 128 \text{ GB}$.
- Usable Active Dataset: $\approx 1.22 \text{ TB}$.
- Replication Factor ($RF = 2$): Total usable RAM required $= 1.22 \text{ TB} \times 2 = 2.44 \text{ TB}$.
- Provisioning Hardware:
- Standard Server Spec: 64 GB RAM, 16 CPU cores, 10 Gbps Network Interface (NIC).
- Memory Ceiling per Node: 48 GB dedicated cache memory (75% utilization ceiling).
- Node Count: $\lceil 2.44 \text{ TB} / 48 \text{ GB} \rceil = 51 \text{ nodes}$. Adding a 20% head-room safety buffer yields 64 active nodes.
- Per-Node Network Bandwidth: $$\frac{10\text{M QPS}}{64 \text{ nodes}} \approx 156\text{K QPS/node}$$ $$\text{Throughput} \approx 156\text{K} \times 1.1 \text{ KB} \approx 171.6 \text{ MB/s} \approx 1.37 \text{ Gbps}$$ This fits comfortably within a standard 10 Gbps network interface.
2. Node Architecture & Memory Layout
Concurrency & Storage Engine
To avoid global lock contention across multi-core processors, each node shards its memory space into internal bucket partitions using xxHash3. A node with 16 cores manages 64 sub-buckets. Each sub-bucket operates its own lock-free hashtable index and eviction queue, pinned to an event loop or protected by fine-grained std::shared_mutex instances.
+-------------------------------------------------------+
| Cache Node |
| |
Incoming Request | +-------------------------------------------------+ |
----------------->| | xxHash3 Hash Partitioning | |
| +-------------------------------------------------+ |
| | |
| +-------------------+-------------------+ |
| | | | |
| +-----------+ +-----------+ +-----------+|
| | Sub-Bucket| | Sub-Bucket| | Sub-Bucket||
| | Index 0 | | Index 1 | | Index 63 ||
| +-----------+ +-----------+ +-----------+|
| | Multi-LRU | | Multi-LRU | | Multi-LRU ||
| +-----------+ +-----------+ +-----------+|
+-------------------------------------------------------+
Memory Allocation & Fragmentation Management
Standard system dynamic allocation (malloc) causes memory fragmentation over extended operations under variable item sizes.
- Slab Allocation: Pre-allocates memory into fixed 1 MB memory pages (Slabs). Each Slab is sliced into uniform chunks called Slot Classes (e.g., 128B, 256B, 512B, ..., up to 1MB).
- Inline Structs: Payloads $< 2 \text{ KB}$ are stored directly inside slab allocation slots alongside eviction pointers to minimize pointer-chasing CPU cache misses.
Eviction & Expiration Strategies
- Segmented LRU (SLRU): Prevents large batch operations from invalidating frequently accessed keys.
- Probationary Pool (20% of capacity): New write entries enter here.
- Protected Pool (80% of capacity): Subsequent hits on items in the Probationary pool promote them here. Evictions first drop items from the Probationary pool.
- Dual Expiry Sweeper:
- Lazy Removal: On
GETaccess, ifCurrentTime > KeyExpiry, the node purges the item immediately and reports a cache miss. - Proactive Active Worker: A low-priority background thread periodically samples 20 keys per sub-bucket. If more than 25% are expired, it executes an immediate purge pass on that sub-bucket.
- Lazy Removal: On
3. Cluster Partitioning, Routing, & Replication
Keyspace Partitioning
The system uses Consistent Hashing with Virtual Nodes (VNodes) across a $2^{32}-1$ ring space.
- Each physical node maps to 256 VNodes distributed across the ring to prevent data imbalance.
- Bounded Load Optimization: If a node's load exceeds $1.25 \times \text{Average Node Load}$, requests dynamically spill over to the immediate successor node on the hash ring.
[ Node A - VNode 1 ]
/ \
[ Node C - VNode 2 ] [ Node B - VNode 1 ]
\ /
[ Node A - VNode 2 ]
Routing Architectures
| Parameter | Client-Side Library Routing | Dedicated Proxy Layer (e.g., Envoy) |
|---|---|---|
| Hops per Read | 1 Hop (Direct to target node) | 2 Hops (Client $\rightarrow$ Proxy $\rightarrow$ Node) |
| $P_{99}$ Latency | Lowest ($\approx 400 \mu s$) | Slightly Higher ($\approx 800 \mu s$) |
| Operational Overhead | High (Client libraries in every language) | Low (Centralized proxy management) |
| Connection Overhead | High ($N_{\text{clients}} \times N_{\text{nodes}}$ connections) | Low (Multiplexed pool via proxies) |
Decision: Use Client-Side Routing via a thin native wrapper library for latency-critical core microservices, alongside an optional Proxy Tier for legacy applications or non-latency-sensitive runtimes.
Consensus & Metadata Management
Cluster state is orchestrated using an external consensus service (e.g., etcd or ZooKeeper):
- Nodes register themselves using ephemeral heartbeats.
- Topology shifts (additions/removals) generate a updated hash-ring map version published to client libraries via persistent gRPC streams.
Replication & Failover
- Primary-Backup Scheme ($RF=2$): A key's primary node sits at VNode $R$. Its replica sits at the adjacent physical node's VNode downstream on the ring.
- Write Path: Writes hit the primary node, which asynchronously mirrors the update to the backup node with a configurable $10 \text{ms}$ replication buffer.
- Failover: If the health monitoring cluster marks a primary node dead, client routers update their topology maps to redirect reads to the secondary replica node. Any unflushed async writes in transit during a primary crash are lost (acceptable under the volatile cache design trade-off).
4. Data Freshness & Datastore Protection
Invalidation & Race Condition Safeguards
When database values change, asynchronous invalidation commands are published to a Pub/Sub bus (e.g., Kafka) subscribed to by the caching tier.
The Out-of-Order Cache Fill Race:
- Time $T_1$: Client A reads DB (Value = $V_1$) after a cache miss.
- Time $T_2$: Client B updates DB to $V_2$ and emits an Invalidation event for the key.
- Time $T_3$: Invalidation reaches the cache, clearing the key.
- Time $T_4$: Client A writes stale value $V_1$ back to the cache (overwriting the invalidation).
Client A Client B Cache Node Database
| | | |
|---(1) Read Miss------------------->| |
|----------------(1b) Fetch V1-------------------------->|
| | | |
| |---(2) Write V2---------------------->|
| |---(2b) Invalidate| |
| |----------------->| (Clears key) |
| | | |
|---(4) Fill V1 (STALE!)------------>| |
| | | |
Solution: Lease Tokens (Generation Identifiers)
- On a cache miss, the cache issues a unique, monotonically increasing Lease Token to the client.
- When the client attempts to populate the missing entry via
SET_WITH_LEASE(key, val, token), the cache accepts the write only if the token matches the current active lease ID for that key. - Any intervening
DELETEor invalidation increments the active lease ID, invalidating stale client fills automatically.
Protecting the Primary Database
Incoming Read Requests for Hot Key K
+--------------------------------------------+
| Req 1 | Req 2 | Req 3 | Req 4 |
+--------------------------------------------+
|
v
+-------------------------+
| Single-Flight Coalescer |
+-------------------------+
|
Only 1 Request Sent
v
+-------------------------+
| Back-end Database / DB |
+-------------------------+
|
Returns Value V
v
+--------------------------------------------+
| Req 1 | Req 2 | Req 3 | Req 4 |
+--------------------------------------------+
All Requesters Receive Value V
-
Thundering Herd / Cache Stampede Protection (Single-Flight Coalescing):
- When a cache miss occurs on a hot key, the client-side library or proxy uses a local
SingleFlightmutex lock structure. - Only a single worker thread executes the database query; all other concurrent requests for that key block and await the primary thread's result, preventing database overloading.
- When a cache miss occurs on a hot key, the client-side library or proxy uses a local
-
Probabilistic Early Expiration (XFetch Algorithm):
- To prevent popular items from expiring simultaneously and exposing the database, reads compute a probabilistic early refresh: $$\text{CurrentTime} - (\beta \times \delta \times \ln(\text{rand}())) > \text{ExpiryTime}$$ Where $\delta$ represents the computation time to fetch from the DB, and $\beta > 0$ is an aggressiveness constant. As expiration approaches, reads become probabilistically more likely to trigger an asynchronous background fetch to refresh the entry before it hard-expires.
-
Hot-Key Mitigation:
- Keys exceeding threshold access rates (e.g., $>10,000 \text{ QPS}$) dynamically replicate locally across all client memory spaces (in-process client-side L1 cache with a 1-second TTL).
-
Graceful Degradation (Circuit Breaking):
- If the database response latency exceeds safe operational thresholds, the client library trips a circuit breaker. Requests return stale cache data marked with a
STALE_WARNINGmetadata flag rather than failing or overwhelming the database.
- If the database response latency exceeds safe operational thresholds, the client library trips a circuit breaker. Requests return stale cache data marked with a