Distributed LRU Cache and Transfer-Matching API

Hard · System Design · Software Engineer · Technical Screen

Prompt

Design two production backend services that operate together in a high-throughput financial platform:

  1. Multi-threaded, horizontally scalable LRU cache: An in-memory key-value caching tier enforcing Least-Recently-Used eviction, byte-capacity quotas, and per-entry Time-To-Live (TTL) expiration—safe under heavy multi-core contention on a single host and distributed cleanly across a multi-node cluster.
  2. Burst-resilient find-transfer-combinations service: A CPU-intensive API that accepts a list of candidate payment transfers and a target settlement amount (for instance, matching incoming bank wires of 180.00 EUR, 320.00 EUR, and 450.00 EUR against a 500.00 EUR payout) and enumerates valid transfer subsets summing exactly to that target, even when reconciliation jobs trigger sudden 10x traffic bursts.

Scope & Expectations

  • Single-node and cluster-wide LRU architecture: Define the cache API, single-process concurrency strategy (comparing fine-grained lock striping against lock-free or buffered designs), concurrent eviction and TTL/size enforcement, cluster sharding (managed Redis vs. consistent-hashing nodes), hot-key absorption, replication/failover, backpressure, and cache-aside consistency.
  • Compute isolation and bounded subset search: Compare stateless and stateful worker topologies for find-transfer-combinations, eliminate shared mutable worker state, bound per-request CPU and memory consumption, and explain result caching, precomputation, and in-flight request deduplication.
  • Burst protection and operational resilience: Detail rate limiting, admission control, deadline propagation, client retry idempotency, and horizontal autoscaling under abrupt traffic spikes.
  • Sizing, telemetry, and verification: Provide back-of-the-envelope capacity estimates, key production metrics and alerts, and a testing strategy covering concurrency invariants, solver exactness, and cluster failure modes.

Step-by-step walkthrough

  1. Clarify requirements for both services

    On a global payment platform, low-latency infrastructure and batch settlement reconciliation live side by side—and the second service naturally uses the first as its result cache. Scope each service's functional contract and non-functional targets up front.

    Service A: Scalable thread-safe LRU caching service

    • Core operations: get(ns, key), put(ns, key, value, ttl_ms, expected_version), delete(ns, key), batch mget(ns, keys), plus an in-process helper get_or_load(key, loader, ttl_s).
    • Eviction & isolation: each client team gets an isolated namespace (ns) with a strict byte capacity (not entry count). When a namespace is full, evict LRU (Least Recently Used — the item untouched for the longest time) entries, alongside optional TTL (Time-To-Live — automatic expiration after a set duration).
    • Cache, not source of truth: callers must tolerate cache misses on eviction or node failover; the backing database remains authoritative.
    • Scale & latency targets: 500,000 ops/s peak (90% reads = 450k gets/s, 10% writes = 50k puts+deletes/s), 100M keys, average value 2 KB (max 1 MB), server p99 latency < 1 ms (< 3 ms end-to-end in-region), 99.95% availability, 95% hit ratio, and losing one node must not melt down the backing database.

    Service B: find-transfer-combinations API

    • Core operation: given n incoming transfers (id, amount_minor) in one currency and a target_minor amount, return combinations of transfers (each transfer used at most once) whose amounts sum exact-to-the-cent to target_minor (for example, matching bank wires to a merchant invoice).
    • Bounded exponential search: subset-sum enumeration explores up to 2^n subsets in the worst case. Enforce hard synchronous guardrails (n ≤ 50, max_results ≤ 1,000, CPU node budget, and request deadline), route larger inputs to an async job queue, and return complete: true | false so callers always know whether unreturned combinations may exist.
    • Traffic & spikes: 200 req/s steady state, jumping 10x to 2,000 req/s within 60 seconds during end-of-day merchant reconciliation bursts lasting ~10 minutes. Small requests (n ≤ 20) need p99 < 100 ms.
    • Clarifying assumptions stated explicitly: amounts are positive integers in currency minor units (cents); negative adjustments/refunds are excluded from v1 (because negative numbers disable monotonic sum pruning); callers choose distinct_by: "transfer" | "amount".
  2. Capacity estimates

    Estimate memory, network bandwidth, CPU cores, and failure blast radius before picking cluster sizes.

    Service A — Distributed LRU Cache
      Peak throughput    500,000 ops/s (450k gets/s, 50k writes/s)
      Dataset footprint  100M keys x (2,048 B value + ~100 B key/node metadata) ~ 215 GB
      Per-node RAM       64 GB instance -> ~45 GB usable for cache data (leaving OS, buffers, allocator headroom)
      Shard count        215 GB / 45 GB ~ 4.8 -> choose 8 primary shards + 8 cross-AZ replicas = 16 nodes
      Load per primary   ~62.5k ops/s, ~27 GB stored, ~0.9 Gbps outbound (450k x 2 KB = 7.2 Gbps cluster-wide)
      Hot-key danger     1 viral 200 KB key read 50,000 times/s = 10 GB/s = 80 Gbps on ONE shard!
                         -> impossible for one NIC; requires an in-process near cache on client pods
      Replica math       95% hit rate -> DB normally sees 450k x 5% = 22.5k reads/s
                         if 1 of 8 primaries dies WITHOUT a replica: 427.5k / 8 ~ 53.4k hits/s turn into misses
                         -> DB load jumps to 22.5k + 53.4k ~ 75.9k reads/s (3.4x normal load!)
    
    Service B — find-transfer-combinations API
      Traffic            200 req/s normal  |  2,000 req/s during 10x reconciliation spikes
      CPU per request    80% small (n <= 20): ~1 ms  |  18% medium: ~30 ms  |  2% hit 1 s budget: ~1,000 ms
                         weighted mean CPU = (0.80 x 1) + (0.18 x 30) + (0.02 x 1,000) = 26.2 ms / request
      CPU cores needed   spike: 2,000 req/s x 0.0262 s ~ 52.4 busy cores -> at 60% target utilization ~ 88 vCPUs
                         = 11 stateless pods x 8 vCPUs each (steady state: 3 pods across 3 AZs = 24 vCPUs)
                         with 30% result-cache hits on spike retries: ~62 vCPUs (~8 pods)
      Per-request RAM    max 1,000 results x 50 IDs x 8 B = 400 KB; reachable bitset up to 10^7 cents = 1.25 MB
                         hard worker ceiling = +64 MB -> 8 workers/pod uses < 0.5 GB working RAM
      Cold-start gap     new Kubernetes pods take 60-90 s to boot -> admission control must absorb minute 1!
    
  3. API contracts and exact-money rules

    Service A: Cache API (wire protocol uses persistent pooled gRPC or Redis RESP connections; shown in HTTP style for clarity):

    GET    /v1/cache/{ns}/{key}                    -> 200 {value, version, ttl_ms} | 404 Not Found
    PUT    /v1/cache/{ns}/{key}?ttl_ms=60000       body: raw bytes (<= 1 MB)
           If-Match: <version>                     optional compare-and-set -> 200 {version} | 412 Precondition Failed
    DELETE /v1/cache/{ns}/{key}                    -> 200 OK (idempotent: deleting a missing key succeeds)
    POST   /v1/cache/{ns}:mget {keys: [...]}       -> 200 {hits: {...}, misses: [...]}
    Errors: 413 Payload Too Large (> 1 MB) | 429 / 503 BUSY + Retry-After
    
    In-process client & near-cache helper:
      cache.get_or_load(key, loader_fn, ttl_s)     # single-flight: coalesces concurrent misses into 1 loader call
    

    Service B: find-transfer-combinations API

    POST /v1/transfer-combinations
         Idempotency-Key: <uuid>                   prevents duplicate async jobs when clients retry timeouts
         X-Request-Deadline-Ms: 800                client timeout budget so workers never compute past caller timeout
         {
           "currency": "EUR",
           "target_minor": 50000,                  integer minor units (50000 cents = 500.00 EUR; NEVER floats!)
           "transfers": [
             {"id": "w1", "amount_minor": 18000},
             {"id": "w2", "amount_minor": 32000},
             {"id": "w3", "amount_minor": 45000}
           ],
           "max_results": 100,
           "distinct_by": "transfer" | "amount",
           "mode": "sync" | "async"
         }
      -> 200 {"combinations": [["w1", "w2"]], "complete": true, "stop_reason": null}
      -> 200 {"combinations": [...], "complete": false, "stop_reason": "max_results" | "budget"}
      -> 202 {"job_id": "job_91"}                  for mode="async" or large inputs routed to async queue
      -> 400 invalid input (n > 50 in sync mode, mixed currencies, floats, or amount_minor <= 0)
      -> 429 per-client rate limit exceeded | 503 load shed (Retry-After)
    

    Why integer minor units (amount_minor) are mandatory: in IEEE-754 binary floating point, 0.10 + 0.20 == 0.30000000000000004 != 0.30, which silently misses valid transfer combinations!

  4. Data model and in-memory structures

    Service A — Single-Node Segmented LRU (64 independent segments per namespace: hash(key) mod 64)
      Segment:
        lock          mutex protecting ONLY this 1/64th slice
        map           dict: key -> Node
        head, tail    dummy sentinel Nodes of a doubly linked list (head.next = MRU, tail.prev = LRU)
        used_bytes    current sum of entry bytes in this segment (<= namespace_capacity / 64)
        next_ver      monotonic uint64 counter assigned on every put for compare-and-set (CAS)
      Node:
        key, value (immutable bytes), size_bytes, expires_at_mono, version, prev, next
    
    Service A — Distributed Cluster Routing
      cluster_map     slot (0..16383) -> shard_id (0..7) -> {primary_addr, replica_addr, epoch}
                      stored in etcd / Redis Cluster gossip; cached in every client library
    
    Service B — Combination Request Canonicalization & Async Jobs
      canonical_req   transfers sorted by (amount_minor, id) + currency + target_minor + max_results
                      + distinct_by + max_nodes
      request_hash    SHA-256(canonical_req) -> key in Service A namespace "combos" (TTL = 10 min)
      async_jobs      (job_id PK, client_id, idempotency_key, request_hash, status, result_uri, created_at)
                      UNIQUE (client_id, idempotency_key)
    
  5. High-level architecture

     Service A: Distributed LRU Cache
       App Pods / Combination Workers
         +-- [L1 Near Cache: in-process 64-segment LRU for hot keys, TTL = 1-2 s]
         +-- [Smart Client: 16,384-slot map, single-flight misses, 5 ms timeout, per-shard circuit breaker]
                     | persistent binary connections (no proxy hop on the hot path)
            +--------+------------------------+
            v                                 v
       [Shard 0 Primary (AZ-a)]          [Shard 7 Primary (AZ-b)]     (64-segment LRU + TTL sweeper)
            | async replication               | async replication
            v                                 v
       [Shard 0 Replica (AZ-b)]   ...    [Shard 7 Replica (AZ-c)]
            ^
       [Control Plane (etcd / Sentinel): health checks, replica promotion, epoch bump]
    
     Service B: find-transfer-combinations API
       Clients --> [API Gateway: auth, body <= 64 KB, per-client token bucket & CPU-cost quota]
                         |
                         v
                   [Stateless Combination Pods (8 vCPUs = 8 isolated worker processes)]
                     1. Admission gate: 8 active workers + bounded queue (max 32 / 200 ms wait -> else 503)
                     2. Canonicalize & SHA-256 -> pod single-flight -> check Service A ("combos" namespace)
                     3. Worker process: bitset feasibility check -> pruned backtracking -> cache if eligible
                         | n > 30 high-cost or mode="async"
                         v
                   [Durable Job Queue] --> [Async Worker Pool] --> [Object Store + GET /v1/jobs/{id}]
    
  6. Deep dive 1: In-process thread-safe LRU and eviction invariants

    Why a textbook single-lock LRU collapses on multi-core servers: In an LRU cache, every get is also a write because a cache hit must unlink its node and move it to the head of the doubly linked list. Behind one global mutex, 32 CPU cores spend more time fighting over one contended CPU cache line (cache-line bouncing) than reading memory.

    Practical concurrency hierarchy (pick the simplest design that meets < 1 ms p99): 1. Lock striping (64 segments, chosen baseline): hash each key to hash(key) mod 64. Each segment owns an independent Lock, dict, doubly linked list, and 1/64 of the byte budget, cutting lock contention ~64x. Eviction is exact LRU per segment, which closely approximates global LRU across random hashes. 2. Debounce hot-key list moves: record last_bumped_at on each Node and skip unlinking/re-linking on get if it already moved within the last 1 second. Hot items stay near the head while turning 99% of hot reads into pure map lookups! 3. Buffered read ring buffers / CLOCK (if profiling ever demands lock-free reads): Java's Caffeine records read hits into lock-free striped ring buffers and replays list updates in batches; CLOCK sets an atomic referenced = 1 bit on reads and sweeps bits only during eviction. Both avoid lock writes on get at the cost of approximate eviction order.

    Five concurrency invariants enforced by every segment: - I1 (Map-list parity): segment.map and the doubly linked list contain the exact same Node set at the end of every lock acquisition. - I2 (Byte budget): segment.used_bytes <= segment.capacity holds before put releases segment.lock (oversize items > segment.capacity raise immediately instead of wiping the segment). - I3 (No expired reads): get checks expires_at <= time.monotonic() under the lock, unlinks expired nodes immediately, and returns None. - I4 (Immutable values): put allocates a brand-new Node rather than mutating bytes in place, so a thread that just returned from get holds safe, immutable bytes even if another thread evicts that key 1 microsecond later. - I5 (Monotonic CAS versions): every write increments segment.next_ver, enabling race-free compare-and-set (CAS) cache fills.

    import threading
    import time
    
    
    class Node:
        def __init__(self, key, value, size_bytes, expires_at, version):
            self.key = key
            self.value = value          # immutable bytes: safe for readers after concurrent eviction
            self.size_bytes = size_bytes
            self.expires_at = expires_at
            self.version = version
            self.prev = None
            self.next = None
    
    
    class LRUSegment:
        def __init__(self, capacity_bytes):
            self.lock = threading.Lock()
            self.capacity = capacity_bytes
            self.used_bytes = 0
            self.next_ver = 0
            self.map = {}
            # Dummy sentinel nodes eliminate all None checks on head/tail pointer updates.
            self.head = Node(None, None, 0, None, 0)
            self.tail = Node(None, None, 0, None, 0)
            self.head.next = self.tail
            self.tail.prev = self.head
    
        def get(self, key):
            now = time.monotonic()
            with self.lock:
                node = self.map.get(key)
                if node is None:
                    return None
                if node.expires_at is not None and node.expires_at <= now:
                    self._remove(node)
                    return None
                self._unlink(node)
                self._push_front(node)
                return node.value, node.version
    
        def put(self, key, value, size_bytes, ttl_s=None, expected_ver=None):
            if size_bytes < 0 or size_bytes > self.capacity:
                raise ValueError("entry size is negative or exceeds segment byte capacity")
            now = time.monotonic()
            with self.lock:
                old = self.map.get(key)
                if old is not None and old.expires_at is not None and old.expires_at <= now:
                    self._remove(old)
                    old = None
                if expected_ver is not None:
                    cur_ver = old.version if old is not None else 0
                    if cur_ver != expected_ver:
                        return None     # CAS precondition failed: a newer write won the race
                if ttl_s is not None and ttl_s <= 0:
                    if old is not None:
                        self._remove(old)
                    return 0
                if old is not None:
                    self._remove(old)
                self.next_ver += 1
                expires_at = (now + ttl_s) if ttl_s is not None else None
                node = Node(key, value, size_bytes, expires_at, self.next_ver)
                self.map[key] = node
                self._push_front(node)
                self.used_bytes += size_bytes
                while self.used_bytes > self.capacity:
                    self._remove(self.tail.prev)
                return node.version
    
        def _remove(self, node):
            self._unlink(node)
            del self.map[node.key]
            self.used_bytes -= node.size_bytes
    
        def _unlink(self, node):
            node.prev.next = node.next
            node.next.prev = node.prev
    
        def _push_front(self, node):
            node.next = self.head.next
            node.prev = self.head
            self.head.next.prev = node
            self.head.next = node
    

    Because lazy expiry only frees keys that are read again, a lightweight background TTL sweeper wakes every 100 ms, samples 20 random keys per segment under the lock (<50 µs), and deletes expired entries so dead keys never hog RAM.

  7. Deep dive 2: Distributed cache scaling, hot keys, failover, and consistency

    Managed Redis Cluster vs. custom segmented service: Use Redis Cluster (which maps keys via CRC16(key) mod 16384 hash slots across our 8 primaries + 8 replicas) for the shared tier unless profiling proves you need multi-threaded single-key throughput, strict byte quotas per tenant namespace, or server-side lease tokens—and embed our LRUSegment directly inside client pods as the L1 near cache!

    Preventing hot keys and cache stampedes: - Hot-key relief: client libraries sample 1% of reads into a heavy-hitter sketch. Keys crossing 5% of a shard's traffic enter the L1 near cache (TTL = 1–2 s): 500 app pods then query the shard at most 500 times/s instead of 50,000 times/s (80 Gbps -> 0.8 Gbps). - Stampede protection (single-flight): when a popular key expires, get_or_load stores an in-flight Future per key so 1,000 concurrent threads wait on one database query instead of firing 1,000 duplicate SQL reads.

    Cache-aside database consistency & the two subtle races: Standard cache-aside updates the database first and deletes (never overwrites!) the cache key so two concurrent writers cannot leave an older put behind. Two edge races remain:

    Race 1 — Stale cache fill:
      Reader R misses key K -> reads v1 from DB -> pauses (GC).
      Writer W writes v2 to DB -> DELETEs key K from cache.
      Reader R wakes up -> PUTs stale v1 into cache (stays stale until TTL)!
      Fix: include DB row_version on fills, or use lease tokens (DELETE invalidates outstanding miss tokens).
    
    Race 2 — Lost DELETE during async replica failover:
      Writer W writes v2 to DB -> DELETEs K on Primary -> Primary crashes 2 ms BEFORE async replication!
      Replica promotes to Primary still holding v1!
      Fix: every key carries a bounding TTL; for critical keys, tail the DB CDC log (Debezium) to replay idempotent DELETEs after any failover.
    

    Backpressure: cache servers cap in-flight requests and return BUSY immediately rather than growing unbounded socket queues; client circuit breakers trip on slow shards and rate-limit fallback DB queries so a cache hiccup never cascades into a database outage.

  8. Deep dive 3: Bounded backtracking engine, isolation, and caching

    Four-stage bounded solver inside each worker process: 1. Canonicalize: validate amount_minor > 0, sort transfers ascending by (amount_minor, id), and hash the canonical JSON with SHA-256 to form request_hash. 2. Fast O(n × target / 64) bitset infeasibility pre-check: when target_minor ≤ 10^7 (100,000.00 EUR, a 1.25 MB integer bitset), shift-and-OR one Python big integer in < 2 ms. If bit target_minor is 0, return ([], True, None) immediately without searching a single branch! 3. Sorted backtracking with two-sided pruning: because amounts are positive and sorted ascending, stop scanning loop index i immediately if amounts[i] > remaining (all later items are even larger) OR suffix[i] < remaining (even summing every remaining item falls short). 4. Accurate complete reporting: only flag stop_reason = "max_results" when the search actually proves a (max_results + 1)-th valid combination exists (so a unique solution with max_results = 1 truthfully returns complete = True!).

    def is_target_reachable(amounts, target):
        # Bit s of `reach` is 1 iff some subset of processed amounts sums to s.
        reach = 1
        mask = (1 << (target + 1)) - 1
        for amount in amounts:
            reach = (reach | (reach << amount)) & mask
        return ((reach >> target) & 1) == 1
    
    
    def find_combinations(amounts, target, max_results, max_nodes, distinct_by_amount=False):
        """amounts: positive ints sorted ascending.
        Returns (list_of_index_lists, is_complete, stop_reason).
        """
        n = len(amounts)
        # suffix[i] = sum of amounts[i..n-1] for fast underflow pruning.
        suffix = [0] * (n + 1)
        for i in range(n - 1, -1, -1):
            suffix[i] = suffix[i + 1] + amounts[i]
    
        results = []
        path = []
        state = {"nodes": 0, "stop_reason": None}
    
        def search(start, remaining):
            if remaining == 0:
                # Stop for max_results ONLY when a (max_results + 1)-th solution is hit,
                # so finding exactly max_results total solutions still reports complete=True.
                if len(results) >= max_results:
                    state["stop_reason"] = "max_results"
                    return
                results.append(list(path))
                return
    
            for i in range(start, n):
                if state["stop_reason"] is not None:
                    return
                # Sorted ascending + positive: if amounts[i] overshoots or suffix[i] falls short,
                # no index j >= i can succeed either -> prune the rest of this loop!
                if amounts[i] > remaining or suffix[i] < remaining:
                    return
                if distinct_by_amount and i > start and amounts[i] == amounts[i - 1]:
                    continue  # avoid emitting duplicate multisets of identical amounts
    
                state["nodes"] += 1
                if state["nodes"] > max_nodes:
                    state["stop_reason"] = "budget"
                    return
    
                path.append(i)
                search(i + 1, remaining - amounts[i])
                path.pop()
    
        search(0, target)
        return results, (state["stop_reason"] is None), state["stop_reason"]
    

    Zero shared mutable state & hard per-worker memory isolation: - Every call allocates local suffix, path, and results variables inside one worker process (8 processes per 8-vCPU pod in Python to bypass the GIL, or 8 threads in Go/Java). - Enforce an OS address-space limit (RLIMIT_AS = baseline + 64 MB) per worker process so a bug or giant payload raises MemoryError and recycles one worker instead of OOM-killing all 8 active requests in the pod. - Stateless vs. stateful workers: stateless pods pass the ≤50 transfers (~2 KB) in each request, making horizontal scaling and retries trivial. Only introduce sticky stateful pods (precomputing meet-in-the-middle 2^(n/2) half-sum tables per set_id) if analytics show clients querying hundreds of targets against the exact same static transfer list. - Caching rule: cache responses in Service A (ns = "combos", TTL = 10 min, payload ≤ 256 KB) when complete == True OR when stopped deterministically by max_results / max_nodes (since both are part of request_hash). Never cache responses cut off early by a caller's wall-clock deadline!

  9. Handling request spikes: rate limits, admission control, and scaling

    Because a 10x reconciliation burst arrives in under a minute while new pods take 60–90 s to boot, defend the fleet in layers from edge to worker:

    1. API Gateway token bucket + CPU-cost quota: cap each merchant's request rate and deduct actual CPU milliseconds returned in a response header so one client sending n = 50 worst-case payloads cannot starve fifty clients sending n = 10.
    2. Fast pod admission control (fail in 1 ms, not 2,000 ms): each pod allows 8 running searches + a bounded FIFO queue of 32 requests (or 200 ms estimated wait). Request #41 immediately receives 503 Service Unavailable + Retry-After, preserving low p99 latency for admitted calls.
    3. Deadline propagation: compute worker_time_budget = min(1000 ms, caller_deadline - queue_wait - 15 ms) and check the clock every 4,096 search nodes; return partial results (complete: false, stop_reason: "budget") before the caller times out!
    4. Priority classes & async offload: interactive UI calls preempt batch reconciliation jobs during shedding, and synchronous calls with n > 30 and high estimated branch counts return 202 Accepted onto the durable async queue.
    5. Pre-scaling + client retry budgets: schedule pod scale-out 10 minutes before known end-of-day bank cutoffs, keep 3x steady-state headroom during business hours, and require client SDKs to use exponential backoff with jitter plus a 10% retry budget so 503 responses never snowball into a retry storm.
  10. Observability, testing plan, and trade-off summary

    Key metrics & alerts: - Service A (Cache): hit ratio per namespace, server p50/p99/p999 latency, evictions/s (capacity vs ttl), segment byte-skew and lock wait time, BUSY count, replication lag, and top hot keys. - Service B (Combinations): latency and search nodes by n-bucket, complete=false rate by stop_reason, queue wait, 429/503 shed rate, single-flight coalesced hits, and "combos" cache hit rate. Never log raw transfer amounts/IDs in plaintext traces (financial data minimization).

    Rigorous testing plan: - Property-based & concurrency tests (LRU): fuzz LRUSegment against a single-threaded OrderedDict oracle using a fake monotonic clock for TTLs; stress 32 threads under ThreadSanitizer / -race verifying invariants I1–I5 and checking small-key histories with a linearizability checker (verifying concurrent operations behave as if executed in one valid atomic order). - Exactness cross-check (Combinations): fuzz find_combinations and is_target_reachable against a 2^n bitmask brute-force solver for n ≤ 15 across duplicate amounts, impossible sums, single-element exact max_results = 1, and tight max_nodes caps. - Spike & chaos load tests: ramp 200 -> 2,000 req/s in 30 s to verify p99 stays < 100 ms for small inputs while shedding absorbs minute 1; kill 1 of 8 Redis primaries at 500k ops/s to verify replica promotion and DB fallback rate-limiting.

    Core trade-offs: - 64-way lock striping vs. global lock: ~64x higher multi-core throughput in exchange for per-segment (near-global) LRU eviction. - L1 near cache + async Redis replicas vs. strict linearizable reads: absorbs 80 Gbps hot keys and protects the DB from 3.4x failover miss storms, accepting 1–2 s bounded staleness on hot/failover keys. - Stateless bounded workers (complete: false) vs. unbounded synchronous search: guarantees predictable latency and pod survival during spikes, requiring callers to inspect complete or poll async jobs for giant inputs.

Intuition & how it works

Think of these two paired services like a multi-lane coat check with a VIP desk notepad (Service A) backing an accountant matching bank wires under a strict stopwatch (Service B): - In Service A (the scalable LRU cache), putting one giant lock around a dictionary and a doubly linked list forces every CPU core into a single-file line because even a cache read (get) has to move its coat to the "most recently used" hook. Splitting each server's RAM into 64 independent striped lanes (hash(key) mod 64) lets 64 threads update their lanes in parallel, while a tiny 1–2 second near cache inside each client pod keeps 50,000 readers of one viral key from stampeding a single server's network card. - In Service B (find-transfer-combinations), matching n transfers to an exact payout target is the exponential subset-sum problem (2^n subsets). Before exploring branches, a 1-millisecond reachable-sum bitset (one big integer where bit s is 1 if some subset adds up to s cents) rejects impossible targets immediately; then sorted backtracking with upper/lower sum pruning and hard node budgets guarantees one tough request can never freeze a worker or starve everyone else during a 10x end-of-day burst.

Why do the naive designs fail? Protecting an in-process LRU cache with one global lock (or mistakenly using a read-write lock when get mutates linked-list pointers) either kills throughput or corrupts pointers under concurrent traffic, and sharding nodes with hash(key) mod num_nodes flushes almost the entire cache to the database whenever one server restarts. On the combination API, using binary float numbers (0.1 + 0.2 != 0.3) misses exact cent matches, unbounded recursion lets one 50-transfer payload spin for hours, and relying on Kubernetes autoscaling alone fails during sudden spikes because new pods take 60–90 seconds to start.

Walk through a concrete trace of a payout reconciliation query (transfers = [180, 180, 320, 450] cents, target = 500, max_results = 1, distinct_by = "amount") hitting both services:

1. Canonicalize & check caches:
   - Sort transfers ascending -> [180, 180, 320, 450]; hash canonical request -> req_hash = "7c4e...".
   - Pod checks single-flight map (not running) -> checks Service A namespace "combos":
     Client hashes "7c4e..." to slot 5820 -> Shard 3 -> Segment (hash mod 64 = 11) -> 404 Miss.

2. Fast bitset check + pruned backtracking inside an isolated worker process:
   - Reachable bitset shifts bits {0} -> {0,180} -> {0,180,360} -> {0,180,320,360,500} -> ...
     Bit 500 is 1 -> feasible! Precompute suffix sums = [1130, 950, 770, 450, 0].
   - i = 0 (180, rem = 320):
       - i = 1 (180, rem = 140): next i = 2 is 320 > 140 -> pruned immediately!
       - i = 2 (320, rem = 0):   HIT! results = [[0, 2]] (transfers 180 + 320 = 500).
       - i = 3 (450 > 320):      pruned!
   - Back at root (rem = 500):
       - i = 1 (180): distinct_by="amount" sees amounts[1] == amounts[0] at same depth -> skipped!
       - i = 2 (320, rem = 180): next is 450 > 180 -> pruned!
       - i = 3 (450): suffix[3] = 450 < 500 -> underflow-pruned immediately!
   - Search finishes naturally without hitting a 2nd solution -> returns ([[0, 2]], complete=True)!

3. Store in Service A ("combos", TTL = 600 s):
   - Segment 11 acquires its local mutex, inserts Node("7c4e...", size=96 B, version=1), pushes to head,
     evicts tail.prev if segment.used_bytes > segment.capacity, and serves retry spikes in < 1 ms!

Key trade-offs

  • 64-way lock striping vs. exact global LRU order. Lock striping (splitting one cache into 64 independent hash-partitioned segments, each with its own lock, hash map, and doubly linked list) eliminates multi-core lock bottlenecks while keeping simple, verifiable code, at the minor cost of evicting the oldest item within one 1/64th segment rather than strictly across all 64 segments. Moving to buffered ring-buffer reads (like Java's Caffeine) or CLOCK (a lock-free bit-sweeping approximation of LRU) squeezes out even higher read concurrency if needed, at the price of looser eviction accuracy and trickier concurrency verification.
  • Managed Redis Cluster vs. custom distributed cache service. Redis Cluster gives battle-tested 16,384-slot sharding, cross-zone replication, and automatic failover out of the box, but runs commands on a single thread per node and uses sampled approximate LRU. Building a custom distributed server around our multi-threaded LRUSegment is only justified when measurements prove you need multi-core throughput per shard, strict per-namespace byte quotas, or server-side lease tokens (miss tokens invalidated by deletes to block stale database fills).
  • Cross-AZ replicas vs. memory cost. Doubling from 8 nodes to 16 nodes (8 primaries + 8 replicas) is not about disk durability—it prevents a single node crash from turning 53.4k hits/s into misses and multiplying database load by 3.4x (22.5k -> 75.9k reads/s). Asynchronous replication keeps write latency sub-millisecond in exchange for potentially losing the last few milliseconds of writes or invalidations during a crash.
  • L1 near cache vs. strict read freshness. Caching detected hot keys for 1–2 seconds inside client pods collapses a dangerous 80 Gbps single-key read storm down to a few hundred reads per second, trading up to 2 seconds of staleness on those specific hot keys.
  • Delete-on-write vs. overwrite-on-write in cache-aside. Deleting the cache key after committing a database update forces one extra cache miss on the next read, in exchange for preventing two concurrent writers from racing their PUTs out of order and leaving an overwritten old value stuck in cache.
  • Stateless vs. stateful combination workers. Sending all ≤ 50 transfers (~2 KB) in every request keeps workers stateless (any pod can handle any request, crashes need zero state rebuild, and scaling just adds pods). Pinning precomputed meet-in-the-middle tables (2^(n/2) half-subset sums) onto stateful pods via consistent hashing (a hash ring where adding or removing a pod moves only 1/N of keys) speeds up repeated queries against a static transfer set, at the cost of sticky routing and cache warm-up on pod restarts.
  • Bounded partial answers (complete: false) vs. unbounded synchronous execution. Enforcing max_results, max_nodes, and caller deadlines keeps CPU and tail latency predictable for the whole fleet, requiring clients to check complete or use the 202 Accepted async job API for oversized reconciliations.
  • Fast load shedding (503) vs. deep request queues. Rejecting excess burst traffic in 1 ms once the 200 ms pod queue fills keeps admitted requests fast, whereas deep queues make every request time out after callers have already hung up.

Common mistakes

  • Using a ReadWriteLock on get while still moving the hit node to the list head. Every LRU hit mutates prev/next pointers on up to four linked-list neighbors; running that under a shared read lock corrupts the doubly linked list and causes infinite loops or crashes under multi-threaded load.
  • Sizing cache capacity by item count (max_entries = 1,000,000) instead of bytes. A million 64 B counters take ~100 MB, whereas a million 1 MB blobs need 1 TB and trigger an out-of-memory crash long before LRU eviction kicks in.
  • Relying solely on lazy TTL expiration during get. Keys with a 5-minute TTL that are written once and never read again sit in RAM as "zombie bytes" until LRU pressure eventually pushes them to the tail; pair lazy checks on get with a bounded periodic background sweeper.
  • Partitioning distributed cache nodes with hash(key) mod num_nodes. Adding or losing 1 server in an 8-node cluster remaps 7/8 (87.5%) of all keys simultaneously, causing a massive cache stampede (thousands of simultaneous misses overwhelming the database). Use 16,384 fixed hash slots or consistent hashing with virtual nodes.
  • Marking complete = False as soon as len(results) == max_results. If an input has exact total solution count equal to max_results (for example, 1 unique matching pair when max_results = 1), stopping before verifying whether another branch succeeds falsely tells the user the answer is incomplete. Only set stop_reason = "max_results" when a (max_results + 1)-th solution is actually reached!
  • Using floating-point numbers (float) or allowing negative amounts in pruned subset-sum. Binary floats break exact equality (0.1 + 0.2 != 0.3), and negative numbers invalidate both amounts[i] > remaining and suffix[i] < remaining pruning (and crash bit-shift reachability checks).
  • Caching combination responses that were cut short by a wall-clock deadline. Wall-clock progress depends on noisy-neighbor CPU load and the first caller's tight timeout; caching a deadline-truncated partial result serves a truncated answer to a later caller who had plenty of budget. Only cache complete results or deterministic max_results / max_nodes cutoffs.
  • Retrying 503 spike errors immediately without jitter or a retry budget. Synchronization across retrying clients turns a 30-second reconciliation spike into a self-inflicted outage (retry storm).

Follow-up questions

  • If one thread reads a cached entry just microseconds before another thread evicts that key, is correctness violated and how is memory freed safely? Correctness is completely preserved—that execution is linearizable (get ordered right before the evicting put) as long as cached value buffers are immutable and deallocation waits for active readers. Because put always constructs a fresh Node rather than overwriting node.value in place, the reading thread holds a valid, unchanging byte slice from the moment of lookup while eviction simply unlinks the node from future map and list traversals. Managed runtimes (Python, Go, Java) keep the byte buffer alive automatically until the reader finishes; in non-GC languages (C++ or Rust), wrap payloads in atomic reference counts (std::shared_ptr / Arc) or epoch-based reclamation so memory is never freed while a reader is still writing bytes to the network socket.
  • How does your solver behave when a caller submits dozens of identical transfer amounts that yield billions of valid index subsets? For instance, 40 identical 100 EUR transfers against a 2,000 EUR target produce C(40, 20) ≈ 137.8 billion index combinations, which must never be materialized in full. Under distinct_by = "transfer", the worker emits the first max_results (<= 1,000) subsets in milliseconds and returns complete: false, stop_reason: "max_results" upon reaching combination max_results + 1. Better yet, setting distinct_by = "amount" skips duplicate values at the same recursion level and collapses all 137.8 billion subsets into one canonical multiset (20 x 100 EUR, complete: true) in 20 steps, optionally paired with an O(n * target) dynamic-programming counter if finance wants the exact count of transfer-ID subsets.
  • What changes are needed if candidate inputs can include negative credit memos or fee adjustments alongside positive transfers? Split inputs into negative adjustments (sum S_neg < 0) and positive transfers (sum S_pos > 0). In the reachable-sum bitset, offset coordinates by -S_neg so bit 0 represents S_neg and negative items perform right-shifts reach >> abs(a). In sorted backtracking (still ordered ascending from most negative to most positive), replace positive-only checks with signed suffix bounds (min_suffix[i] summing remaining negatives and max_suffix[i] summing remaining positives), pruning whenever remaining < min_suffix[i] or remaining > max_suffix[i], and lower the synchronous cap from n = 50 to n = 35 because mixed signs prune less aggressively.

Follow-up questions

Similar questions

More Adyen interview questions

All 4 Adyen questions →