{"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: Real-Time Fraud Scoring Service (transaction risk classification) targeting ~35,000 QPS and p99 < 45 ms.","completion":"# End-to-End AI System Design: Real-Time Fraud Scoring Service\n\n## 1. Problem Statement & Goals\nDesign **Real-Time Fraud Scoring Service**, an end-to-end system for transaction risk classification. The system must serve ~35,000 QPS at a p99 latency budget of 45 ms while operating over 8B historical transactions. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for transaction risk classification via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using GBDT ensemble + 200M tabular transformer and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 11 ms, p99 < 45 ms.\n- Throughput: sustain 35,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~875 RPS at the latency budget, steady-state needs ~40 nodes; provision 80 for 2x burst + rolling deploys. Daily request volume \u2248 3,024,000,000. At ~2 KB\/request logged, that is ~5.63 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates GBDT ensemble + 200M tabular transformer components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for Real-Time Fraud Scoring Service: feature store (Redis online \/ Delta offline). Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses GBDT ensemble + 200M tabular transformer behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Real-Time Fraud Scoring Service', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":1,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: Enterprise RAG Assistant (knowledge retrieval over private corpora) targeting ~1,200 QPS and p99 < 1800 ms.","completion":"# End-to-End AI System Design: Enterprise RAG Assistant\n\n## 1. Problem Statement & Goals\nDesign **Enterprise RAG Assistant**, an end-to-end system for knowledge retrieval over private corpora. The system must serve ~1,200 QPS at a p99 latency budget of 1800 ms while operating over 12M documents \/ 480M chunks. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for knowledge retrieval over private corpora via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using 1.5B dense LLM + bi-encoder retriever and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 450 ms, p99 < 1800 ms.\n- Throughput: sustain 1,200 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~50 RPS at the latency budget, steady-state needs ~24 nodes; provision 48 for 2x burst + rolling deploys. Daily request volume \u2248 103,680,000. At ~2 KB\/request logged, that is ~0.19 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates 1.5B dense LLM + bi-encoder retriever components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for Enterprise RAG Assistant: vector DB (HNSW) + object store + Postgres metadata. Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 1.5B dense LLM + bi-encoder retriever behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Enterprise RAG Assistant', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":2,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: Voice Assistant Orchestrator (speech-to-action pipeline) targeting ~4,800 QPS and p99 < 700 ms.","completion":"# End-to-End AI System Design: Voice Assistant Orchestrator\n\n## 1. Problem Statement & Goals\nDesign **Voice Assistant Orchestrator**, an end-to-end system for speech-to-action pipeline. The system must serve ~4,800 QPS at a p99 latency budget of 700 ms while operating over streaming audio frames. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for speech-to-action pipeline via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using ASR + 1.5B intent LLM + TTS and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 175 ms, p99 < 700 ms.\n- Throughput: sustain 4,800 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~120 RPS at the latency budget, steady-state needs ~40 nodes; provision 80 for 2x burst + rolling deploys. Daily request volume \u2248 414,720,000. At ~2 KB\/request logged, that is ~0.77 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates ASR + 1.5B intent LLM + TTS components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for Voice Assistant Orchestrator: session KV store + transcript warehouse. Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses ASR + 1.5B intent LLM + TTS behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Voice Assistant Orchestrator', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":3,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: LLM API Gateway (multi-tenant inference routing) targeting ~22,500 QPS and p99 < 2500 ms.","completion":"# End-to-End AI System Design: LLM API Gateway\n\n## 1. Problem Statement & Goals\nDesign **LLM API Gateway**, an end-to-end system for multi-tenant inference routing. The system must serve ~22,500 QPS at a p99 latency budget of 2500 ms while operating over tenant prompt\/response logs. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for multi-tenant inference routing via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using routed pool of 1.5B-70B models and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 625 ms, p99 < 2500 ms.\n- Throughput: sustain 22,500 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~562 RPS at the latency budget, steady-state needs ~41 nodes; provision 82 for 2x burst + rolling deploys. Daily request volume \u2248 1,944,000,000. At ~2 KB\/request logged, that is ~3.62 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates routed pool of 1.5B-70B models components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for LLM API Gateway: rate-limit Redis + audit log warehouse. Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses routed pool of 1.5B-70B models behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='LLM API Gateway', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":4,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: Semantic Product Search (e-commerce retrieval & ranking) targeting ~22,000 QPS and p99 < 120 ms.","completion":"# End-to-End AI System Design: Semantic Product Search\n\n## 1. Problem Statement & Goals\nDesign **Semantic Product Search**, an end-to-end system for e-commerce retrieval & ranking. The system must serve ~22,000 QPS at a p99 latency budget of 120 ms while operating over 90M product SKUs. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for e-commerce retrieval & ranking via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using two-tower retriever + cross-encoder reranker and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 30 ms, p99 < 120 ms.\n- Throughput: sustain 22,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~550 RPS at the latency budget, steady-state needs ~40 nodes; provision 80 for 2x burst + rolling deploys. Daily request volume \u2248 1,900,800,000. At ~2 KB\/request logged, that is ~3.54 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates two-tower retriever + cross-encoder reranker components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for Semantic Product Search: ANN index + inverted index + cache. Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses two-tower retriever + cross-encoder reranker behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Semantic Product Search', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":5,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: Voice Assistant Orchestrator (speech-to-action pipeline) targeting ~7,500 QPS and p99 < 700 ms.","completion":"# End-to-End AI System Design: Voice Assistant Orchestrator\n\n## 1. Problem Statement & Goals\nDesign **Voice Assistant Orchestrator**, an end-to-end system for speech-to-action pipeline. The system must serve ~7,500 QPS at a p99 latency budget of 700 ms while operating over streaming audio frames. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for speech-to-action pipeline via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using ASR + 1.5B intent LLM + TTS and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 175 ms, p99 < 700 ms.\n- Throughput: sustain 7,500 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~187 RPS at the latency budget, steady-state needs ~41 nodes; provision 82 for 2x burst + rolling deploys. Daily request volume \u2248 648,000,000. At ~2 KB\/request logged, that is ~1.21 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates ASR + 1.5B intent LLM + TTS components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for Voice Assistant Orchestrator: session KV store + transcript warehouse. Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses ASR + 1.5B intent LLM + TTS behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Voice Assistant Orchestrator', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":6,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: Real-Time Fraud Scoring Service (transaction risk classification) targeting ~52,500 QPS and p99 < 45 ms.","completion":"# End-to-End AI System Design: Real-Time Fraud Scoring Service\n\n## 1. Problem Statement & Goals\nDesign **Real-Time Fraud Scoring Service**, an end-to-end system for transaction risk classification. The system must serve ~52,500 QPS at a p99 latency budget of 45 ms while operating over 8B historical transactions. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for transaction risk classification via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using GBDT ensemble + 200M tabular transformer and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 11 ms, p99 < 45 ms.\n- Throughput: sustain 52,500 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~1,312 RPS at the latency budget, steady-state needs ~41 nodes; provision 82 for 2x burst + rolling deploys. Daily request volume \u2248 4,536,000,000. At ~2 KB\/request logged, that is ~8.45 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates GBDT ensemble + 200M tabular transformer components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for Real-Time Fraud Scoring Service: feature store (Redis online \/ Delta offline). Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses GBDT ensemble + 200M tabular transformer behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Real-Time Fraud Scoring Service', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":7,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: Semantic Product Search (e-commerce retrieval & ranking) targeting ~33,000 QPS and p99 < 120 ms.","completion":"# End-to-End AI System Design: Semantic Product Search\n\n## 1. Problem Statement & Goals\nDesign **Semantic Product Search**, an end-to-end system for e-commerce retrieval & ranking. The system must serve ~33,000 QPS at a p99 latency budget of 120 ms while operating over 90M product SKUs. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for e-commerce retrieval & ranking via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using two-tower retriever + cross-encoder reranker and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 30 ms, p99 < 120 ms.\n- Throughput: sustain 33,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~825 RPS at the latency budget, steady-state needs ~40 nodes; provision 80 for 2x burst + rolling deploys. Daily request volume \u2248 2,851,200,000. At ~2 KB\/request logged, that is ~5.31 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates two-tower retriever + cross-encoder reranker components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for Semantic Product Search: ANN index + inverted index + cache. Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses two-tower retriever + cross-encoder reranker behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Semantic Product Search', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":8,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: LLM API Gateway (multi-tenant inference routing) targeting ~27,000 QPS and p99 < 2500 ms.","completion":"# End-to-End AI System Design: LLM API Gateway\n\n## 1. Problem Statement & Goals\nDesign **LLM API Gateway**, an end-to-end system for multi-tenant inference routing. The system must serve ~27,000 QPS at a p99 latency budget of 2500 ms while operating over tenant prompt\/response logs. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for multi-tenant inference routing via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using routed pool of 1.5B-70B models and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 625 ms, p99 < 2500 ms.\n- Throughput: sustain 27,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~675 RPS at the latency budget, steady-state needs ~40 nodes; provision 80 for 2x burst + rolling deploys. Daily request volume \u2248 2,332,800,000. At ~2 KB\/request logged, that is ~4.35 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates routed pool of 1.5B-70B models components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for LLM API Gateway: rate-limit Redis + audit log warehouse. Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses routed pool of 1.5B-70B models behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='LLM API Gateway', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":9,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: Enterprise RAG Assistant (knowledge retrieval over private corpora) targeting ~1,800 QPS and p99 < 1800 ms.","completion":"# End-to-End AI System Design: Enterprise RAG Assistant\n\n## 1. Problem Statement & Goals\nDesign **Enterprise RAG Assistant**, an end-to-end system for knowledge retrieval over private corpora. The system must serve ~1,800 QPS at a p99 latency budget of 1800 ms while operating over 12M documents \/ 480M chunks. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for knowledge retrieval over private corpora via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using 1.5B dense LLM + bi-encoder retriever and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 450 ms, p99 < 1800 ms.\n- Throughput: sustain 1,800 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~50 RPS at the latency budget, steady-state needs ~36 nodes; provision 72 for 2x burst + rolling deploys. Daily request volume \u2248 155,520,000. At ~2 KB\/request logged, that is ~0.29 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates 1.5B dense LLM + bi-encoder retriever components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for Enterprise RAG Assistant: vector DB (HNSW) + object store + Postgres metadata. Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 1.5B dense LLM + bi-encoder retriever behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Enterprise RAG Assistant', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":10,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: Voice Assistant Orchestrator (speech-to-action pipeline) targeting ~9,000 QPS and p99 < 700 ms.","completion":"# End-to-End AI System Design: Voice Assistant Orchestrator\n\n## 1. Problem Statement & Goals\nDesign **Voice Assistant Orchestrator**, an end-to-end system for speech-to-action pipeline. The system must serve ~9,000 QPS at a p99 latency budget of 700 ms while operating over streaming audio frames. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for speech-to-action pipeline via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using ASR + 1.5B intent LLM + TTS and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 175 ms, p99 < 700 ms.\n- Throughput: sustain 9,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~225 RPS at the latency budget, steady-state needs ~40 nodes; provision 80 for 2x burst + rolling deploys. Daily request volume \u2248 777,600,000. At ~2 KB\/request logged, that is ~1.45 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates ASR + 1.5B intent LLM + TTS components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for Voice Assistant Orchestrator: session KV store + transcript warehouse. Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses ASR + 1.5B intent LLM + TTS behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Voice Assistant Orchestrator', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":11,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: Real-Time Fraud Scoring Service (transaction risk classification) targeting ~43,750 QPS and p99 < 45 ms.","completion":"# End-to-End AI System Design: Real-Time Fraud Scoring Service\n\n## 1. Problem Statement & Goals\nDesign **Real-Time Fraud Scoring Service**, an end-to-end system for transaction risk classification. The system must serve ~43,750 QPS at a p99 latency budget of 45 ms while operating over 8B historical transactions. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for transaction risk classification via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using GBDT ensemble + 200M tabular transformer and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 11 ms, p99 < 45 ms.\n- Throughput: sustain 43,750 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~1,093 RPS at the latency budget, steady-state needs ~41 nodes; provision 82 for 2x burst + rolling deploys. Daily request volume \u2248 3,780,000,000. At ~2 KB\/request logged, that is ~7.04 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates GBDT ensemble + 200M tabular transformer components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for Real-Time Fraud Scoring Service: feature store (Redis online \/ Delta offline). Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses GBDT ensemble + 200M tabular transformer behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Real-Time Fraud Scoring Service', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":12,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: Semantic Product Search (e-commerce retrieval & ranking) targeting ~17,600 QPS and p99 < 120 ms.","completion":"# End-to-End AI System Design: Semantic Product Search\n\n## 1. Problem Statement & Goals\nDesign **Semantic Product Search**, an end-to-end system for e-commerce retrieval & ranking. The system must serve ~17,600 QPS at a p99 latency budget of 120 ms while operating over 90M product SKUs. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for e-commerce retrieval & ranking via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using two-tower retriever + cross-encoder reranker and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 30 ms, p99 < 120 ms.\n- Throughput: sustain 17,600 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~440 RPS at the latency budget, steady-state needs ~40 nodes; provision 80 for 2x burst + rolling deploys. Daily request volume \u2248 1,520,640,000. At ~2 KB\/request logged, that is ~2.83 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates two-tower retriever + cross-encoder reranker components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for Semantic Product Search: ANN index + inverted index + cache. Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses two-tower retriever + cross-encoder reranker behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Semantic Product Search', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":13,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: Real-Time Fraud Scoring Service (transaction risk classification) targeting ~28,000 QPS and p99 < 45 ms.","completion":"# End-to-End AI System Design: Real-Time Fraud Scoring Service\n\n## 1. Problem Statement & Goals\nDesign **Real-Time Fraud Scoring Service**, an end-to-end system for transaction risk classification. The system must serve ~28,000 QPS at a p99 latency budget of 45 ms while operating over 8B historical transactions. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for transaction risk classification via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using GBDT ensemble + 200M tabular transformer and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 11 ms, p99 < 45 ms.\n- Throughput: sustain 28,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~700 RPS at the latency budget, steady-state needs ~40 nodes; provision 80 for 2x burst + rolling deploys. Daily request volume \u2248 2,419,200,000. At ~2 KB\/request logged, that is ~4.51 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates GBDT ensemble + 200M tabular transformer components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for Real-Time Fraud Scoring Service: feature store (Redis online \/ Delta offline). Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses GBDT ensemble + 200M tabular transformer behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Real-Time Fraud Scoring Service', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":14,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: LLM API Gateway (multi-tenant inference routing) targeting ~14,400 QPS and p99 < 2500 ms.","completion":"# End-to-End AI System Design: LLM API Gateway\n\n## 1. Problem Statement & Goals\nDesign **LLM API Gateway**, an end-to-end system for multi-tenant inference routing. The system must serve ~14,400 QPS at a p99 latency budget of 2500 ms while operating over tenant prompt\/response logs. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for multi-tenant inference routing via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using routed pool of 1.5B-70B models and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 625 ms, p99 < 2500 ms.\n- Throughput: sustain 14,400 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~360 RPS at the latency budget, steady-state needs ~40 nodes; provision 80 for 2x burst + rolling deploys. Daily request volume \u2248 1,244,160,000. At ~2 KB\/request logged, that is ~2.32 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates routed pool of 1.5B-70B models components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for LLM API Gateway: rate-limit Redis + audit log warehouse. Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses routed pool of 1.5B-70B models behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='LLM API Gateway', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":15,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: Enterprise RAG Assistant (knowledge retrieval over private corpora) targeting ~960 QPS and p99 < 1800 ms.","completion":"# End-to-End AI System Design: Enterprise RAG Assistant\n\n## 1. Problem Statement & Goals\nDesign **Enterprise RAG Assistant**, an end-to-end system for knowledge retrieval over private corpora. The system must serve ~960 QPS at a p99 latency budget of 1800 ms while operating over 12M documents \/ 480M chunks. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for knowledge retrieval over private corpora via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using 1.5B dense LLM + bi-encoder retriever and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 450 ms, p99 < 1800 ms.\n- Throughput: sustain 960 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~50 RPS at the latency budget, steady-state needs ~20 nodes; provision 40 for 2x burst + rolling deploys. Daily request volume \u2248 82,944,000. At ~2 KB\/request logged, that is ~0.15 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates 1.5B dense LLM + bi-encoder retriever components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for Enterprise RAG Assistant: vector DB (HNSW) + object store + Postgres metadata. Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 1.5B dense LLM + bi-encoder retriever behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Enterprise RAG Assistant', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":16,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: LLM API Gateway (multi-tenant inference routing) targeting ~18,000 QPS and p99 < 2500 ms.","completion":"# End-to-End AI System Design: LLM API Gateway\n\n## 1. Problem Statement & Goals\nDesign **LLM API Gateway**, an end-to-end system for multi-tenant inference routing. The system must serve ~18,000 QPS at a p99 latency budget of 2500 ms while operating over tenant prompt\/response logs. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for multi-tenant inference routing via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using routed pool of 1.5B-70B models and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 625 ms, p99 < 2500 ms.\n- Throughput: sustain 18,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~450 RPS at the latency budget, steady-state needs ~40 nodes; provision 80 for 2x burst + rolling deploys. Daily request volume \u2248 1,555,200,000. At ~2 KB\/request logged, that is ~2.90 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates routed pool of 1.5B-70B models components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for LLM API Gateway: rate-limit Redis + audit log warehouse. Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses routed pool of 1.5B-70B models behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='LLM API Gateway', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":17,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: Semantic Product Search (e-commerce retrieval & ranking) targeting ~27,500 QPS and p99 < 120 ms.","completion":"# End-to-End AI System Design: Semantic Product Search\n\n## 1. Problem Statement & Goals\nDesign **Semantic Product Search**, an end-to-end system for e-commerce retrieval & ranking. The system must serve ~27,500 QPS at a p99 latency budget of 120 ms while operating over 90M product SKUs. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for e-commerce retrieval & ranking via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using two-tower retriever + cross-encoder reranker and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 30 ms, p99 < 120 ms.\n- Throughput: sustain 27,500 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~687 RPS at the latency budget, steady-state needs ~41 nodes; provision 82 for 2x burst + rolling deploys. Daily request volume \u2248 2,376,000,000. At ~2 KB\/request logged, that is ~4.43 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates two-tower retriever + cross-encoder reranker components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for Semantic Product Search: ANN index + inverted index + cache. Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses two-tower retriever + cross-encoder reranker behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Semantic Product Search', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":18,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: Enterprise RAG Assistant (knowledge retrieval over private corpora) targeting ~1,500 QPS and p99 < 1800 ms.","completion":"# End-to-End AI System Design: Enterprise RAG Assistant\n\n## 1. Problem Statement & Goals\nDesign **Enterprise RAG Assistant**, an end-to-end system for knowledge retrieval over private corpora. The system must serve ~1,500 QPS at a p99 latency budget of 1800 ms while operating over 12M documents \/ 480M chunks. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for knowledge retrieval over private corpora via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using 1.5B dense LLM + bi-encoder retriever and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 450 ms, p99 < 1800 ms.\n- Throughput: sustain 1,500 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~50 RPS at the latency budget, steady-state needs ~30 nodes; provision 60 for 2x burst + rolling deploys. Daily request volume \u2248 129,600,000. At ~2 KB\/request logged, that is ~0.24 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates 1.5B dense LLM + bi-encoder retriever components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for Enterprise RAG Assistant: vector DB (HNSW) + object store + Postgres metadata. Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 1.5B dense LLM + bi-encoder retriever behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Enterprise RAG Assistant', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":19,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, including capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs.","context":"None","question":"Design an end-to-end AI system: Voice Assistant Orchestrator (speech-to-action pipeline) targeting ~6,000 QPS and p99 < 700 ms.","completion":"# End-to-End AI System Design: Voice Assistant Orchestrator\n\n## 1. Problem Statement & Goals\nDesign **Voice Assistant Orchestrator**, an end-to-end system for speech-to-action pipeline. The system must serve ~6,000 QPS at a p99 latency budget of 700 ms while operating over streaming audio frames. Primary goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior under production load.\n\n## 2. Functional Requirements\n- Accept user\/system requests for speech-to-action pipeline via a versioned API.\n- Validate, normalize, and authenticate every inbound request.\n- Run inference using ASR + 1.5B intent LLM + TTS and return a structured response.\n- Persist requests\/responses for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 175 ms, p99 < 700 ms.\n- Throughput: sustain 6,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts (object store).\n- Consistency: read-your-writes for session state; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAssuming each serving node handles ~150 RPS at the latency budget, steady-state needs ~40 nodes; provision 80 for 2x burst + rolling deploys. Daily request volume \u2248 518,400,000. At ~2 KB\/request logged, that is ~0.97 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> API Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-------------------------------------+--------------------+\n | | | |\n Feature\/Embed Retrieval (ANN) Model Serving Cache (Redis)\n | | | |\n +---------> Ranking \/ Post-process <---+--------------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator coordinates ASR + 1.5B intent LLM + TTS components, applies the cache, and emits structured telemetry on every hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers for Voice Assistant Orchestrator: session KV store + transcript warehouse. Raw inputs land in an object store partitioned by date; a CDC\/stream stage (Kafka) feeds both the online path and an offline Delta Lake table. Schema is governed with a registry; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndef ingest_stream(topic: str, sink_path: str, batch_size: int = 1000):\n consumer = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n consumer.subscribe([topic])\n buf = []\n while True:\n msg = consumer.poll(1.0)\n if msg is None or msg.error():\n continue\n rec = tokenize_pii(json.loads(msg.value())) # PII scrub at ingest\n buf.append(rec)\n if len(buf) >= batch_size:\n table = pa.Table.from_pylist(buf)\n pq.write_to_dataset(table, root_path=sink_path, partition_cols=['dt'])\n consumer.commit(asynchronous=False)\n buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nEmbeddings\/features are computed by a dedicated worker pool. Online features come from Redis (sub-ms reads); offline features are materialized nightly into the feature store with point-in-time correctness to avoid label leakage. Embedding model version is pinned per index to keep query\/doc spaces aligned.\n\n```python\nimport numpy as np, redis, hashlib\n\nr = redis.Redis(host='feature-store', decode_responses=False)\n\ndef embed(texts: list[str], model, version: str) -> np.ndarray:\n vecs = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return vecs.astype(np.float32)\n\ndef get_online_feature(entity_id: str, version: str):\n key = f'feat:{version}:{entity_id}'\n raw = r.get(key) # sub-ms online read\n if raw is None:\n return None # fall back to default\n return np.frombuffer(raw, dtype=np.float32)\n\ndef materialize_offline(entities, model, version, ttl=86400):\n pipe = r.pipeline()\n for eid, text in entities: # point-in-time correct join upstream\n vec = embed([text], model, version)[0]\n pipe.set(f'feat:{version}:{eid}', vec.tobytes(), ex=ttl)\n pipe.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses ASR + 1.5B intent LLM + TTS behind a model server with **continuous batching** and a **KV-cache** for autoregressive decode. Requests are admitted via a queue with deadline-aware scheduling; **speculative decoding** with a small draft model cuts decode latency. GPU memory is managed with paged attention; **KV-cache quantization** (int8) extends effective batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model = model\n self.max_batch = max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.queue: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.queue.put((req, fut))\n return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n timeout = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.queue.get(), timeout))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n reqs = [b[0] for b in batch]\n # paged-attention KV cache + int8 KV quant + speculative decode\n outs = self.model.generate(reqs, kv_cache='paged', kv_dtype='int8')\n for (_, fut), out in zip(batch, outs):\n fut.set_result(out)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: (1) ANN recall over an HNSW index returns top-k candidates; (2) a cross-encoder reranker scores the shortlist. Hybrid scoring blends dense similarity with lexical BM25 to handle rare terms. k is tuned against a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query: str, ann_index, bm25, reranker,\n k_recall: int = 200, k_final: int = 8, alpha: float = 0.7):\n qvec = embed_query(query)\n dense_ids, dense_scores = ann_index.search(qvec, k_recall) # HNSW recall\n lex_ids, lex_scores = bm25.search(query, k_recall) # lexical recall\n\n pool = {}\n for i, s in zip(dense_ids, _minmax(dense_scores)):\n pool[i] = alpha * s\n for i, s in zip(lex_ids, _minmax(lex_scores)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n\n shortlist = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n pairs = [(query, doc_text(i)) for i in shortlist]\n rerank = reranker.predict(pairs) # cross-encoder\n order = np.argsort(rerank)[::-1][:k_final]\n return [shortlist[j] for j in order]\n\ndef _minmax(x):\n x = np.asarray(x, dtype=np.float32)\n return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline: scheduled retraining on the Delta table with versioned datasets and a champion\/challenger eval gate. Online: feedback (clicks, corrections, thumbs) is logged and aggregated into the next training set. Models are promoted only after passing automated regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set,\n min_gain: float = 0.01) -> bool:\n c_metrics = evaluate(challenger, eval_set) # accuracy, recall@k, safety\n p_metrics = evaluate(champion, eval_set)\n\n if c_metrics['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n gain = c_metrics['primary'] - p_metrics['primary']\n if gain < min_gain:\n return False # not enough lift\n\n registry.set_alias('production', challenger.version) # versioned alias\n log_promotion(champion.version, challenger.version, gain)\n return True\n\ndef aggregate_feedback(events):\n # clicks \/ corrections \/ thumbs -> next training set\n return [to_training_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: (1) exact-match response cache keyed by a normalized request hash; (2) semantic cache keyed by embedding proximity for near-duplicate queries; (3) prompt-prefix \/ KV reuse for shared system context. TTLs are short for volatile data; cache hits are the largest single cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, redis_client, sem_index, sim_threshold=0.97):\n self.r = redis_client\n self.sem = sem_index\n self.tau = sim_threshold\n\n def _norm_key(self, req: dict) -> str:\n payload = json.dumps(req, sort_keys=True).encode()\n return 'resp:' + hashlib.md5(payload).hexdigest() # exact match\n\n def get(self, req: dict, qvec: np.ndarray):\n hit = self.r.get(self._norm_key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qvec, 1) # semantic match\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req: dict, qvec: np.ndarray, resp: dict, ttl=300):\n self.r.set(self._norm_key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qvec, resp)\n```\n\n## 12. API Design & Contracts\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Voice Assistant Orchestrator', version='1.0.0')\n\nclass Request(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Response(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Response)\nasync def infer(req: Request) -> Response:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n result = await orchestrator.run(req) # cache -> retrieve -> serve\n return result\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics (Rate, Errors, Duration) per stage + GPU utilization.\n- Distributed tracing (one trace per request across all hops).\n- Quality evals: groundedness, recall@k, and task-specific accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alerting on error-budget burn rate, not just raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'per-stage latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage: str):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc()\n raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef error_budget_burn(errors, total, slo=0.0005):\n observed = errors \/ max(total, 1)\n return observed \/ slo # >1.0 means burning budget too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection and PII detection pre-inference.\n- Output guardrails: toxicity, leakage, and policy classifiers.\n- Per-tenant data isolation; encryption in transit and at rest.\n- Full audit trail with immutable logs for regulatory review.\n- Human-in-the-loop escalation path for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text: str) -> tuple[bool, str]:\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp: str, classifiers) -> tuple[bool, str]:\n for name, clf in classifiers.items(): # toxicity \/ leakage \/ policy\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name, payload_hash=md5(resp))\n return False, name\n return True, 'ok'\n\ndef route(resp, confidence: float, threshold: float = 0.6):\n return resp if confidence >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: route to a fallback smaller model or cached answer.\n- Vector DB unavailable: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission control.\n- Bad model promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self) -> bool:\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok: bool):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n out = primary(req); breaker.record(True); return out\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req) # degrade gracefully\n```\n\n## 16. Scaling & Multi-Region Strategy\nHorizontal scaling via stateless serving replicas behind a load balancer; autoscaling keyed on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices are replicated per region, and the feature store uses async cross-region replication. Sticky session affinity preserves KV-cache locality where it helps.\n\n```python\ndef desired_replicas(queue_depth: int, gpu_util: float,\n cur: int, target_depth=50, target_util=0.65,\n lo=4, hi=512) -> int:\n by_queue = cur * (queue_depth \/ target_depth)\n by_gpu = cur * (gpu_util \/ target_util)\n want = max(by_queue, by_gpu)\n return int(min(hi, max(lo, round(want)))) # autoscale signal\n\ndef route_region(client_geo: str, regions: dict, health: dict):\n candidates = [r for r in regions if health.get(r, False)]\n if not candidates:\n raise RuntimeError('no healthy region')\n return min(candidates, key=lambda r: regions[r].rtt_ms(client_geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green for the serving tier; canary 1% -> 10% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; immutable container images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(new_version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(new_version, pct) # shift traffic\n time.sleep(hold_s)\n ok, metrics = slo_check(new_version)\n if not ok:\n registry.set_weight(new_version, 0.0) # instant rollback\n alert('canary_failed', version=new_version, metrics=metrics)\n return False\n registry.set_alias('production', new_version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache aggressiveness vs. freshness: longer TTL cuts cost, risks staleness.\n- Larger model vs. cost: route easy requests to a small model.\n- Strong consistency vs. availability: chose AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but materially cuts p99.\n\n```python\ndef pick_model(difficulty: float, latency_budget_ms: float,\n small, large, threshold: float = 0.5):\n # route easy\/low-budget requests to the cheap model\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate: float,\n gpu_cost_per_hr: float, rps: float) -> float:\n served = rps * (1 - cache_hit_rate) # cache absorbs the rest\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":20,"source_file":"ai_sysdesign_e2e.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Code Review Copilot (automated PR analysis & suggestion) targeting ~3,125 QPS and p99 < 4000 ms.","completion":"# End-to-End AI System Design: Code Review Copilot\n\n## 1. Problem Statement & Goals\nDesign **Code Review Copilot**, an end-to-end system for automated PR analysis & suggestion. It must serve ~3,125 QPS within a p99 budget of 4000 ms over monorepo + 40M historical diffs. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for automated PR analysis & suggestion via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with code-tuned 1.5B LLM + AST retriever and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 1000 ms, p99 < 4000 ms.\n- Throughput: sustain 3,125 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~78 RPS\/node within budget, steady-state needs ~41 nodes; provision 82 for burst + rolling deploys. Daily volume \u2248 270,000,000 requests; at ~2 KB logged that is ~0.50 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires code-tuned 1.5B LLM + AST retriever together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: repo index + review feedback warehouse. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses code-tuned 1.5B LLM + AST retriever behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Code Review Copilot', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":21,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Image Moderation Service (content-safety classification at upload) targeting ~37,500 QPS and p99 < 150 ms.","completion":"# End-to-End AI System Design: Image Moderation Service\n\n## 1. Problem Statement & Goals\nDesign **Image Moderation Service**, an end-to-end system for content-safety classification at upload. It must serve ~37,500 QPS within a p99 budget of 150 ms over 1.2B labeled images. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for content-safety classification at upload via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with vision encoder + policy classifier head and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 37 ms, p99 < 150 ms.\n- Throughput: sustain 37,500 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~937 RPS\/node within budget, steady-state needs ~41 nodes; provision 82 for burst + rolling deploys. Daily volume \u2248 3,240,000,000 requests; at ~2 KB logged that is ~6.03 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires vision encoder + policy classifier head together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: object store + decision audit log. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses vision encoder + policy classifier head behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Image Moderation Service', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":22,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Anomaly Detection for Observability (metric\/log\/trace anomaly scoring) targeting ~120,000 QPS and p99 < 60 ms.","completion":"# End-to-End AI System Design: Anomaly Detection for Observability\n\n## 1. Problem Statement & Goals\nDesign **Anomaly Detection for Observability**, an end-to-end system for metric\/log\/trace anomaly scoring. It must serve ~120,000 QPS within a p99 budget of 60 ms over 10M time series + log streams. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for metric\/log\/trace anomaly scoring via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with streaming forecaster + 300M log encoder and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 15 ms, p99 < 60 ms.\n- Throughput: sustain 120,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~3,000 RPS\/node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 10,368,000,000 requests; at ~2 KB logged that is ~19.31 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires streaming forecaster + 300M log encoder together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: TSDB + embedding index. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses streaming forecaster + 300M log encoder behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Anomaly Detection for Observability', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":23,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Code Review Copilot (automated PR analysis & suggestion) targeting ~2,000 QPS and p99 < 4000 ms.","completion":"# End-to-End AI System Design: Code Review Copilot\n\n## 1. Problem Statement & Goals\nDesign **Code Review Copilot**, an end-to-end system for automated PR analysis & suggestion. It must serve ~2,000 QPS within a p99 budget of 4000 ms over monorepo + 40M historical diffs. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for automated PR analysis & suggestion via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with code-tuned 1.5B LLM + AST retriever and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 1000 ms, p99 < 4000 ms.\n- Throughput: sustain 2,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~50 RPS\/node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 172,800,000 requests; at ~2 KB logged that is ~0.32 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires code-tuned 1.5B LLM + AST retriever together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: repo index + review feedback warehouse. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses code-tuned 1.5B LLM + AST retriever behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Code Review Copilot', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":24,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Conversational Support Agent (tier-1 customer support automation) targeting ~11,250 QPS and p99 < 2200 ms.","completion":"# End-to-End AI System Design: Conversational Support Agent\n\n## 1. Problem Statement & Goals\nDesign **Conversational Support Agent**, an end-to-end system for tier-1 customer support automation. It must serve ~11,250 QPS within a p99 budget of 2200 ms over 5M tickets + knowledge base. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for tier-1 customer support automation via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 1.5B RAG LLM + intent classifier and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 550 ms, p99 < 2200 ms.\n- Throughput: sustain 11,250 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~281 RPS\/node within budget, steady-state needs ~41 nodes; provision 82 for burst + rolling deploys. Daily volume \u2248 972,000,000 requests; at ~2 KB logged that is ~1.81 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 1.5B RAG LLM + intent classifier together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: vector KB + CRM integration store. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 1.5B RAG LLM + intent classifier behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Conversational Support Agent', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":25,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Anomaly Detection for Observability (metric\/log\/trace anomaly scoring) targeting ~100,000 QPS and p99 < 60 ms.","completion":"# End-to-End AI System Design: Anomaly Detection for Observability\n\n## 1. Problem Statement & Goals\nDesign **Anomaly Detection for Observability**, an end-to-end system for metric\/log\/trace anomaly scoring. It must serve ~100,000 QPS within a p99 budget of 60 ms over 10M time series + log streams. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for metric\/log\/trace anomaly scoring via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with streaming forecaster + 300M log encoder and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 15 ms, p99 < 60 ms.\n- Throughput: sustain 100,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~2,500 RPS\/node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 8,640,000,000 requests; at ~2 KB logged that is ~16.09 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires streaming forecaster + 300M log encoder together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: TSDB + embedding index. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses streaming forecaster + 300M log encoder behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Anomaly Detection for Observability', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":26,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Multi-Agent Workflow Orchestrator (tool-using agent planning & execution) targeting ~5,000 QPS and p99 < 6000 ms.","completion":"# End-to-End AI System Design: Multi-Agent Workflow Orchestrator\n\n## 1. Problem Statement & Goals\nDesign **Multi-Agent Workflow Orchestrator**, an end-to-end system for tool-using agent planning & execution. It must serve ~5,000 QPS within a p99 budget of 6000 ms over agent traces + tool schemas. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for tool-using agent planning & execution via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 1.5B planner LLM + tool router and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 1500 ms, p99 < 6000 ms.\n- Throughput: sustain 5,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~125 RPS\/node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 432,000,000 requests; at ~2 KB logged that is ~0.80 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 1.5B planner LLM + tool router together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: task graph DB + episodic memory store. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 1.5B planner LLM + tool router behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Multi-Agent Workflow Orchestrator', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":27,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Image Moderation Service (content-safety classification at upload) targeting ~30,000 QPS and p99 < 150 ms.","completion":"# End-to-End AI System Design: Image Moderation Service\n\n## 1. Problem Statement & Goals\nDesign **Image Moderation Service**, an end-to-end system for content-safety classification at upload. It must serve ~30,000 QPS within a p99 budget of 150 ms over 1.2B labeled images. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for content-safety classification at upload via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with vision encoder + policy classifier head and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 37 ms, p99 < 150 ms.\n- Throughput: sustain 30,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~750 RPS\/node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 2,592,000,000 requests; at ~2 KB logged that is ~4.83 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires vision encoder + policy classifier head together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: object store + decision audit log. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses vision encoder + policy classifier head behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Image Moderation Service', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":28,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Image Moderation Service (content-safety classification at upload) targeting ~45,000 QPS and p99 < 150 ms.","completion":"# End-to-End AI System Design: Image Moderation Service\n\n## 1. Problem Statement & Goals\nDesign **Image Moderation Service**, an end-to-end system for content-safety classification at upload. It must serve ~45,000 QPS within a p99 budget of 150 ms over 1.2B labeled images. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for content-safety classification at upload via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with vision encoder + policy classifier head and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 37 ms, p99 < 150 ms.\n- Throughput: sustain 45,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~1,125 RPS\/node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 3,888,000,000 requests; at ~2 KB logged that is ~7.24 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires vision encoder + policy classifier head together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: object store + decision audit log. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses vision encoder + policy classifier head behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Image Moderation Service', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":29,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Image Moderation Service (content-safety classification at upload) targeting ~24,000 QPS and p99 < 150 ms.","completion":"# End-to-End AI System Design: Image Moderation Service\n\n## 1. Problem Statement & Goals\nDesign **Image Moderation Service**, an end-to-end system for content-safety classification at upload. It must serve ~24,000 QPS within a p99 budget of 150 ms over 1.2B labeled images. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for content-safety classification at upload via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with vision encoder + policy classifier head and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 37 ms, p99 < 150 ms.\n- Throughput: sustain 24,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~600 RPS\/node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 2,073,600,000 requests; at ~2 KB logged that is ~3.86 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires vision encoder + policy classifier head together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: object store + decision audit log. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses vision encoder + policy classifier head behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Image Moderation Service', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":30,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Code Review Copilot (automated PR analysis & suggestion) targeting ~3,750 QPS and p99 < 4000 ms.","completion":"# End-to-End AI System Design: Code Review Copilot\n\n## 1. Problem Statement & Goals\nDesign **Code Review Copilot**, an end-to-end system for automated PR analysis & suggestion. It must serve ~3,750 QPS within a p99 budget of 4000 ms over monorepo + 40M historical diffs. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for automated PR analysis & suggestion via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with code-tuned 1.5B LLM + AST retriever and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 1000 ms, p99 < 4000 ms.\n- Throughput: sustain 3,750 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~93 RPS\/node within budget, steady-state needs ~41 nodes; provision 82 for burst + rolling deploys. Daily volume \u2248 324,000,000 requests; at ~2 KB logged that is ~0.60 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires code-tuned 1.5B LLM + AST retriever together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: repo index + review feedback warehouse. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses code-tuned 1.5B LLM + AST retriever behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Code Review Copilot', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":31,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Anomaly Detection for Observability (metric\/log\/trace anomaly scoring) targeting ~64,000 QPS and p99 < 60 ms.","completion":"# End-to-End AI System Design: Anomaly Detection for Observability\n\n## 1. Problem Statement & Goals\nDesign **Anomaly Detection for Observability**, an end-to-end system for metric\/log\/trace anomaly scoring. It must serve ~64,000 QPS within a p99 budget of 60 ms over 10M time series + log streams. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for metric\/log\/trace anomaly scoring via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with streaming forecaster + 300M log encoder and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 15 ms, p99 < 60 ms.\n- Throughput: sustain 64,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~1,600 RPS\/node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 5,529,600,000 requests; at ~2 KB logged that is ~10.30 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires streaming forecaster + 300M log encoder together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: TSDB + embedding index. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses streaming forecaster + 300M log encoder behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Anomaly Detection for Observability', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":32,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Conversational Support Agent (tier-1 customer support automation) targeting ~7,200 QPS and p99 < 2200 ms.","completion":"# End-to-End AI System Design: Conversational Support Agent\n\n## 1. Problem Statement & Goals\nDesign **Conversational Support Agent**, an end-to-end system for tier-1 customer support automation. It must serve ~7,200 QPS within a p99 budget of 2200 ms over 5M tickets + knowledge base. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for tier-1 customer support automation via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 1.5B RAG LLM + intent classifier and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 550 ms, p99 < 2200 ms.\n- Throughput: sustain 7,200 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~180 RPS\/node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 622,080,000 requests; at ~2 KB logged that is ~1.16 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 1.5B RAG LLM + intent classifier together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: vector KB + CRM integration store. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 1.5B RAG LLM + intent classifier behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Conversational Support Agent', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":33,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Recommendation Ranking Platform (personalized feed ranking) targeting ~96,000 QPS and p99 < 80 ms.","completion":"# End-to-End AI System Design: Recommendation Ranking Platform\n\n## 1. Problem Statement & Goals\nDesign **Recommendation Ranking Platform**, an end-to-end system for personalized feed ranking. It must serve ~96,000 QPS within a p99 budget of 80 ms over 2B user-item interactions. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for personalized feed ranking via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with two-tower retriever + DLRM ranker and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 20 ms, p99 < 80 ms.\n- Throughput: sustain 96,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~2,400 RPS\/node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 8,294,400,000 requests; at ~2 KB logged that is ~15.45 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires two-tower retriever + DLRM ranker together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: feature store + ANN index + Redis. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses two-tower retriever + DLRM ranker behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Recommendation Ranking Platform', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":34,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Code Review Copilot (automated PR analysis & suggestion) targeting ~2,500 QPS and p99 < 4000 ms.","completion":"# End-to-End AI System Design: Code Review Copilot\n\n## 1. Problem Statement & Goals\nDesign **Code Review Copilot**, an end-to-end system for automated PR analysis & suggestion. It must serve ~2,500 QPS within a p99 budget of 4000 ms over monorepo + 40M historical diffs. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for automated PR analysis & suggestion via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with code-tuned 1.5B LLM + AST retriever and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 1000 ms, p99 < 4000 ms.\n- Throughput: sustain 2,500 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~62 RPS\/node within budget, steady-state needs ~41 nodes; provision 82 for burst + rolling deploys. Daily volume \u2248 216,000,000 requests; at ~2 KB logged that is ~0.40 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires code-tuned 1.5B LLM + AST retriever together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: repo index + review feedback warehouse. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses code-tuned 1.5B LLM + AST retriever behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Code Review Copilot', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":35,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Multi-Agent Workflow Orchestrator (tool-using agent planning & execution) targeting ~4,000 QPS and p99 < 6000 ms.","completion":"# End-to-End AI System Design: Multi-Agent Workflow Orchestrator\n\n## 1. Problem Statement & Goals\nDesign **Multi-Agent Workflow Orchestrator**, an end-to-end system for tool-using agent planning & execution. It must serve ~4,000 QPS within a p99 budget of 6000 ms over agent traces + tool schemas. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for tool-using agent planning & execution via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 1.5B planner LLM + tool router and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 1500 ms, p99 < 6000 ms.\n- Throughput: sustain 4,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~100 RPS\/node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 345,600,000 requests; at ~2 KB logged that is ~0.64 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 1.5B planner LLM + tool router together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: task graph DB + episodic memory store. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 1.5B planner LLM + tool router behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Multi-Agent Workflow Orchestrator', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":36,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Conversational Support Agent (tier-1 customer support automation) targeting ~9,000 QPS and p99 < 2200 ms.","completion":"# End-to-End AI System Design: Conversational Support Agent\n\n## 1. Problem Statement & Goals\nDesign **Conversational Support Agent**, an end-to-end system for tier-1 customer support automation. It must serve ~9,000 QPS within a p99 budget of 2200 ms over 5M tickets + knowledge base. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for tier-1 customer support automation via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 1.5B RAG LLM + intent classifier and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 550 ms, p99 < 2200 ms.\n- Throughput: sustain 9,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~225 RPS\/node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 777,600,000 requests; at ~2 KB logged that is ~1.45 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 1.5B RAG LLM + intent classifier together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: vector KB + CRM integration store. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 1.5B RAG LLM + intent classifier behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Conversational Support Agent', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":37,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Document Intelligence Pipeline (OCR + extraction over scanned docs) targeting ~3,200 QPS and p99 < 3500 ms.","completion":"# End-to-End AI System Design: Document Intelligence Pipeline\n\n## 1. Problem Statement & Goals\nDesign **Document Intelligence Pipeline**, an end-to-end system for OCR + extraction over scanned docs. It must serve ~3,200 QPS within a p99 budget of 3500 ms over 300M scanned pages. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for OCR + extraction over scanned docs via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with layout encoder + 1.5B extraction LLM and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 875 ms, p99 < 3500 ms.\n- Throughput: sustain 3,200 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~80 RPS\/node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 276,480,000 requests; at ~2 KB logged that is ~0.51 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires layout encoder + 1.5B extraction LLM together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: object store + structured doc DB. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses layout encoder + 1.5B extraction LLM behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Document Intelligence Pipeline', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":38,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Real-Time Translation Service (streaming speech & text translation) targeting ~14,000 QPS and p99 < 400 ms.","completion":"# End-to-End AI System Design: Real-Time Translation Service\n\n## 1. Problem Statement & Goals\nDesign **Real-Time Translation Service**, an end-to-end system for streaming speech & text translation. It must serve ~14,000 QPS within a p99 budget of 400 ms over parallel corpora across 40 languages. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for streaming speech & text translation via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 1.5B multilingual seq2seq and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 100 ms, p99 < 400 ms.\n- Throughput: sustain 14,000 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~350 RPS\/node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 1,209,600,000 requests; at ~2 KB logged that is ~2.25 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 1.5B multilingual seq2seq together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: glossary store + correction warehouse. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 1.5B multilingual seq2seq behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Real-Time Translation Service', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":39,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Multi-Agent Workflow Orchestrator (tool-using agent planning & execution) targeting ~3,200 QPS and p99 < 6000 ms.","completion":"# End-to-End AI System Design: Multi-Agent Workflow Orchestrator\n\n## 1. Problem Statement & Goals\nDesign **Multi-Agent Workflow Orchestrator**, an end-to-end system for tool-using agent planning & execution. It must serve ~3,200 QPS within a p99 budget of 6000 ms over agent traces + tool schemas. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept requests for tool-using agent planning & execution via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 1.5B planner LLM + tool router and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 1500 ms, p99 < 6000 ms.\n- Throughput: sustain 3,200 QPS with 2x burst headroom.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~80 RPS\/node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 276,480,000 requests; at ~2 KB logged that is ~0.51 TB\/day of raw logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 1.5B planner LLM + tool router together, applies caching, and emits a trace per hop.\n\n## 6. Data Ingestion & Storage\nStorage tiers: task graph DB + episodic memory store. Raw inputs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; PII is tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_pii(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(texts, model, version):\n v = model.encode(texts, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, text in entities:\n p.set(f'feat:{version}:{eid}', embed([text], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 1.5B planner LLM + tool router behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (clicks, corrections, thumbs) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Multi-Agent Workflow Orchestrator', version='1.0.0')\n\nclass Req(BaseModel):\n query: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n answer: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/infer', response_model=Resp)\nasync def infer(req: Req) -> Resp:\n if not req.query.strip():\n raise HTTPException(400, 'empty query')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: prompt-injection & PII detection pre-inference.\n- Output guardrails: toxicity, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop escalation for low-confidence outputs.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nPII = re.compile(r'\\b(\\d{3}-\\d{2}-\\d{4}|\\d{16})\\b')\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if PII.search(text):\n return False, 'pii_detected'\n return True, 'ok'\n\ndef output_guardrail(resp, classifiers):\n for name, clf in classifiers.items():\n if clf.score(resp) > clf.threshold:\n audit_log(event='blocked', reason=name)\n return False, name\n return True, 'ok'\n\ndef route(resp, conf, threshold=0.6):\n return resp if conf >= threshold else escalate_to_human(resp)\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":40,"source_file":"ai_sysdesign_e2e_v2.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: AI-Native Git Platform (version control with AI review & search) targeting ~18,000 git operations\/sec and p99 < 900 ms.","completion":"# End-to-End AI System Design: AI-Native Git Platform\n\n## 1. Problem Statement & Goals\nDesign **AI-Native Git Platform**, an end-to-end system for version control with AI review & search. It must serve ~18,000 git operations\/sec within a p99 budget of 900 ms over 80M repos \/ 4B commits. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each git operation via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with code-tuned 1.5B LLM + diff embedder and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 225 ms, p99 < 900 ms.\n- Throughput: sustain 18,000 git operations\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~450 git operations\/sec per node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 1,555,200,000; at ~2 KB logged that is ~2.90 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires code-tuned 1.5B LLM + diff embedder together, applies caching, and emits a trace per git operation.\n\n## 6. Data Ingestion & Storage\nStorage tiers: object store (packfiles) + ref DB + code index. Raw git operations land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses code-tuned 1.5B LLM + diff embedder behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='AI-Native Git Platform', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per git operation across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":41,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: PowerShell Copilot Service (natural-language to PowerShell automation) targeting ~4,375 command requests\/sec and p99 < 2500 ms.","completion":"# End-to-End AI System Design: PowerShell Copilot Service\n\n## 1. Problem Statement & Goals\nDesign **PowerShell Copilot Service**, an end-to-end system for natural-language to PowerShell automation. It must serve ~4,375 command requests\/sec within a p99 budget of 2500 ms over command docs + 20M script samples. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each command request via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 1.5B code LLM + cmdlet schema retriever and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 625 ms, p99 < 2500 ms.\n- Throughput: sustain 4,375 command requests\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~109 command requests\/sec per node within budget, steady-state needs ~41 nodes; provision 82 for burst + rolling deploys. Daily volume \u2248 378,000,000; at ~2 KB logged that is ~0.70 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 1.5B code LLM + cmdlet schema retriever together, applies caching, and emits a trace per command request.\n\n## 6. Data Ingestion & Storage\nStorage tiers: cmdlet catalog + execution audit log. Raw command requests land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 1.5B code LLM + cmdlet schema retriever behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='PowerShell Copilot Service', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per command request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":42,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: AI Secrets Management Service (secret storage with AI leak & anomaly detection) targeting ~40,000 secret accesss\/sec and p99 < 50 ms.","completion":"# End-to-End AI System Design: AI Secrets Management Service\n\n## 1. Problem Statement & Goals\nDesign **AI Secrets Management Service**, an end-to-end system for secret storage with AI leak & anomaly detection. It must serve ~40,000 secret accesss\/sec within a p99 budget of 50 ms over access logs + rotation history. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each secret access via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 300M access-pattern anomaly model and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 12 ms, p99 < 50 ms.\n- Throughput: sustain 40,000 secret accesss\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~1,000 secret accesss\/sec per node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 3,456,000,000; at ~2 KB logged that is ~6.44 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 300M access-pattern anomaly model together, applies caching, and emits a trace per secret access.\n\n## 6. Data Ingestion & Storage\nStorage tiers: encrypted KV (HSM-backed) + audit ledger. Raw secret accesss land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 300M access-pattern anomaly model behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='AI Secrets Management Service', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per secret access across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":43,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Serverless Function Platform (Lambda-style) (event-driven function execution with AI autoscale) targeting ~90,000 invocations\/sec and p99 < 100 ms.","completion":"# End-to-End AI System Design: Serverless Function Platform (Lambda-style)\n\n## 1. Problem Statement & Goals\nDesign **Serverless Function Platform (Lambda-style)**, an end-to-end system for event-driven function execution with AI autoscale. It must serve ~90,000 invocations\/sec within a p99 budget of 100 ms over function code + invocation traces. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each invocation via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 300M cold-start predictor + anomaly scorer and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 25 ms, p99 < 100 ms.\n- Throughput: sustain 90,000 invocations\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~2,250 invocations\/sec per node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 7,776,000,000; at ~2 KB logged that is ~14.48 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 300M cold-start predictor + anomaly scorer together, applies caching, and emits a trace per invocation.\n\n## 6. Data Ingestion & Storage\nStorage tiers: code store + warm-pool registry + metrics TSDB. Raw invocations land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 300M cold-start predictor + anomaly scorer behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Serverless Function Platform (Lambda-style)', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per invocation across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":44,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Serverless Function Platform (Lambda-style) (event-driven function execution with AI autoscale) targeting ~112,500 invocations\/sec and p99 < 100 ms.","completion":"# End-to-End AI System Design: Serverless Function Platform (Lambda-style)\n\n## 1. Problem Statement & Goals\nDesign **Serverless Function Platform (Lambda-style)**, an end-to-end system for event-driven function execution with AI autoscale. It must serve ~112,500 invocations\/sec within a p99 budget of 100 ms over function code + invocation traces. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each invocation via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 300M cold-start predictor + anomaly scorer and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 25 ms, p99 < 100 ms.\n- Throughput: sustain 112,500 invocations\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~2,812 invocations\/sec per node within budget, steady-state needs ~41 nodes; provision 82 for burst + rolling deploys. Daily volume \u2248 9,720,000,000; at ~2 KB logged that is ~18.10 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 300M cold-start predictor + anomaly scorer together, applies caching, and emits a trace per invocation.\n\n## 6. Data Ingestion & Storage\nStorage tiers: code store + warm-pool registry + metrics TSDB. Raw invocations land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 300M cold-start predictor + anomaly scorer behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Serverless Function Platform (Lambda-style)', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per invocation across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":45,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: AI Observability Platform (log\/metric\/trace analysis with AI RCA) targeting ~70,000 telemetry querys\/sec and p99 < 250 ms.","completion":"# End-to-End AI System Design: AI Observability Platform\n\n## 1. Problem Statement & Goals\nDesign **AI Observability Platform**, an end-to-end system for log\/metric\/trace analysis with AI RCA. It must serve ~70,000 telemetry querys\/sec within a p99 budget of 250 ms over PB-scale telemetry. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each telemetry query via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with streaming detector + 1.5B root-cause LLM and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 62 ms, p99 < 250 ms.\n- Throughput: sustain 70,000 telemetry querys\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~1,750 telemetry querys\/sec per node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 6,048,000,000; at ~2 KB logged that is ~11.27 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires streaming detector + 1.5B root-cause LLM together, applies caching, and emits a trace per telemetry query.\n\n## 6. Data Ingestion & Storage\nStorage tiers: TSDB + trace store + embedding index. Raw telemetry querys land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses streaming detector + 1.5B root-cause LLM behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='AI Observability Platform', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per telemetry query across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":46,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: AI Observability Platform (log\/metric\/trace analysis with AI RCA) targeting ~105,000 telemetry querys\/sec and p99 < 250 ms.","completion":"# End-to-End AI System Design: AI Observability Platform\n\n## 1. Problem Statement & Goals\nDesign **AI Observability Platform**, an end-to-end system for log\/metric\/trace analysis with AI RCA. It must serve ~105,000 telemetry querys\/sec within a p99 budget of 250 ms over PB-scale telemetry. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each telemetry query via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with streaming detector + 1.5B root-cause LLM and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 62 ms, p99 < 250 ms.\n- Throughput: sustain 105,000 telemetry querys\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~2,625 telemetry querys\/sec per node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 9,072,000,000; at ~2 KB logged that is ~16.90 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires streaming detector + 1.5B root-cause LLM together, applies caching, and emits a trace per telemetry query.\n\n## 6. Data Ingestion & Storage\nStorage tiers: TSDB + trace store + embedding index. Raw telemetry querys land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses streaming detector + 1.5B root-cause LLM behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='AI Observability Platform', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per telemetry query across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":47,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: AI Secrets Management Service (secret storage with AI leak & anomaly detection) targeting ~60,000 secret accesss\/sec and p99 < 50 ms.","completion":"# End-to-End AI System Design: AI Secrets Management Service\n\n## 1. Problem Statement & Goals\nDesign **AI Secrets Management Service**, an end-to-end system for secret storage with AI leak & anomaly detection. It must serve ~60,000 secret accesss\/sec within a p99 budget of 50 ms over access logs + rotation history. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each secret access via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 300M access-pattern anomaly model and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 12 ms, p99 < 50 ms.\n- Throughput: sustain 60,000 secret accesss\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~1,500 secret accesss\/sec per node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 5,184,000,000; at ~2 KB logged that is ~9.66 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 300M access-pattern anomaly model together, applies caching, and emits a trace per secret access.\n\n## 6. Data Ingestion & Storage\nStorage tiers: encrypted KV (HSM-backed) + audit ledger. Raw secret accesss land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 300M access-pattern anomaly model behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='AI Secrets Management Service', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per secret access across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":48,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: AI Infrastructure-as-Code Assistant (natural-language to Terraform\/K8s manifests) targeting ~3,500 provisioning requests\/sec and p99 < 3000 ms.","completion":"# End-to-End AI System Design: AI Infrastructure-as-Code Assistant\n\n## 1. Problem Statement & Goals\nDesign **AI Infrastructure-as-Code Assistant**, an end-to-end system for natural-language to Terraform\/K8s manifests. It must serve ~3,500 provisioning requests\/sec within a p99 budget of 3000 ms over provider schemas + 15M IaC modules. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each provisioning request via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 1.5B IaC LLM + schema-grounded validator and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 750 ms, p99 < 3000 ms.\n- Throughput: sustain 3,500 provisioning requests\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~87 provisioning requests\/sec per node within budget, steady-state needs ~41 nodes; provision 82 for burst + rolling deploys. Daily volume \u2248 302,400,000; at ~2 KB logged that is ~0.56 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 1.5B IaC LLM + schema-grounded validator together, applies caching, and emits a trace per provisioning request.\n\n## 6. Data Ingestion & Storage\nStorage tiers: module index + plan\/state store. Raw provisioning requests land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 1.5B IaC LLM + schema-grounded validator behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='AI Infrastructure-as-Code Assistant', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per provisioning request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":49,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: AI Secrets Management Service (secret storage with AI leak & anomaly detection) targeting ~32,000 secret accesss\/sec and p99 < 50 ms.","completion":"# End-to-End AI System Design: AI Secrets Management Service\n\n## 1. Problem Statement & Goals\nDesign **AI Secrets Management Service**, an end-to-end system for secret storage with AI leak & anomaly detection. It must serve ~32,000 secret accesss\/sec within a p99 budget of 50 ms over access logs + rotation history. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each secret access via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 300M access-pattern anomaly model and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 12 ms, p99 < 50 ms.\n- Throughput: sustain 32,000 secret accesss\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~800 secret accesss\/sec per node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 2,764,800,000; at ~2 KB logged that is ~5.15 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 300M access-pattern anomaly model together, applies caching, and emits a trace per secret access.\n\n## 6. Data Ingestion & Storage\nStorage tiers: encrypted KV (HSM-backed) + audit ledger. Raw secret accesss land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 300M access-pattern anomaly model behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='AI Secrets Management Service', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per secret access across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":50,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: AI-Enhanced API Gateway (request routing with AI rate-shaping & threat scoring) targeting ~150,000 API calls\/sec and p99 < 40 ms.","completion":"# End-to-End AI System Design: AI-Enhanced API Gateway\n\n## 1. Problem Statement & Goals\nDesign **AI-Enhanced API Gateway**, an end-to-end system for request routing with AI rate-shaping & threat scoring. It must serve ~150,000 API calls\/sec within a p99 budget of 40 ms over tenant traffic logs. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each API call via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 300M request classifier + anomaly scorer and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 10 ms, p99 < 40 ms.\n- Throughput: sustain 150,000 API calls\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~3,750 API calls\/sec per node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 12,960,000,000; at ~2 KB logged that is ~24.14 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 300M request classifier + anomaly scorer together, applies caching, and emits a trace per API call.\n\n## 6. Data Ingestion & Storage\nStorage tiers: rate-limit Redis + threat-rule store + audit log. Raw API calls land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 300M request classifier + anomaly scorer behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='AI-Enhanced API Gateway', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per API call across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":51,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: PowerShell Copilot Service (natural-language to PowerShell automation) targeting ~5,250 command requests\/sec and p99 < 2500 ms.","completion":"# End-to-End AI System Design: PowerShell Copilot Service\n\n## 1. Problem Statement & Goals\nDesign **PowerShell Copilot Service**, an end-to-end system for natural-language to PowerShell automation. It must serve ~5,250 command requests\/sec within a p99 budget of 2500 ms over command docs + 20M script samples. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each command request via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 1.5B code LLM + cmdlet schema retriever and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 625 ms, p99 < 2500 ms.\n- Throughput: sustain 5,250 command requests\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~131 command requests\/sec per node within budget, steady-state needs ~41 nodes; provision 82 for burst + rolling deploys. Daily volume \u2248 453,600,000; at ~2 KB logged that is ~0.84 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 1.5B code LLM + cmdlet schema retriever together, applies caching, and emits a trace per command request.\n\n## 6. Data Ingestion & Storage\nStorage tiers: cmdlet catalog + execution audit log. Raw command requests land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 1.5B code LLM + cmdlet schema retriever behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='PowerShell Copilot Service', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per command request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":52,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: AI-Augmented Search Engine (crawl, index & semantic web search) targeting ~75,000 querys\/sec and p99 < 200 ms.","completion":"# End-to-End AI System Design: AI-Augmented Search Engine\n\n## 1. Problem Statement & Goals\nDesign **AI-Augmented Search Engine**, an end-to-end system for crawl, index & semantic web search. It must serve ~75,000 querys\/sec within a p99 budget of 200 ms over 5B crawled pages. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each query via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with bi-encoder retriever + 1.5B answer LLM and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 50 ms, p99 < 200 ms.\n- Throughput: sustain 75,000 querys\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~1,875 querys\/sec per node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 6,480,000,000; at ~2 KB logged that is ~12.07 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires bi-encoder retriever + 1.5B answer LLM together, applies caching, and emits a trace per query.\n\n## 6. Data Ingestion & Storage\nStorage tiers: inverted index + ANN index + doc store. Raw querys land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses bi-encoder retriever + 1.5B answer LLM behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='AI-Augmented Search Engine', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per query across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":53,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: AI-Augmented Search Engine (crawl, index & semantic web search) targeting ~60,000 querys\/sec and p99 < 200 ms.","completion":"# End-to-End AI System Design: AI-Augmented Search Engine\n\n## 1. Problem Statement & Goals\nDesign **AI-Augmented Search Engine**, an end-to-end system for crawl, index & semantic web search. It must serve ~60,000 querys\/sec within a p99 budget of 200 ms over 5B crawled pages. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each query via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with bi-encoder retriever + 1.5B answer LLM and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 50 ms, p99 < 200 ms.\n- Throughput: sustain 60,000 querys\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~1,500 querys\/sec per node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 5,184,000,000; at ~2 KB logged that is ~9.66 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires bi-encoder retriever + 1.5B answer LLM together, applies caching, and emits a trace per query.\n\n## 6. Data Ingestion & Storage\nStorage tiers: inverted index + ANN index + doc store. Raw querys land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses bi-encoder retriever + 1.5B answer LLM behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='AI-Augmented Search Engine', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per query across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":54,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: AI Secrets Management Service (secret storage with AI leak & anomaly detection) targeting ~50,000 secret accesss\/sec and p99 < 50 ms.","completion":"# End-to-End AI System Design: AI Secrets Management Service\n\n## 1. Problem Statement & Goals\nDesign **AI Secrets Management Service**, an end-to-end system for secret storage with AI leak & anomaly detection. It must serve ~50,000 secret accesss\/sec within a p99 budget of 50 ms over access logs + rotation history. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each secret access via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 300M access-pattern anomaly model and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 12 ms, p99 < 50 ms.\n- Throughput: sustain 50,000 secret accesss\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~1,250 secret accesss\/sec per node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 4,320,000,000; at ~2 KB logged that is ~8.05 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 300M access-pattern anomaly model together, applies caching, and emits a trace per secret access.\n\n## 6. Data Ingestion & Storage\nStorage tiers: encrypted KV (HSM-backed) + audit ledger. Raw secret accesss land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 300M access-pattern anomaly model behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='AI Secrets Management Service', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per secret access across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":55,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: AI-Driven CI\/CD Pipeline (Jenkins-style) (build orchestration with AI triage) targeting ~6,250 pipeline runs\/sec and p99 < 1500 ms.","completion":"# End-to-End AI System Design: AI-Driven CI\/CD Pipeline (Jenkins-style)\n\n## 1. Problem Statement & Goals\nDesign **AI-Driven CI\/CD Pipeline (Jenkins-style)**, an end-to-end system for build orchestration with AI triage. It must serve ~6,250 pipeline runs\/sec within a p99 budget of 1500 ms over 300M build logs. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each pipeline run via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with log encoder + 1.5B failure-triage LLM and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 375 ms, p99 < 1500 ms.\n- Throughput: sustain 6,250 pipeline runs\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~156 pipeline runs\/sec per node within budget, steady-state needs ~41 nodes; provision 82 for burst + rolling deploys. Daily volume \u2248 540,000,000; at ~2 KB logged that is ~1.01 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires log encoder + 1.5B failure-triage LLM together, applies caching, and emits a trace per pipeline run.\n\n## 6. Data Ingestion & Storage\nStorage tiers: build queue + artifact store + log warehouse. Raw pipeline runs land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses log encoder + 1.5B failure-triage LLM behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='AI-Driven CI\/CD Pipeline (Jenkins-style)', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per pipeline run across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":56,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: Serverless Function Platform (Lambda-style) (event-driven function execution with AI autoscale) targeting ~72,000 invocations\/sec and p99 < 100 ms.","completion":"# End-to-End AI System Design: Serverless Function Platform (Lambda-style)\n\n## 1. Problem Statement & Goals\nDesign **Serverless Function Platform (Lambda-style)**, an end-to-end system for event-driven function execution with AI autoscale. It must serve ~72,000 invocations\/sec within a p99 budget of 100 ms over function code + invocation traces. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each invocation via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 300M cold-start predictor + anomaly scorer and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 25 ms, p99 < 100 ms.\n- Throughput: sustain 72,000 invocations\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~1,800 invocations\/sec per node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 6,220,800,000; at ~2 KB logged that is ~11.59 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 300M cold-start predictor + anomaly scorer together, applies caching, and emits a trace per invocation.\n\n## 6. Data Ingestion & Storage\nStorage tiers: code store + warm-pool registry + metrics TSDB. Raw invocations land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 300M cold-start predictor + anomaly scorer behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='Serverless Function Platform (Lambda-style)', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per invocation across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":57,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: AI Observability Platform (log\/metric\/trace analysis with AI RCA) targeting ~87,500 telemetry querys\/sec and p99 < 250 ms.","completion":"# End-to-End AI System Design: AI Observability Platform\n\n## 1. Problem Statement & Goals\nDesign **AI Observability Platform**, an end-to-end system for log\/metric\/trace analysis with AI RCA. It must serve ~87,500 telemetry querys\/sec within a p99 budget of 250 ms over PB-scale telemetry. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each telemetry query via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with streaming detector + 1.5B root-cause LLM and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 62 ms, p99 < 250 ms.\n- Throughput: sustain 87,500 telemetry querys\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~2,187 telemetry querys\/sec per node within budget, steady-state needs ~41 nodes; provision 82 for burst + rolling deploys. Daily volume \u2248 7,560,000,000; at ~2 KB logged that is ~14.08 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires streaming detector + 1.5B root-cause LLM together, applies caching, and emits a trace per telemetry query.\n\n## 6. Data Ingestion & Storage\nStorage tiers: TSDB + trace store + embedding index. Raw telemetry querys land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses streaming detector + 1.5B root-cause LLM behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='AI Observability Platform', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per telemetry query across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":58,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: AI-Aware Package Registry (artifact hosting with vuln & quality scoring) targeting ~25,000 package requests\/sec and p99 < 300 ms.","completion":"# End-to-End AI System Design: AI-Aware Package Registry\n\n## 1. Problem Statement & Goals\nDesign **AI-Aware Package Registry**, an end-to-end system for artifact hosting with vuln & quality scoring. It must serve ~25,000 package requests\/sec within a p99 budget of 300 ms over 40M packages \/ 2B versions. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each package request via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with dependency-graph GNN + 300M code-risk classifier and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 75 ms, p99 < 300 ms.\n- Throughput: sustain 25,000 package requests\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~625 package requests\/sec per node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 2,160,000,000; at ~2 KB logged that is ~4.02 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires dependency-graph GNN + 300M code-risk classifier together, applies caching, and emits a trace per package request.\n\n## 6. Data Ingestion & Storage\nStorage tiers: blob store + dependency graph DB + index. Raw package requests land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses dependency-graph GNN + 300M code-risk classifier behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='AI-Aware Package Registry', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per package request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":59,"source_file":"ai_sysdesign_e2e_v3.jsonl"} {"instruction":"s\nYou are a senior AI systems architect. Produce a complete, production-grade end-to-end system design covering 15-20 sections, with capacity estimation, model serving, retrieval, safety, failure modes, and trade-offs. Include Python where it clarifies a component.","context":"None","question":"Design an end-to-end AI system: AI Infrastructure-as-Code Assistant (natural-language to Terraform\/K8s manifests) targeting ~2,800 provisioning requests\/sec and p99 < 3000 ms.","completion":"# End-to-End AI System Design: AI Infrastructure-as-Code Assistant\n\n## 1. Problem Statement & Goals\nDesign **AI Infrastructure-as-Code Assistant**, an end-to-end system for natural-language to Terraform\/K8s manifests. It must serve ~2,800 provisioning requests\/sec within a p99 budget of 3000 ms over provider schemas + 15M IaC modules. Goals: correctness, low tail latency, cost efficiency, and safe, auditable behavior.\n\n## 2. Functional Requirements\n- Accept each provisioning request via a versioned API.\n- Authenticate, validate, and normalize every inbound request.\n- Run inference with 1.5B IaC LLM + schema-grounded validator and return a structured response.\n- Persist I\/O for audit, replay, and offline training.\n- Expose health, readiness, and metrics endpoints.\n\n## 3. Non-Functional Requirements (SLOs)\n- Availability: 99.95% monthly (error budget ~21.9 min).\n- Latency: p50 < 750 ms, p99 < 3000 ms.\n- Throughput: sustain 2,800 provisioning requests\/sec with 2x burst.\n- Durability: 11 nines for stored artifacts.\n- Consistency: read-your-writes for sessions; eventual for analytics.\n\n## 4. Capacity Estimation & Scale\nAt ~70 provisioning requests\/sec per node within budget, steady-state needs ~40 nodes; provision 80 for burst + rolling deploys. Daily volume \u2248 241,920,000; at ~2 KB logged that is ~0.45 TB\/day of logs.\n\n## 5. High-Level Architecture\nRequest flow:\n```\nClient -> Gateway -> Auth\/RateLimit -> Orchestrator\n |\n +-----------------+-----------------+----------------+\n | | | |\n Feature\/Embed Retrieval(ANN) Model Serving Cache(Redis)\n | | | |\n +-------> Ranking \/ Post-process <--+----------------+\n |\n Response + Async Logging -> Warehouse\n```\nThe orchestrator wires 1.5B IaC LLM + schema-grounded validator together, applies caching, and emits a trace per provisioning request.\n\n## 6. Data Ingestion & Storage\nStorage tiers: module index + plan\/state store. Raw provisioning requests land in an object store partitioned by date; a Kafka CDC stage feeds the online path and an offline Delta table. Schema is registry-governed; secrets\/PII are tokenized at ingest.\n\n```python\nfrom confluent_kafka import Consumer\nimport pyarrow as pa, pyarrow.parquet as pq, json\n\ndef ingest(topic: str, sink: str, batch: int = 1000):\n c = Consumer({'group.id': 'ingest', 'auto.offset.reset': 'earliest'})\n c.subscribe([topic]); buf = []\n while True:\n msg = c.poll(1.0)\n if msg is None or msg.error():\n continue\n buf.append(tokenize_secrets(json.loads(msg.value())))\n if len(buf) >= batch:\n pq.write_to_dataset(pa.Table.from_pylist(buf),\n root_path=sink, partition_cols=['dt'])\n c.commit(asynchronous=False); buf.clear()\n```\n\n## 7. Feature \/ Embedding Pipeline\nFeatures\/embeddings are computed by a dedicated worker pool. Online reads come from Redis (sub-ms); offline features materialize nightly with point-in-time correctness to avoid leakage. Embedding version is pinned per index.\n\n```python\nimport numpy as np, redis\n\nr = redis.Redis(host='feature-store')\n\ndef embed(items, model, version):\n v = model.encode(items, batch_size=64, normalize_embeddings=True)\n return v.astype(np.float32)\n\ndef online_feature(entity_id, version):\n raw = r.get(f'feat:{version}:{entity_id}') # sub-ms read\n return np.frombuffer(raw, dtype=np.float32) if raw else None\n\ndef materialize(entities, model, version, ttl=86400):\n p = r.pipeline()\n for eid, payload in entities:\n p.set(f'feat:{version}:{eid}', embed([payload], model, version)[0].tobytes(), ex=ttl)\n p.execute()\n```\n\n## 8. Model Serving & Inference\nServing uses 1.5B IaC LLM + schema-grounded validator behind a server with **continuous batching** and a **KV-cache**. Admission is deadline-aware; **speculative decoding** with a draft model cuts decode latency; paged attention + int8 **KV-cache quantization** raise batch size. Weights are bf16.\n\n```python\nimport asyncio, time\n\nclass ContinuousBatcher:\n def __init__(self, model, max_batch=32, max_wait_ms=5):\n self.model, self.max_batch = model, max_batch\n self.max_wait = max_wait_ms \/ 1000\n self.q: asyncio.Queue = asyncio.Queue()\n\n async def submit(self, req):\n fut = asyncio.get_event_loop().create_future()\n await self.q.put((req, fut)); return await fut\n\n async def run(self):\n while True:\n batch, deadline = [], time.monotonic() + self.max_wait\n while len(batch) < self.max_batch and time.monotonic() < deadline:\n try:\n t = max(0, deadline - time.monotonic())\n batch.append(await asyncio.wait_for(self.q.get(), t))\n except asyncio.TimeoutError:\n break\n if not batch:\n continue\n outs = self.model.generate([b[0] for b in batch],\n kv_cache='paged', kv_dtype='int8')\n for (_, fut), o in zip(batch, outs):\n fut.set_result(o)\n```\n\n## 9. Retrieval & Ranking Layer\nTwo-stage retrieval: ANN recall over HNSW returns top-k candidates; a cross-encoder reranks the shortlist. Hybrid scoring blends dense similarity with lexical BM25; k is tuned on a recall@k \/ latency Pareto curve.\n\n```python\nimport numpy as np\n\ndef hybrid_retrieve(query, ann, bm25, reranker,\n k_recall=200, k_final=8, alpha=0.7):\n qv = embed_query(query)\n d_ids, d_sc = ann.search(qv, k_recall)\n l_ids, l_sc = bm25.search(query, k_recall)\n pool = {}\n for i, s in zip(d_ids, _mm(d_sc)):\n pool[i] = alpha * s\n for i, s in zip(l_ids, _mm(l_sc)):\n pool[i] = pool.get(i, 0.0) + (1 - alpha) * s\n short = sorted(pool, key=pool.get, reverse=True)[:k_recall]\n sc = reranker.predict([(query, doc_text(i)) for i in short])\n return [short[j] for j in np.argsort(sc)[::-1][:k_final]]\n\ndef _mm(x):\n x = np.asarray(x, np.float32); return (x - x.min()) \/ (x.ptp() + 1e-9)\n```\n\n## 10. Online \/ Offline Training Loop\nOffline retraining runs on versioned Delta datasets behind a champion\/challenger gate. Online feedback (accepts, edits, reverts) is aggregated into the next training set. Promotion requires passing regression and safety suites.\n\n```python\ndef promote_if_better(challenger, champion, eval_set, min_gain=0.01):\n c, p = evaluate(challenger, eval_set), evaluate(champion, eval_set)\n if c['safety_pass_rate'] < 0.999:\n return False # hard safety gate\n if c['primary'] - p['primary'] < min_gain:\n return False # insufficient lift\n registry.set_alias('production', challenger.version)\n return True\n\ndef aggregate_feedback(events):\n return [to_row(e) for e in events if e['label'] is not None]\n```\n\n## 11. Caching & Cost Optimization\nMulti-layer caching: exact-match response cache keyed by a normalized request hash; semantic cache keyed by embedding proximity for near-duplicates; prompt-prefix \/ KV reuse for shared context. Cache hits are the single largest cost lever.\n\n```python\nimport hashlib, json, numpy as np\n\nclass TwoTierCache:\n def __init__(self, r, sem, tau=0.97):\n self.r, self.sem, self.tau = r, sem, tau\n\n def _key(self, req):\n return 'resp:' + hashlib.md5(json.dumps(req, sort_keys=True).encode()).hexdigest()\n\n def get(self, req, qv):\n hit = self.r.get(self._key(req))\n if hit:\n return json.loads(hit), 'exact'\n ids, sims = self.sem.search(qv, 1)\n if len(sims) and sims[0] >= self.tau:\n return self.sem.payload(ids[0]), 'semantic'\n return None, 'miss'\n\n def put(self, req, qv, resp, ttl=300):\n self.r.set(self._key(req), json.dumps(resp), ex=ttl)\n self.sem.add(qv, resp)\n```\n\n## 12. API Design & Contracts\nA versioned REST contract with strict request\/response schemas and a health endpoint; validation rejects malformed input early.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title='AI Infrastructure-as-Code Assistant', version='1.0.0')\n\nclass Req(BaseModel):\n payload: str = Field(..., min_length=1, max_length=8192)\n tenant_id: str\n top_k: int = Field(default=8, ge=1, le=64)\n\nclass Resp(BaseModel):\n result: str\n sources: list[str]\n latency_ms: float\n model_version: str\n\n@app.post('\/v1\/execute', response_model=Resp)\nasync def execute(req: Req) -> Resp:\n if not req.payload.strip():\n raise HTTPException(400, 'empty payload')\n return await orchestrator.run(req) # cache -> retrieve -> serve\n\n@app.get('\/healthz')\ndef healthz():\n return {'status': 'ok'}\n```\n\n## 13. Observability & Evaluation\n- RED metrics per stage + GPU utilization.\n- Distributed tracing: one trace per provisioning request across all hops.\n- Quality evals: groundedness, recall@k, task accuracy.\n- Drift detection on input distribution and embedding norms.\n- Alert on error-budget burn rate, not raw thresholds.\n\n```python\nfrom prometheus_client import Histogram, Counter\nimport time, contextlib\n\nLAT = Histogram('stage_latency_ms', 'latency', ['stage'],\n buckets=(5, 10, 25, 50, 100, 250, 500, 1000, 2500))\nERR = Counter('stage_errors_total', 'errors', ['stage'])\n\n@contextlib.contextmanager\ndef observe(stage):\n start = time.perf_counter()\n try:\n yield\n except Exception:\n ERR.labels(stage).inc(); raise\n finally:\n LAT.labels(stage).observe((time.perf_counter() - start) * 1000)\n\ndef burn_rate(errors, total, slo=0.0005):\n return (errors \/ max(total, 1)) \/ slo # >1.0 = burning too fast\n```\n\n## 14. Safety, Guardrails & Compliance\n- Input guardrails: injection & secret detection pre-inference.\n- Output guardrails: dangerous-command, leakage, policy classifiers.\n- Per-tenant isolation; encryption in transit and at rest.\n- Immutable audit trail for regulatory review.\n- Human-in-the-loop approval for destructive operations.\n\n```python\nimport re\n\nINJECTION = re.compile(r'(ignore (previous|above)|system prompt|exfiltrate)', re.I)\nSECRET = re.compile(r'(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')\nDESTRUCTIVE = re.compile(r'(rm\\s+-rf|DROP\\s+TABLE|Remove-Item\\s+-Recurse|terraform destroy)', re.I)\n\ndef input_guardrail(text):\n if INJECTION.search(text):\n return False, 'prompt_injection'\n if SECRET.search(text):\n return False, 'secret_detected'\n return True, 'ok'\n\ndef output_guardrail(text):\n if DESTRUCTIVE.search(text):\n audit_log(event='requires_approval', reason='destructive_op')\n return False, 'needs_human_approval'\n return True, 'ok'\n```\n\n## 15. Failure Modes & Degradation\n- Model server down: fall back to a smaller model or cache.\n- Vector DB down: degrade to lexical-only retrieval.\n- Latency spike: shed load via deadline-aware admission.\n- Bad promotion: instant rollback via versioned aliases.\n- Circuit breakers + bulkheads isolate failing dependencies.\n\n```python\nimport time\n\nclass CircuitBreaker:\n def __init__(self, fail_max=5, reset_after=30):\n self.fail_max, self.reset_after = fail_max, reset_after\n self.fails, self.opened_at, self.state = 0, 0.0, 'closed'\n\n def allow(self):\n if self.state == 'open' and time.time() - self.opened_at > self.reset_after:\n self.state = 'half_open'\n return self.state != 'open'\n\n def record(self, ok):\n if ok:\n self.fails, self.state = 0, 'closed'\n else:\n self.fails += 1\n if self.fails >= self.fail_max:\n self.state, self.opened_at = 'open', time.time()\n\ndef serve_with_fallback(req, primary, fallback, cache, breaker):\n if breaker.allow():\n try:\n o = primary(req); breaker.record(True); return o\n except Exception:\n breaker.record(False)\n return cache.get(req) or fallback(req)\n```\n\n## 16. Scaling & Multi-Region Strategy\nStateless serving replicas autoscale on queue depth + GPU utilization. Multi-region active-active with geo-routing; indices replicate per region; the feature store replicates asynchronously cross-region.\n\n```python\ndef desired_replicas(queue_depth, gpu_util, cur,\n target_depth=50, target_util=0.65, lo=4, hi=512):\n want = max(cur * (queue_depth \/ target_depth),\n cur * (gpu_util \/ target_util))\n return int(min(hi, max(lo, round(want))))\n\ndef route_region(geo, regions, health):\n healthy = [r for r in regions if health.get(r, False)]\n if not healthy:\n raise RuntimeError('no healthy region')\n return min(healthy, key=lambda r: regions[r].rtt_ms(geo))\n```\n\n## 17. Deployment & Rollout\n- Blue\/green serving tier; canary 1% -> 10% -> 50% -> 100%.\n- Model versions behind aliases; shadow traffic before promotion.\n- Infra as code; images pinned by digest.\n- Automated rollback on SLO regression during canary.\n\n```python\nimport time\n\nCANARY_STEPS = [0.01, 0.10, 0.50, 1.00]\n\ndef canary_rollout(version, slo_check, hold_s=300):\n for pct in CANARY_STEPS:\n registry.set_weight(version, pct)\n time.sleep(hold_s)\n ok, metrics = slo_check(version)\n if not ok:\n registry.set_weight(version, 0.0) # instant rollback\n alert('canary_failed', version=version, metrics=metrics)\n return False\n registry.set_alias('production', version)\n return True\n```\n\n## 18. Trade-offs & Alternatives\n- Reranker quality vs. latency: cross-encoder is accurate but costly.\n- Cache TTL vs. freshness: longer cuts cost, risks staleness.\n- Big model vs. cost: route easy requests to a small model.\n- Consistency vs. availability: AP for analytics, CP for sessions.\n- Speculative decoding adds complexity but cuts p99.\n\n```python\ndef pick_model(difficulty, latency_budget_ms, small, large, threshold=0.5):\n if difficulty < threshold or latency_budget_ms < 200:\n return small\n return large\n\ndef cost_per_request(model, cache_hit_rate, gpu_cost_per_hr, rps):\n served = rps * (1 - cache_hit_rate)\n gpu_hrs = served \/ model.throughput_rps \/ 3600\n return gpu_hrs * gpu_cost_per_hr\n```","id":60,"source_file":"ai_sysdesign_e2e_v3.jsonl"}