Semantic Caching and Coalescing for Clinical Extraction
Medium · System Design · Software Engineer · Onsite
Prompt
A clinical document intelligence platform ingests free-text chart excerpts, clinician notes, and structured prompts to extract structured medical records (such as clinical risk factors or medical billing codes). Running the extraction model plus deterministic post-processing is expensive, yet real-world traffic contains heavy repetition: notes routinely differ only in whitespace, capitalization, shorthand, or synonymous clinical wording while conveying the exact same meaning.
Design a backend caching and request-coalescing system that guarantees identical structured outputs for equivalent inputs, safely reuses prior computations, and prevents duplicate model runs under concurrent load.
Functional Requirements
- Structured extraction API: Accept clinical text payloads and return the extracted structured record.
- Equivalence matching: Identify whether an incoming payload matches an earlier input either after deterministic normalization or via a configurable semantic similarity cutoff.
- Canonical output repeatability: Ensure all inputs deemed equivalent within a pipeline version return the exact same authoritative output.
- Safe pipeline evolution: Isolate and roll out updates to model weights, prompt templates, or post-processing rules using explicit versioning or invalidation so stale answers never mix with updated logic.
Non-Functional Targets
- Latency: Keep cache-hit p99 latency under
100 ms; an uncached inference and post-processing pass requires1.5–3.0 sat p99. - Traffic scale: Sustain
3,000 QPSon average and8,000 QPSduring peak bursts. - Stampede protection: Collapse concurrent identical or paraphrased cache misses so traffic bursts do not trigger redundant GPU runs.
- Durability and fault tolerance: Persist canonical outputs and lookup mappings across node failures so previously returned answers never disappear or change.
Scope & Expectations
- Multi-tier similarity & clinical guardrails: Explain how deterministic text normalization combines with embedding search and domain safety checks to separate harmless wording variants from clinically distinct notes (such as negations or numeric changes).
- In-flight request coalescing: Show how concurrent exact and near-duplicate misses are deduplicated across servers without race conditions or stale overwrites.
- Versioned storage & rollout lifecycle: Define schemas for immutable canonical records, lookup maps, and vector indexes, and detail how model, prompt, or threshold updates deploy safely.
Step-by-step walkthrough
Clarify requirements and the cost of errors
Before drawing boxes, pin down what "similar" and "consistent" mean in a clinical setting, because the two possible caching mistakes have wildly different costs:
- A false miss (recomputing an input we could have reused from cache) wastes 1.5 to 3 seconds of GPU model inference.
- A false merge (reusing a cached output for an input with a different clinical meaning) returns the wrong risk factor or medical billing code.
"Patient denies chest pain"and"Patient reports chest pain"differ by one word and sit very close in standard text embeddings, yet their clinical meanings are opposites.
Therefore, our core rule is conservative reuse: when in doubt, treat the input as a miss and run the model.
Key scope assumptions to confirm with the interviewer:
- Tenant isolation: Clinical notes contain Protected Health Information (PHI) (identifiable patient medical data regulated by privacy laws like HIPAA). Every cache lookup and vector index is strictly isolated per tenant (customer healthcare organization) so patient-derived outputs never cross organizations.
- Task isolation: Each extraction workflow (
risk_factors,billing_codes) has its own prompt, post-processing rules, and cache namespace. - Why store outputs instead of relying on model determinism: Even with greedy decoding (always picking the highest-probability next token at temperature 0), GPU floating-point matrix math is not guaranteed to be bit-for-bit identical across varying batch sizes or hardware types. Thus, consistency comes from storing and re-serving the first committed output, never from hoping a re-run produces the same JSON.
- Synchronous with async fallback: Callers wait up to a configurable budget (default 5 seconds) for an answer; if inference is still queued, the API returns
202 Acceptedwith a job ID to poll.
Exact consistency contract: Within a
(tenant, task, pipeline_version)namespace, every input resolves to one canonical record (the single authoritative reference entry for a group of equivalent inputs). A canonical record's output is written once and never overwritten, and once a specific input text maps to a canonical record, future copies of that text stick to that same record unless an operator explicitly revokes it or tightens similarity rules.Back-of-the-envelope capacity and latency math
Let's size compute, memory, storage, and latency from the prompt's 3,000 average QPS and 8,000 peak QPS:
1. Traffic Average: 3,000 QPS * 86,400 s/day ≈ 259M requests/day Peak: 8,000 QPS 2. Assumed cache hit split (instrument and measure in production) Tier 1 (exact match after text normalization): 50% Tier 2 (semantic vector match): 30% Cache miss (must run GPU inference): 20% 3. GPU inference concurrency at peak Peak misses: 20% * 8,000 QPS = 1,600 inference jobs/s By Little's Law (concurrent_jobs = arrival_rate * avg_duration): With cache: 1,600 jobs/s * 2.0 s ≈ 3,200 in-flight jobs Without cache: 8,000 jobs/s * 2.0 s ≈ 16,000 in-flight jobs (5x GPU fleet!) 4. Embedding generation load Only Tier-1 misses need embeddings: 50% * 8,000 QPS = 4,000 embeddings/s peak Small GPU-batched encoder (e.g., 384-dim clinical model): <= 20 ms p99 5. Storage and memory growth New canonical records (only the 20% misses create new clusters): 20% * 3,000 QPS = 600 new records/s ≈ 52M records/day Durable JSON outputs (~2 KB each): 52M/day * 2 KB ≈ 104 GB/day on replicated disk/KV storage In-memory vector index (30-day active search window): Raw 384-dim float16 vector = 768 B (~40 GB/day raw, kept on disk) Compressed in RAM with Product Quantization (~96 B) + HNSW graph links (~128 B) + ID metadata ≈ 250 B/vector -> 52M * 250 B ≈ 13 GB/day -> ~390 GB for 30 days -> Fits comfortably across 12 shards of 64 GB RAM (768 GB total, ~50% headroom) Sticky exact-map rows (written on every Tier-1 miss = 30% semantic + 20% miss = 50%): 50% * 3,000 QPS = 1,500 new mappings/s ≈ 130M/day * ~100 B ≈ 13 GB/day 6. Hit-path latency budget (target: < 100 ms p99) API gateway + auth + routing: 5 ms Text canonicalization + SHA-256 hash: 1 ms Tier-1 lookup (Redis + KV fallback): 2-5 ms --> Tier-1 exact hit returns in ~15 ms! GPU embedding generation: 20 ms Parallel ANN vector search (top 5): 10 ms Fetch exact vectors, re-score & guard: 5 ms Async/fast sticky exact-map insert: 5 ms --> Tier-2 semantic hit returns in ~50 ms!Three architectural conclusions jump right out of these numbers:
- The cache protects GPU survival, not just latency. Losing the cache during a model upgrade would instantly multiply GPU demand by 5x, so version rollouts require cache warm-up.
- Index only canonical representatives (52M/day), never every request (259M/day). Indexing every alias wastes 5x the expensive RAM without adding new clusters.
- In-flight compute is small (~3,200 pending jobs across the whole platform). Deduplicating concurrent near-identical misses does not need a complex distributed vector index—an exact in-memory scan inside a shard coordinator is under a millisecond.
API design
Expose a clean extraction API that makes versioning and provenance explicit to clinical reviewers and audit logs:
POST /v1/extract Headers: Authorization: Bearer <token> Body: { "task": "risk_factors" | "billing_codes", "input": { "text": "Pt denies chest pain. BMI 31.0 kg/m2" }, "pipeline_version": "rf-v12", // optional pin; defaults to tenant's active version "wait_ms": 5000 // optional sync wait budget before async fallback } 200 OK: { "result_id": "can_8f2c91a0", // ID of the canonical record "output": { "codes": ["E66.9"], "risk_factors": ["obesity"] }, "pipeline_version": "rf-v12", "match": { "type": "exact" | "semantic" | "computed", "score": 0.984 } } 202 Accepted: { // returned if inference exceeds wait_ms "job_id": "can_8f2c91a0", "poll_url": "/v1/jobs/can_8f2c91a0" } GET /v1/jobs/{job_id} // returns 202 while running, 200 OK body once done GET /v1/results/{result_id} // audit endpoint: version, match metadata, output Admin & Rollout Endpoints (authenticated, audit-logged): POST /v1/pipelines/{task}/versions // register new model/prompt/rule bundle in shadow mode POST /v1/pipelines/{task}/rollout // ramp active version for selected tenants PUT /v1/similarity/{task}/config // update threshold or guard rules -> new sim_version POST /v1/results/{result_id}/revoke // invalidate a flawed canonical outputReturning
result_id(the canonical record ID) andmatch.typelets auditors verify externally that two clinically equivalent notes received the exact same canonical record under the samepipeline_version.Data model and versioned namespaces
We separate immutable canonical outputs from fast lookup mappings, and bake version IDs into every key and namespace so two versions can never mix:
1. pipeline_versions (Postgres; small config table) - (task, pipeline_version) PK - model_checkpoint, prompt_hash, rules_version, postproc_version - status: SHADOW | RAMPING | ACTIVE | RETIRED 2. similarity_configs (Postgres; small config table) - (task, sim_version) PK - canon_version, embed_model, accept_threshold, gray_threshold, guard_version 3. exact_map (Durable KV store like DynamoDB/Cassandra + Redis hot cache) - PK: (tenant, task, pipeline_version, canon_version, sha256_canonical_text) - Columns: canonical_id, match_type, match_score, created_at - Write-once sticky pointer: once mapped, future identical inputs skip vector search! 4. canonical_records (Durable KV store, replicated across 3 availability zones) - PK: canonical_id - tenant, task, pipeline_version, sim_version - encrypted_text_ref // pointer to clinical text encrypted with tenant KMS key - exact_embedding // uncompressed float16 vector for exact re-scoring - guard_signature // extracted numbers+units, negations, laterality - status // PENDING | DONE | FAILED | REVOKED - fencing_token // integer attempt counter preventing stale worker writes - raw_model_output_ref // pre-post-processing output for GPU-free rule backfills - output_json // write-once final structured output - created_at 5. vector_index (In-memory HNSW shards, rebuildable from canonical_records) - Namespace: (tenant, task, pipeline_version, sim_version) - Stores compressed vectors ONLY for DONE canonical records from the last 30 days 6. request_log (Append-only stream -> data warehouse) - request_id, tenant, exact_key, canonical_id, match_type, score, latency_ms, ts - Used asynchronously to count hits per canonical_id without mutating hot KV rows!Keeping
canonical_recordsstrictly write-once (apart from status movingPENDING -> DONEorREVOKED, never updating ahit_countcolumn on reads) avoids write contention on popular clinical snippets and allows resolver nodes to cache hotcanonical_id -> output_jsonentries in local memory with zero staleness bugs.High-level architecture
Clients (Clinical UI, Batch Chart Jobs) | v +-------------------+ | API Gateway | Auth, tenant extraction, rate limits +---------+---------+ | Consistent-hash route by hash(exact_key) v +-------------------------------------------------------------------------+ | Stateless Resolver Nodes (with local Singleflight + tiny hot-output LRU)| | | | Step 1: Canonicalize + SHA-256 --> [Redis] -> [exact_map KV] ---> HIT! | | | (miss: 50%) (~15ms)| | v | | Step 2: Generate embedding ------> [Batched Embedding GPU Pool] | | | | | v | | Step 3: Search top-5 candidates -> [Sharded HNSW Vector Index] | | | | | v | | Step 4: Fetch exact vectors, re-score cosine + clinical guard | | |-- pass (30%) -> write sticky exact_map ------------> HIT! | | | (miss: 20%) (~50ms)| +-------------|-----------------------------------------------------------+ v +-------------------------------------------------------------------------+ | Namespace Coordinators (sharded by tenant+task+version; single-threaded)| | - Exact scan of ~3,200 PENDING + last-2s DONE vectors (< 1 ms) | | - Match found? Attach caller to existing canonical_id | | - No match? Create PENDING canonical_record & enqueue compute job | +-----------------------------------+-------------------------------------+ v [Inference Queue] -> [GPU Inference + Deterministic Post-Proc] | v Conditional Commit (PENDING -> DONE if fencing_token matches) + Insert into HNSW Index + Publish done(canonical_id) | v Waiting resolvers wake via Pub/Sub (with 200ms KV poll backup), write their own sticky exact_map entry, and return 200 OKEvery request takes one of three clean paths:
- Tier-1 Exact Hit (~50%, ~15 ms): Normalize formatting, hash the text, find
canonical_idin Redis orexact_map, and return the immutable output. - Tier-2 Semantic Hit (~30%, ~50 ms): Embed the normalized text, search the Approximate Nearest Neighbor (ANN) vector index (an index structure like HNSW—Hierarchical Navigable Small World graph—that finds near-optimal closest vectors in milliseconds without scanning millions of rows), verify exact cosine similarity and clinical safety guards, save a sticky
exact_maprow so next time is a Tier-1 hit, and return the output. - Cache Miss (~20%, ~1.5–3 s): Hand off to the namespace coordinator, which collapses identical and near-identical concurrent misses into a single GPU job and broadcasts the committed result to all waiters.
- Tier-1 Exact Hit (~50%, ~15 ms): Normalize formatting, hash the text, find
Deep dive 1: Two-tier similarity and clinical safety guards
Why two tiers instead of embedding everything? Tier 1 costs ~1 ms of CPU and has zero risk of merging distinct medical facts, shedding half our traffic before touching GPUs.
Tier 1 — Deterministic canonicalization: We apply Unicode NFKC normalization (converting compatibility characters like non-breaking spaces or full-width digits into standard ASCII), strip invisible zero-width characters, lowercase text, collapse repeated whitespace, sort JSON keys, and drop transport metadata like
request_id. Crucially, we never strip negation words (no,denies,without), numbers, units, left/right laterality, or section headers (Family History:).Tier 2 — Exact re-scoring plus a clinical guard: Because our in-memory HNSW shards use Product Quantization (PQ) (compressing vectors into compact codebooks to cut RAM ~8x), raw ANN scores have slight quantization noise—too blurry for a strict threshold near
0.97. So we fetch the top 5 candidates'canonical_records, compute exact cosine similarity using their uncompressedexact_embedding, and accept the top match only if all three checks pass:- Exact cosine similarity
>= accept_threshold(e.g.,0.97, tuned empirically per task). - Comparable text length (length ratio between
0.80and1.25, preventing a 1-line snippet from matching a 10-line note that contains it). - Identical clinical guard signature: every number+unit pair, negated term, and laterality word (
left,right,bilateral) matches exactly.
import hashlib import re import unicodedata NEGATION_WORDS = {"no", "not", "denies", "denied", "without", "negative", "absent"} LATERALITY_WORDS = {"left", "right", "bilateral"} ZERO_WIDTH_CHARS = ("\u200b", "\u2060", "\ufeff") def canonicalize(text: str) -> str: # Normalize Unicode compatibility forms and strip invisible characters cleaned = unicodedata.normalize("NFKC", text) for ch in ZERO_WIDTH_CHARS: cleaned = cleaned.replace(ch, "") cleaned = cleaned.lower() # Collapse tabs, newlines, and multiple spaces into single spaces cleaned = re.sub(r"\s+", " ", cleaned) return cleaned.strip() def build_exact_key( tenant: str, task: str, pipeline_ver: str, canon_ver: str, raw_text: str ) -> str: # Include tenant and version IDs so rollouts and customers never collide fields = [tenant, task, pipeline_ver, canon_ver, canonicalize(raw_text)] joined = "\x1f".join(fields).encode("utf-8") return hashlib.sha256(joined).hexdigest() def normalize_number_token(token: str) -> str: # Turn "31.0" into "31" without float rounding that could corrupt long IDs if "." in token: token = token.rstrip("0").rstrip(".") return token def extract_guard_signature(canonical_text: str) -> tuple: # Extract critical clinical facts that embeddings frequently blur together tokens = re.findall(r"\d+(?:\.\d+)?|[a-z][a-z0-9/]*", canonical_text) numbers_with_units = [] negated_targets = [] laterality_terms = [] for i, token in enumerate(tokens): next_word = tokens[i + 1] if i + 1 < len(tokens) else "" if token[0].isdigit(): numbers_with_units.append(f"{normalize_number_token(token)} {next_word}") elif token in NEGATION_WORDS: negated_targets.append(next_word) elif token in LATERALITY_WORDS: laterality_terms.append(token) return ( tuple(sorted(numbers_with_units)), tuple(sorted(negated_targets)), tuple(sorted(laterality_terms)), )Let's trace three clinical pairs through these two tiers:
Pair 1: "Patient DENIES chest pain.\nBMI 31.0 kg/m2" vs. "patient denies chest pain.\tbmi 31.0 kg/m2" -> Canonical strings are identical -> Tier-1 SHA-256 HIT (~15 ms). Pair 2: "Patient denies chest pain. BMI 31.0 kg/m2" vs. "Pt denies chest pain; BMI 31 kg/m2" -> Tier 1 misses ("patient" vs "pt", "31.0" vs "31"). -> Tier 2 cosine = 0.982 (>= 0.97), and BOTH produce guard signature: (("31 kg/m2",), ("chest",), ()) -> Tier-2 Semantic HIT (~50 ms)! Pair 3: "No fever, cough" vs. "Fever, no cough" -> Embedding cosine might be 0.98+, BUT guard negated_targets are ("fever",) vs. ("cough",) -> Guard MISMATCH -> Forced compute (safe!).Finally, remember that threshold similarity is not transitive: input
Acan be 0.975 close toB, andB0.975 close toC, whileAandCare only 0.91 apart. If new inputs matched against any previous alias, clusters would slowly drift across meanings. We prevent drift by indexing only the original canonical representative of each cluster—never subsequent semantic aliases.- Exact cosine similarity
Deep dive 2: Collapsing concurrent requests without stampedes
When a hospital batch job submits 50 identical or slightly paraphrased notes at once, we prevent GPU stampedes using three concentric defenses:
Layer 1 — In-process Singleflight for identical text: The API gateway hashes
exact_key(~1 ms) and uses consistent hashing (mapping keys onto a hash ring so the same key consistently routes to the same server) to send identical normalized texts to the same resolver node. Inside each resolver, a singleflight map (exact_key -> in_flight_future, a pattern where the first caller runs the work and concurrent callers with the same key simply await its result) collapses 50 identical requests into 1 downstream lookup.Layer 2 — Single-threaded Namespace Coordinator for concurrent paraphrases: Paraphrased notes (
"Pt denies chest pain"vs"Patient denies chest pain") have differentexact_keyhashes and land on different resolvers. On a cache miss, resolvers call the Namespace Coordinator owning(tenant, task, pipeline_version). Because one coordinator thread serializes registrations for a namespace shard, checking in-flight jobs and registering a new one is atomic without distributed locks.Crucially, the coordinator keeps vectors for both
PENDINGjobs AND jobs committed in the last 2 seconds (covering the< 1 slag before a newly committed vector becomes searchable in the HNSW index). Even if a single namespace took the entire platform's peak miss rate,3,200 pending + (1,600/s * 2 s) = 6,400384-dim vectors is ~10 MB—an exact matrix-vector dot product takes< 0.5 mson one CPU core:import numpy as np class NamespaceCoordinator: """Serializes cache-miss registration per namespace shard on a single thread.""" def __init__(self, accept_threshold: float): self.accept_threshold = accept_threshold # exact_key -> canonical_id for pending and recently-committed (< 2s) jobs self.active_by_key = {} # Parallel lists of active canonical jobs for fast exact cosine scan self.canonical_ids = [] self.unit_vectors = [] self.guard_signatures = [] def register_miss( self, exact_key: str, unit_vec: np.ndarray, guard: tuple, candidate_id: str ) -> tuple: """Returns (canonical_id, is_owner). Only the owner enqueues GPU work.""" # 1. Exact duplicate of an already in-flight or just-committed request if exact_key in self.active_by_key: return self.active_by_key[exact_key], False # 2. Semantic scan against all pending + last-2s committed canonical jobs best_id = None best_score = -1.0 if self.unit_vectors: # Dot product of unit-normalized vectors equals exact cosine similarity cosine_scores = np.stack(self.unit_vectors) @ unit_vec for idx, score in enumerate(cosine_scores): if score < self.accept_threshold: continue if self.guard_signatures[idx] != guard: continue # Strictly '>' keeps the older canonical job on ties if score > best_score: best_score = float(score) best_id = self.canonical_ids[idx] if best_id is not None: self.active_by_key[exact_key] = best_id return best_id, False # 3. Brand-new cluster: caller becomes the owner of candidate_id self.active_by_key[exact_key] = candidate_id self.canonical_ids.append(candidate_id) self.unit_vectors.append(unit_vec) self.guard_signatures.append(guard) return candidate_id, True(In production,
unit_vectorsuses a pre-allocated ring buffer matrix rather thannp.stackon each call, evicting committed entries once they are > 2 seconds old.)Layer 3 — Conditional commit with fencing tokens: No worker ever returns its private in-memory result directly. Instead, each job attempt carries a monotonically increasing fencing token (an integer version number checked by storage so a delayed, timed-out worker cannot overwrite a newer retry):
t = 0 ms R1 ("denies chest pain, BMI 31") misses cache. Coordinator creates c1 (PENDING, fencing_token=1); R1 is owner. t = 3 ms R2 ("Denies chest pain, BMI 31") has same exact_key -> joins R1's local Singleflight future on the same resolver node. t = 5 ms R3 ("Pt denies chest pain; BMI 31.0") has different exact_key -> Coordinator sees cosine 0.982 + matching guard against c1 -> returns (c1, False). t = 2,100ms Worker finishes c1: 1. Conditional KV write: UPDATE canonical_records[c1] SET output=..., status=DONE WHERE status=PENDING AND fencing_token=1. 2. Writes owner's exact_map[key_R1] = c1, inserts c1 into HNSW index, and publishes done(c1) on Pub/Sub. 3. R1 (and R2 via Singleflight) return c1's committed output. 4. R3 wakes via Pub/Sub (or its 200ms backup KV poll), writes its own sticky exact_map[key_R3] = c1 (IF NOT EXISTS), and returns the exact same output!Notice why each follower (
R3) writes its ownexact_mapentry after readingDONE: even ifR4joinsc1500 ms afterc1already committed (while HNSW indexing is still catching up),R4still records its stickyexact_mappointer cleanly without needing the already-finished owner to know about late joiners.Deep dive 3: Pipeline versioning, rollouts, and invalidation
We track two distinct version numbers because changes affect different parts of the stack:
pipeline_versioncovers anything that changes the extracted output: LLM checkpoint, prompt template, clinical rules, or post-processor.sim_versioncovers anything that changes which inputs group together: canonicalizer rules (canon_version), embedding model, similarity threshold, or guard rules.
What changed Safe rollout & cache action Model checkpoint or prompt Register new pipeline_version(rf-v13) with a fresh empty namespace. Warm up top historical inputs at low priority before switching tenants. Oldrf-v12records remain immutable for billing audits.Post-processing code only New pipeline_version, zero GPU cost: batch-replay deterministic post-processing over storedraw_model_output_reffromrf-v12to pre-populaterf-v13in minutes.Embedding model New sim_version. Existing outputs andexact_mapentries remain valid; background GPU workers re-embed active 30-day canonical texts (most-frequently-hit first viarequest_log) into the new HNSW namespace.Threshold loosened / tightened Loosening ( 0.97 -> 0.96) applies safely to new misses. Tightening (0.97 -> 0.98) scansexact_maprows withmatch_type='semantic'andscore < 0.98, deletes those sticky pointers so future requests recompute, and logs the withdrawal.Bad single output spotted Operator calls /revoke: setscanonical_records[c].status = REVOKED, deletes pointingexact_maprows and removescfrom HNSW. Next request cleanly recomputes.To guarantee consistency during rollouts, ramp by tenant rather than random per-request percentages, and let batch chart jobs pin
pipeline_versionat session start so a single patient's chart is never extracted half withv12and half withv13.Scaling, failure handling, and trade-off summary
Scaling and backpressure: - Stateless resolvers: 12 nodes across 3 zones easily serve 8,000 QPS peak; hot
canonical_idoutputs live in a tiny in-process LRU cache with zero invalidation headaches because outputs are immutable. - Durable KV store: Handles ~2,700 writes/s average (1,500newexact_mappointers +600canonical records written atPENDINGandDONE), ~7,200 writes/s peak. - GPU admission control: If the inference queue exceeds 30 seconds of work (e.g., during a traffic spike or HNSW outage), new cache misses immediately return202 Accepted(async) or429 Retry-After, keeping cache hits under 100 ms.Failure modes: - Worker crash or hang: Each worker holds a 10-second heartbeat lease. On expiry, the coordinator re-queues the job with
fencing_token + 1. After 3 crashes (a "poison pill" input), status becomesFAILEDwith a 10-minute negative cache TTL so a malformed note cannot crash GPUs in a loop; failures are never cached permanently as clinical outputs. - Coordinator failover: A hot standby rebuilds in-flight state by readingPENDINGand last-2-secondDONErows for its shard from the durable KV store. If a rare near-duplicate slips past during the 2-second takeover, a commit-time re-check against the index converts the duplicate into an alias pointing to the earlier canonical ID. - Vector index timeout (> 15 ms): Resolvers fail open to a semantic miss; misses rise from 20% to 50% (2.5x GPU load), cushioned by async202admission control while on-call is paged. - Cross-region durability: Synchronous quorum writes across 3 availability zones (plus cross-region replication on the 2-second miss path before returning200 OK) ensure no answered clinical query ever vanishes or changes answer after a node or zone outage.Core trade-offs recap: - Conservative threshold + rule guard vs. maximum cache hits: Spends slightly more GPU compute to protect clinical accuracy against negation and number errors. - Write-once stored outputs vs. temperature-0 recomputation: Trades ~104 GB/day of cheap disk storage for strict bit-for-bit output consistency and full auditability. - Frozen canonical representatives vs. transitive clustering: Creates a few extra clusters near boundary edges to prevent semantic meaning drift. - Per-tenant, per-version namespaces vs. one global cache: Requires staged cache warm-ups on version upgrades and forbids cross-tenant sharing, in exchange for strict PHI isolation and instant, clean rollbacks.
Intuition & how it works
Think of this system like a hospital medical-coding reference desk with a master binder of approved rulings. When a clinical note arrives asking for billing codes, we want two notes that say the exact same thing in slightly different words ("Patient denies chest pain, BMI 31.0" vs. "Pt denies chest pain; BMI 31") to receive the exact same approved answer in milliseconds, without paying a specialist 2 seconds of GPU time to re-read it. First, the desk checks a fast exact barcode after cleaning up harmless formatting like uppercase letters and extra spaces (Tier 1). If no exact barcode matches, it looks up the note's meaning in an indexed catalog (Tier 2 vector search), verifies a strict clinical safety checklist (checking that numbers, units, left/right side, and negation words like "no" or "denies" match word-for-word), and pins a permanent shortcut sticker so future copies hit Tier 1 immediately. Meanwhile, if 20 identical or paraphrased copies of a brand-new note arrive at the same millisecond, a sign-up clipboard (request coalescing) groups all 20 callers behind a single GPU run so they share one authoritative answer.
Why does a naive semantic cache fail here? Hashing raw strings alone misses trivial variations like "31.0" vs. "31" or extra spaces. Conversely, trusting a raw cosine similarity score (a measure of how close two meaning vectors point, from -1 to 1) without a clinical checklist is dangerous: standard embedding models place "Patient denies chest pain" and "Patient reports chest pain" at 0.97+ similarity, returning an opposite medical diagnosis. Finally, relying on temperature-0 GPU inference for consistency fails because floating-point batching differences across GPUs can nudge token probabilities, and locking only on exact string hashes still lets 20 slightly differently worded notes trigger a GPU cache stampede.
Let's trace four clinical requests arriving under pipeline version rf-v12:
1. t = 0 ms: Note A = "Patient DENIES chest pain. BMI 31.0 kg/m2"
- Tier 1 normalizes text -> "patient denies chest pain. bmi 31.0 kg/m2" -> miss.
- Tier 2 embeds text -> searches HNSW vector index -> empty -> miss.
- Namespace Coordinator registers c1 (PENDING, fencing_token=1) and starts 1 GPU job.
2. t = 4 ms: Note B = "Pt denies chest pain; BMI 31 kg/m2" (arrives while c1 is still running!)
- Tier 1 & Tier 2 miss (c1 is not finished yet).
- Coordinator scans pending jobs: cosine(A, B) = 0.982 >= 0.97, and both have identical
guard facts: numbers=("31 kg/m2",), negations=("chest",), sides=().
- Note B attaches to c1! At t = 2,100 ms, c1 commits once; BOTH Note A and Note B return
c1's exact JSON output and save sticky exact_map pointers to c1.
3. t = 5 s: Note C = "patient denies chest pain.\nBMI 31.0 kg/m2"
- Normalizes to the exact same string as Note A -> Tier-1 Redis hit -> returns c1 in 12 ms!
4. t = 6 s: Note D = "Patient reports chest pain. BMI 31.0 kg/m2"
- Embedding cosine to c1 is 0.974, BUT guard negations are () vs. ("chest",).
- Guard blocks the false merge -> runs fresh GPU job c2 so clinical accuracy is preserved!
Key trade-offs
- Clinical safety vs. cache hit rate: Lowering the similarity threshold saves GPU compute, while raising it prevents false merges (serving one clinical extraction for a note that means something different). Because a wrong billing code or risk factor is far costlier than 2 seconds of GPU time, we pair a high cosine threshold with a deterministic guard signature (extracted numbers, units, negations, and left/right laterality) and fall back to computing whenever uncertain.
- Two-tier lookup (exact hash then vector search) vs. embedding every request: Deterministic canonicalization (normalizing Unicode, casing, and whitespace before SHA-256 hashing) takes ~1 ms of CPU and sheds ~50% of traffic with zero false-merge risk. Embedding search catches paraphrases (~30% of traffic) at the cost of ~20 ms of GPU encoder time plus an Approximate Nearest Neighbor (ANN) lookup (a fast graph-based vector search using HNSW, Hierarchical Navigable Small World indexes).
- Frozen canonical representatives vs. transitive cluster growth: Vector similarity is not transitive (
Acan matchBandBmatchCwhileAandCdiverge). Indexing only the original canonical text of each cluster prevents gradual meaning drift, at the small cost of computing a few extra canonical records near cluster boundaries. - Write-once stored outputs vs. deterministic recomputation: Rather than assuming GPU inference is bit-for-bit deterministic, we treat
canonical_recordsas immutable write-once records and store stickyexact_mappointers. This costs ~104 GB/day of cheap durable storage in exchange for guaranteed repeatability and auditability. - Single-threaded namespace coordinator vs. distributed key locks: A distributed Redis lock (
SET key NX) can only deduplicate byte-for-byte identical hashes, missing concurrent paraphrases. Routing misses to a single-threaded shard coordinator allows an atomic< 1 msexact cosine scan over the few thousand in-flight and just-committed vectors, trading a simple standby failover mechanism (backed up by a commit-time re-check) for complete paraphrase deduplication. - Per-tenant, version-isolated namespaces vs. a global shared cache: Sharing cached outputs across hospitals would boost hit rates, but Protected Health Information (PHI) (identifiable patient medical data) must never leak across organizations. Similarly, embedding
pipeline_versioninto every key starts new model versions cold (requiring staged warm-up), but prevents mixed-version answers and makes rollbacks instantaneous.
Common mistakes
- Relying on an embedding cosine threshold alone: Sentence encoders routinely score
"no fever"and"has fever"or"BMI 31"and"BMI 13"above0.96; omitting a deterministic guard on numbers, negations, and laterality causes severe clinical errors. - Over-aggressive Tier-1 normalization: Stripping stop words (which often include
"no","not","without"), punctuation that separates list scopes, or section headers ("Family history:"vs."Active problems:") causes Tier 1 to silently merge opposite meanings. - Omitting
pipeline_versionfrom cache keys and vector namespaces: Serving oldv11cached outputs alongside newv12model outputs during a deployment breaks version consistency and corrupts audit logs. - Indexing every incoming request vector instead of only canonical representatives: Inserting all 259M requests/day instead of the 52M canonical misses inflates expensive HNSW RAM by 5x and enables transitive cluster drift.
- Deduplicating concurrency only by exact hash: Concurrent paraphrases produce distinct SHA-256 hashes, bypassing exact locks and triggering redundant GPU runs unless a coordinator checks in-flight embeddings.
- Returning a worker's private result before durable commit: If two racing attempts happen during a network hiccup and workers return uncommitted results, two callers can receive conflicting outputs; always commit conditionally with a fencing token (a monotonically increasing attempt counter that rejects stale workers) and serve the committed record.
- Relying solely on Pub/Sub to wake waiting requests: A dropped notification leaves HTTP callers hanging until timeout unless paired with periodic KV polling (e.g., every 200 ms) and a bounded
wait_msfallback to202 Accepted. - Mutating
canonical_recordson every cache hit to incrementhit_count: Turning every 15 ms read hit into a durable database write creates hot-key contention; log hits asynchronously in an append-onlyrequest_loginstead.
Follow-up questions
- How should you calibrate and safely adjust the semantic similarity cutoff so false merges stay rare without sacrificing hit rate? Measure the real false-merge rate continuously via shadow recomputation: sample 1% of live Tier-2 semantic hits (at 3,000 QPS and 30% semantic hits,
1% * 900/s = 9background GPU jobs/s, just 1.5% extra compute), run the full model pipeline asynchronously, and compare the fresh output field-by-field against the cached canonical output across 0.01-wide similarity score bins (while also logging natural misses in a "gray band" like0.94–0.97to see what a looser threshold would have done). Have clinical coders adjudicate a sample of disagreements and re-run exact duplicates to measure baseline model noise. Walk downward from the0.99–1.00bin and setaccept_thresholdat the lowest bin whose upper 95% confidence bound on false merges stays below the clinical error budget (stricter for billing codes than exploratory risk hints); deploy updates as a newsim_version, allowing automatic adjustments only in the conservative direction (tightening when an alarm triggers).
text
Cosine bin Live hits/day 1% shadow-checked Output mismatches Upper 95% error bound
0.99-1.00 28M 280,000 42 0.02% (PASS)
0.98-0.99 25M 250,000 190 0.09% (PASS)
0.97-0.98 18M 180,000 310 0.19% (PASS <= 0.20% target)
0.96-0.97 14M 140,000 890 0.68% (STOP -> set 0.97)
-
When a breaking model upgrade ships, how can you warm the new version's cache and cut traffic over with zero downtime? Register the new
pipeline_version(v13) inSHADOWstatus with its own isolated, empty cache namespace while 100% of live tenant traffic stays safely onv12. Queryrequest_logto rank the last 30 days of canonical inputs by hit frequency (since medical templates follow a steep power law where the top 15% of snippets drive most hits), and feed them throughv13via a low-priority background queue that automatically pauses whenever live GPU queue depth rises—reusing already-storedexact_embeddingvectors ifsim_versiondid not change. Once a tenant's top historical canonicals are warm inv13and shadow quality checks pass, flip tenants ontov13in staged cohorts (1% -> 10% -> 50% -> 100%) while monitoring GPU queue headroom; becausev12remains untouched and read-only, rolling back any cohort is an instant configuration switch. -
What happens when two near-identical requests arrive concurrently, yet each sits slightly closer to a different existing neighbor in the vector index? Two cases arise: first, if neither neighbor exists yet (
XandYare brand-new notes arriving concurrently), both miss Tier 2 and enter the single-threadedNamespaceCoordinatorone after the other, so the second immediately matches the first'sPENDINGvector and collapses into a single canonical job. Second, if the index already holds frozen canonicalsC1andC2, and incoming noteAscores highest onC1(0.976) while slightly reworded noteBscores highest onC2(0.977), each maps to a representative withinaccept_threshold(preventing transitive cluster drift), and we eliminate boundary flip-flopping with three rules: (1) a tie-breaker band where top candidates within0.002cosine always pick the oldercanonical_id, (2) an ambiguity guard where if an input clearsaccept_thresholdagainst two canonicals whose stored JSON outputs disagree, we treat it as an ambiguous miss and run fresh inference, and (3) an offline consolidation job that aliases close canonical pairs whose outputs are identical while flagging conflicting pairs for clinical review.
Follow-up questions
- How should you calibrate and safely adjust the semantic similarity cutoff so false merges stay rare without sacrificing hit rate?
- When a breaking model upgrade ships, how can you warm the new version's cache and cut traffic over with zero downtime?
- What happens when two near-identical requests arrive concurrently, yet each sits slightly closer to a different existing neighbor in the vector index?
Similar questions
- Ranked Prefix Autocomplete With Request Ordering
- Past System Deep Dive and Fit for Charta Health
- Thread-Safe Lazy Token Bucket Rate Limiter
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform