KatInterview

Semantic Cache with Deduplication Under Concurrent Load

System DesignModel answer
HardModel answerSystem Designcachingconcurrencyembeddings

Last updated

Build a cache that recognizes semantically equivalent inputs, avoids redundant expensive computation when similar requests arrive concurrently, and keeps outputs consistent.

Problem

You're building a backend service that processes text inputs through an expensive pipeline—think model inference, complex transformations, or multi-stage analysis. The pipeline takes 1–3 seconds per request. Users frequently submit inputs that are semantically identical but lexically different: extra whitespace, reordered clauses, synonyms, or minor rewording.

Your task is to design a system that:

  • Recognizes when two inputs are "close enough" to share the same output
  • Returns cached results for equivalent inputs with sub-100ms latency
  • Prevents duplicate work when many similar requests arrive at the same time (a cache stampede)
  • Maintains consistency: once an input maps to an output, that mapping is stable
  • Supports pipeline updates (new models, new logic) without mixing results from different versions

Scale and Constraints

  • Throughput: 3,000 requests/second average, 8,000 peak
  • Latency: <100ms p99 for cache hits; 1.5–3s for cache misses
  • Cache hit rate: assume 80% once warmed
  • Concurrency: hundreds of near-identical requests can arrive in a burst
  • Versioning: the processing pipeline changes periodically; outputs must never mix versions

What to Cover

  1. Similarity matching: How you decide two inputs are "the same" and can share an output
  2. Storage and indexing: Where and how you store canonical inputs, outputs, embeddings, and version metadata
  3. Concurrency control: How you collapse duplicate or near-duplicate requests into a single compute job
  4. Versioning and invalidation: How you handle pipeline updates without returning stale or inconsistent results
  5. Edge cases: What happens when the threshold is borderline, when a worker dies mid-computation, or when the index updates

Provide a high-level architecture, data models, request flow, and a deep-dive into the stampede-prevention mechanism.

Hints

Hint 1

Think about two tiers of matching: a fast deterministic step for exact or near-exact matches, then a semantic layer using embeddings for paraphrases.

Hint 2

Use a distributed lock or coordination primitive to ensure only one worker computes the result for a given input, while others wait and reuse that result.

Hint 3

Version every cached entry so that pipeline changes trigger recomputation rather than returning outputs from an old model.