Distributed Cache and Compute Service Architecture
System DesignModel answerLast updated
Design a thread-safe in-memory cache with LRU eviction and a CPU-intensive reconciliation service that handles traffic spikes and manages computational limits.
You need to architect two production services for a financial platform:
Service 1: In-Memory Cache with LRU Eviction
Build a caching layer that stores key-value pairs with automatic eviction when capacity limits are reached. The cache must:
- Support concurrent reads and writes safely across multiple threads
- Evict least-recently-used entries when memory or entry-count limits are exceeded
- Handle time-based expiration (TTL) for cached entries
- Scale horizontally across multiple server instances
- Provide visibility into cache performance and hot-key patterns
Service 2: Financial Reconciliation API
Design an API that finds combinations of financial transactions summing to a target amount (a variant of the subset-sum problem). The service must:
- Handle normal traffic of 200 requests/second and spikes up to 2,000 requests/second
- Process inputs containing up to 10,000 candidate transactions per request
- Enforce time limits (median 30ms, p99 2s, hard cap 5s) and return partial results when needed
- Prevent duplicate processing of identical requests
- Scale horizontally without shared mutable state between workers
For each service, specify:
- API design and interfaces
- Core data structures and concurrency mechanisms
- Scaling strategy and capacity estimates
- Failure modes, monitoring, and operational considerations
- Key trade-offs in your design choices
Provide concrete numbers and explain how you would validate the design meets requirements.
Hints
Hint 1
For the cache, consider how read operations affect eviction order and what that means for concurrent access patterns
Hint 2
The reconciliation problem is NP-complete in the worst case—your design must prevent unbounded resource consumption
Hint 3
Think about the consistency model: what happens when cache instances diverge or when duplicate reconciliation requests arrive simultaneously?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Distributed Cache and Compute Service Architecture
Initial Requirements Clarification
Before designing, I'd establish concrete scale parameters:
Cache Service:
- Traffic: 50,000 reads/sec and 5,000 writes/sec per instance
- Data: 5 million keys per instance, ~1KB average value size = ~5GB payload
- Total memory budget: ~8GB per instance (including overhead for hash tables and metadata)
- Latency target: p99 < 1ms for local operations, < 3ms over network
Reconciliation Service:
- Normal: 200 RPS, spikes to 2,000 RPS for ~5 minutes
- Median processing: 30ms, p99: 2s, hard timeout: 5s
- Input size: up to 10,000 transactions per request
- This is subset-sum, which is NP-complete—we must bound computation
Service 1: Cache with LRU Eviction
API Design
HTTP Interface:
GET /cache/v1/{key} → 200 + value | 404
PUT /cache/v1/{key} {value, ttl_sec} → 204
DELETE /cache/v1/{key} → 204
Internal Interface:
get(key) → Option<Value>
put(key, value, ttl_seconds)
remove(key)
get_stats() → CacheMetrics
Configuration parameters: max_entries, max_bytes_total.
Core Architecture and Concurrency
The fundamental challenge: get operations must update recency order (move accessed item to "most recent"), which means reads mutate state.
Data Structure:
- HashMap: key → pointer to list node
- Doubly-linked list: nodes ordered by recency (head = most recent)
- Each node contains: key, value, size_bytes, expires_at timestamp
Critical Invariant: The map and list must be updated atomically. If an entry exists in the map, it must exist in the list at the correct position.
Concurrency Strategy (recommended):
Use lock striping with 64 independent segments, each containing its own HashMap + linked list + mutex. Route keys via hash(key) mod 64.
struct CacheSegment {
lock: Mutex,
map: HashMap<Key, *Node>,
list: DoublyLinkedList,
bytes_used: usize,
entry_count: usize,
}
Operations:
get(key): acquire segment lock, lookup in map, move node to list head, release lockput(key, value): acquire segment lock, insert or update, potentially evict LRU items, release lock- Eviction runs inside the critical section until
bytes_used ≤ max_bytesandentry_count ≤ max_entries
Trade-off: Eviction becomes approximate LRU globally but exact within each segment. With 64 segments, the approximation is acceptable in practice.
Alternative for Higher Throughput:
Implement buffered recency tracking (Caffeine-style):
- Reads append to a lock-free ring buffer recording "key X was accessed"
- Background thread drains buffer periodically and reorders the list
- Reads never block on list mutations
- Trade-off: some recency updates may be lost under extreme load, slightly degrading eviction quality but never correctness
TTL Management
Lazy Expiration: On get(key), check now > expires_at; if expired, delete entry and return miss.
Active Expiration: Background sweeper samples N entries per segment every 100ms (similar to Redis). Alternatively, use a timer-wheel data structure bucketed by expiry time for O(1) amortized cleanup.
TTL Jitter: Add random ±10% to requested TTL to prevent thundering herd when many keys expire simultaneously.
Metrics and Observability
Key Metrics:
- Counters:
cache_hits,cache_misses(per segment), evictions split by reason (capacity/TTL/explicit) - Gauges:
bytes_used,entry_count,lock_contention_ratio - Histograms: operation latency distribution
Hot Key Detection: Count-Min sketch + min-heap tracking top-K most frequently accessed keys.
Alerting:
- Hit rate drops below threshold
- Eviction rate spike (may indicate undersized cache)
- Lock contention exceeds 10% of operation time
Horizontal Scaling
Client-Side Consistent Hashing:
- Use 150 virtual nodes per physical instance
- When adding a node, only ~1/N keys are remapped
- Clients maintain a hash ring and route requests deterministically
Alternative: Managed Redis:
- Redis Cluster with 16,384 hash slots
- Configure
maxmemory-policy allkeys-lru - Note: Redis uses approximate LRU (samples random keys) for performance
Recommendation: Start with managed Redis unless there's a specific reason for custom implementation. This demonstrates pragmatism over NIH syndrome.
Hot Key Mitigation:
- Local L1 Cache: Small in-process cache (1-5s TTL) in front of distributed L2
- Key Replication: Replicate hot keys with suffix routing (
key#0throughkey#7), read random replica - Request Coalescing: Single-flight pattern—concurrent misses for the same key trigger only one backend fetch
Replication and Failure Handling:
- One async replica per shard
- Use Sentinel or Cluster for automatic failover
- Accept that async replication may lose recent writes on failover (acceptable for cache)
- Circuit breaker: if cache is down, fail fast and go directly to source with rate limiting
Data Consistency:
- Use cache-aside with delete-on-write (never update-on-write)
- Why: avoids race where concurrent writers leave stale value
- Add version numbers or short TTL to bound staleness window
Service 2: Reconciliation API
API Design
POST /v1/reconciliation/find-combinations
Headers:
Idempotency-Key: <client-generated-uuid>
Body: {
account_id: string,
target_amount: decimal,
currency: string,
candidate_transaction_ids: [string], // or filters
max_results: 10,
max_combination_size: 5,
timeout_ms: 3000
}
Response:
200 {
status: "COMPLETE" | "PARTIAL" | "TIMEOUT",
combinations: [[tx_id, ...], ...],
metadata: {explored_states: int, pruned_branches: int}
}
429 Too Many Requests (with Retry-After header)
503 Service Unavailable
Critical Design Decision: Explicit bounds (max_results, max_combination_size, timeout_ms) are mandatory. Without them, a single request can consume unbounded CPU and memory.
Stateless Worker Architecture
Core Principle: No shared mutable state between requests.
Request → Load Balancer → Worker Pool (one process per core)
↓
Read Replica (transaction data)
Each worker:
- Receives request
- Loads candidate transaction set (snapshot by version or from read replica)
- Runs backtracking search in request-local memory
- Returns result
- Discards all state
Why Stateless:
- No locking in hot path
- No cross-request contamination
- Simple horizontal scaling
- Easy rollback and deployment
Shared Immutable Data:
- Configuration (algorithmic parameters)
- Precomputed indices (e.g., transactions grouped by amount ranges)
- Swapped atomically by reference when updated
Concurrency Model:
- Process pool (to avoid GIL in Python, or thread pool in Java/Go)
- Bounded work queue in front (size = 2× number of workers)
- Queue full → immediate 503 response
Request Deduplication and Idempotency
Idempotency-Key Handling:
On receive:
key = request.headers["Idempotency-Key"]
if result = idempotency_store.get(key):
return cached result
result = compute(request)
idempotency_store.put(key, result, ttl=24h)
return result
Storage: Redis with 24-hour TTL, or PostgreSQL with periodic cleanup.
Request Deduplication (Single-Flight): For identical requests arriving concurrently (same account + target + candidates), only one worker computes; others wait for the result.
Implementation: shared map request_hash → Future<Result>. First request creates Future, others subscribe.
Algorithmic Strategy and Bounds
Backtracking with Aggressive Pruning:
function find_combinations(candidates, target, max_size, deadline):
sort candidates descending by amount
cumulative_sums = precompute suffix sums
backtrack(path=[], remaining=target, start_idx=0):
if time_now() > deadline:
return TIMEOUT
if remaining == 0:
results.add(path.clone())
if results.size >= max_results:
return COMPLETE
if path.size >= max_size:
return
# Pruning
if remaining < 0 or cumulative_sums[start_idx] < remaining:
return
for i in start_idx..candidates.len():
path.push(candidates[i])
backtrack(path, remaining - candidates[i].amount, i+1)
path.pop()
Key Optimizations:
- Pre-sort and precompute suffix sums for pruning
- Check deadline every N iterations (e.g., every 1000 states)
- Early termination when
max_resultsfound
Memory Management
Per-Request Budget:
- Input: 10K transactions × 100 bytes = ~1MB
- Search state stack: max depth 5 × pointers = negligible
- Results: max 10 combinations × max 5 items = ~500 bytes
- Total: ~2MB per request
Capacity:
- 64 cores, 128GB RAM machine
- Reserve 64GB for OS/buffers
- Remaining 64GB ÷ 2MB = 32,000 concurrent requests (far exceeds queue size)
Rate Limiting and Backpressure
Multi-Layer Defense:
- Global Rate Limiter: Token bucket, 2,500 tokens/sec (headroom above spike)
- Per-Account Rate Limiter: Prevent single account from monopolizing service
- Queue Depth: If queue full, reject immediately with 503
- Adaptive Timeout: Under load, reduce default timeout to shed long-tail requests
Load Shedding: Priority queue: interactive API requests > batch jobs. Shed batch first.
Horizontal Scaling
Scaling Math:
- At 2,000 RPS spike, median 30ms → need 2000 × 0.03 = 60 concurrent workers minimum
- Add 2× safety margin → 120 workers
- 1 worker per core → 120 cores → ~4 instances (30-core machines)
Autoscaling Trigger: CPU > 70% sustained for 2 minutes OR queue depth > 50% for 1 minute.
Caching and Precomputation
Result Caching:
Cache computed results keyed by hash(account_id + target + sorted_candidate_ids) with 5-minute TTL.
Precomputed Indices:
- Maintain in-memory index: amount_range → [transaction_ids]
- Quickly filter candidates before search: only include transactions where
min ≤ amount ≤ target
Testing and Validation
Load Testing:
- Baseline: sustain 200 RPS for 1 hour, verify p99 < 2s
- Spike: ramp to 2,000 RPS over 30s, sustain 5 min, verify 503 rate < 1%
- Pathological input: 10K candidates all identical amounts, verify timeout handling
Correctness Testing:
- Unit tests with known subset-sum instances
- Property test: every returned combination must sum to target
- Chaos: kill random workers mid-request, verify no corruption
Monitoring:
- Processing time histogram (by input size bucket)
- Timeout rate, 503 rate
- Idempotency cache hit rate
- Worker queue depth
Key Trade-offs Summary
Cache:
- Lock striping vs. global lock: Higher throughput vs. true LRU ordering
- Custom vs. Redis: Control and learning vs. reliability and maintenance burden
- Consistency: Availability over strict consistency (acceptable for cache)
Reconciliation:
- Stateless vs. stateful: Simpler scaling vs. potential for cross-request memoization (not worth complexity)
- Timeout strategy: Return partial results vs. fail request (partial is more useful)
- Caching: Memory overhead vs. reduced computation for repeated queries
Both designs prioritize operational simplicity, clear failure modes, and observable behavior over micro-optimizations.