Semantic Cache with Deduplication Under Concurrent Load
System DesignModel answerLast 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
- Similarity matching: How you decide two inputs are "the same" and can share an output
- Storage and indexing: Where and how you store canonical inputs, outputs, embeddings, and version metadata
- Concurrency control: How you collapse duplicate or near-duplicate requests into a single compute job
- Versioning and invalidation: How you handle pipeline updates without returning stale or inconsistent results
- 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Semantic Cache with Concurrency Control
1. Clarifying Questions and Scale Estimation
Start by confirming scope:
- What counts as "similar enough"? A similarity threshold based on embeddings is typical, but domain-specific rules may apply. For example, in a medical or financial context, negations or numbers changing should not share outputs even if embeddings are close.
- Namespace isolation? Assume multi-tenant; cache entries are scoped per tenant and per task type.
- Capacity estimate: At 8,000 QPS peak with 80% hit rate, that's 1,600 cache misses/second. Each miss takes ~2.5s, so roughly 4,000 concurrent compute jobs. Storage: assume 10M unique canonicals per month, each needing ~1.5 KB embedding + ~5 KB output = 65 GB/month, easily handled by modern databases.
2. High-Level Architecture
User Request
↓
API Gateway (auth, rate limiting)
↓
Cache Coordinator (Redis + SingleFlight)
↓
┌─────────────┬──────────────┬───────────────┐
│ Tier 1: │ Tier 2: │ Tier 3: │
│ Exact match │ Semantic ANN │ Compute & store│
└─────────────┴──────────────┴───────────────┘
↓
Primary Database (canonicals, aliases, versions)
Vector Index (FAISS/Milvus/pgvector)
Object Store (outputs)
3. Similarity Strategy: Two-Tier Matching
Tier 1: Deterministic Canonicalization
Normalize input text through versioned rules:
- Unicode normalization (NFKC)
- Whitespace collapse, punctuation standardization
- Lowercasing (except case-sensitive tokens)
- Abbreviation expansion from a curated dictionary
Compute:
exact_key = SHA256(tenant_id || task_type || version_id || normalized_text)
This catches trivial variations at near-zero cost. Check Redis and the aliases table for this key first.
Tier 2: Semantic Matching via Embeddings
If Tier 1 misses:
- Encode the normalized text using a small, fast embedding model (e.g., a distilled sentence transformer, ~15ms on GPU)
- Query an approximate nearest neighbor (ANN) index partitioned by
(tenant, task, version) - Accept the top match only if cosine similarity ≥ threshold (e.g., 0.92) and optional guardrails pass
Domain Guardrails (Optional but Recommended)
For sensitive domains, extract a critical-fact signature: negations, numbers, dates, named entities. Two inputs share an output only if their signatures match exactly. This prevents semantic drift in high-stakes scenarios.
Stickiness: Enforcing Consistency
Once a semantic match is accepted, write an alias mapping exact_key → canonical_id. This mapping is write-once and immutable. Future occurrences of that exact input always resolve to the same canonical, preventing flip-flopping if the index changes.
4. Data Model
Use a strongly consistent database (Postgres, CockroachDB, or Spanner) as the source of truth. Redis and the vector index are derived caches.
pipeline_versions (
version_id UUID PRIMARY KEY,
model_checkpoint TEXT,
config_hash TEXT,
normalizer_version INT,
similarity_threshold FLOAT,
status ENUM('shadow', 'active', 'retired'),
created_at TIMESTAMP
)
canonicals (
canonical_id UUID PRIMARY KEY,
tenant_id UUID,
task_type TEXT,
version_id UUID REFERENCES pipeline_versions,
normalized_text_hash TEXT,
embedding_ref TEXT, -- pointer to vector index or blob
output_ref TEXT, -- S3/GCS object key
state ENUM('pending', 'ready', 'failed'),
created_at TIMESTAMP,
INDEX (tenant_id, task_type, version_id, state)
)
aliases (
exact_key TEXT PRIMARY KEY,
canonical_id UUID REFERENCES canonicals,
match_type ENUM('exact', 'semantic'),
similarity FLOAT,
created_at TIMESTAMP
)
active_versions (
tenant_id UUID,
task_type TEXT,
version_id UUID,
PRIMARY KEY (tenant_id, task_type)
)
Outputs live in encrypted object storage; embeddings live in a partitioned vector index.
5. Request Flow
- Normalize and hash: Compute
exact_keyfrom normalized input - Redis check: Look up
exact_key → outputin Redis (TTL ~1 hour) - Alias check: Query the
aliasestable - Semantic search: Embed input, query ANN index plus in-memory pending registry (see §6)
- Compute or wait: If no match, claim a new canonical, acquire a lease, compute, store output, mark ready, publish completion
- Populate caches: Write alias, update Redis, return result
6. Concurrency Control: Preventing Cache Stampedes
This is the core challenge. Two mechanisms:
A. Identical Inputs (Same exact_key)
-
In-process SingleFlight: Within a single server, collapse duplicate requests using a mutex keyed on
exact_key. Only one goroutine/thread computes; others block and share the result. -
Distributed Lease: Across servers, acquire a Redis lock:
SET lease:{exact_key} {worker_id} NX PX 10000- Winner computes and renews the lease via heartbeat
- Losers subscribe to a Redis pub/sub channel
done:{exact_key}or poll with exponential backoff - If the winner crashes, the lease expires and a waiter takes over
-
Idempotent writes: The unique constraint on
aliases.exact_keyensures duplicate computes (after lease expiry) are harmless.
B. Near-Identical Inputs (Different exact_key, Similar Embeddings)
Two slightly different texts produce different hashes, so the lease doesn't help. Solution:
- Insert the new canonical with
state=pendingbefore starting inference - Add its embedding to an in-memory pending index on the coordinator node
- Route requests by
(tenant, task, version)partition to a coordinator shard - That shard serializes "search ANN + pending, then claim or attach" logic
- A near-duplicate arriving milliseconds later finds the pending canonical, writes an alias pointing to it, and waits on the same completion event
The pending set is small (~5k entries cluster-wide at 1,600 misses/s × 3s), so brute-force cosine search is acceptable. Alternatively, maintain a small HNSW index per coordinator.
C. Backpressure
- Cap the inference job queue
- Return HTTP 429 or async job handles when saturated
- Prioritize interactive traffic over batch reprocessing
7. Versioning and Invalidation
Rolling Out a New Pipeline
- Deploy the new version with
status='shadow' - Dual-write: new requests create canonicals under the new
version_id, but the old version remains active for reads - Backfill or warm the cache by re-embedding a sample of popular inputs under the new version
- Atomically flip
active_versionsto the newversion_id - Mark the old version
retired; optionally purge or archive old canonicals after a grace period
Why Version Isolation Matters
Mixing outputs from different models or prompt templates breaks consistency. By partitioning the vector index and alias table by version_id, you ensure:
- Old inputs under the old version continue to resolve correctly during the transition
- New inputs go to the new version immediately after cutover
- No cross-contamination
8. Edge Cases and Trade-offs
- Borderline similarity: If the threshold is crossed by noise, use a two-phase approach: fast embedding for recall, then a slower cross-encoder for precision on borderline cases.
- Worker crash mid-compute: Lease expiry allows recovery. The alias write is idempotent, so duplicate work is safe.
- Index rebuild: Keep the alias table intact. Rebuild the vector index from
canonicalswherestate=ready. Aliases prevent churn. - Privacy: Normalize and hash in a way that doesn't leak PII. Store embeddings and outputs encrypted at rest. Log only hashes, not raw text.
9. Complexity and Latency Breakdown
Cache hit path (~30ms p99):
- Normalize + hash: 1ms
- Redis lookup: 2–5ms
- Embedding (if Tier 2): 15ms
- ANN search: 10ms
- Fetch output: 5ms
Cache miss path (~2.5s):
- Lease acquisition: 5ms
- Inference: 1.5–3s
- Store + publish: 50ms
10. Summary
This design delivers:
- Fast exact matching via normalization + hashing
- Semantic matching via embedding ANN with version isolation
- Stampede prevention using distributed leases + pending registries
- Consistency through write-once aliases and version partitioning
- Graceful version transitions without stale output contamination
The key insight: treat the cache as a content-addressable store with deduplication at two levels—deterministic and semantic—and use distributed coordination primitives to collapse concurrent work, not just sequential lookups.