We are asked to architect a retrieval-augmented generation service with specific features: vector sharding, guardrails, and latency budgets. We need to design the system components, data flow, and mechanisms for these features.
We need to produce a comprehensive architecture description. Likely we should provide a diagram? But as text we can describe the architecture.
We need to consider: retrieval-augmented generation (RAG) typically involves a query, retrieval of relevant documents from a vector store, and generating an answer using an LLM with the retrieved context. Additional features:
Vector sharding: partitioning the vector index across multiple shards for scalability and performance.
Latency budgets: ensuring the system meets response time SLAs, using techniques like parallel retrieval, caching, timeout management.
We need to design a service that includes these aspects.
Potential components:
Client Request: user sends a query to the service.
API Endpoint: receives request, validates, and orchestrates processing.
Query Router: for vector sharding, we need to route the query to relevant shards. Possibly based on metadata (e.g., collection/dataset) or embedding similarity? Since vectors are embedded, we need to compute the embedding of the query and then decide which shards to search. Typically, vector stores can be partitioned by ranges of the embedding space or by metadata. For large-scale systems, we may use approximate nearest neighbor (ANN) search across shards. We need a routing layer that determines which shards to query based on the query embedding. This could involve a metadata index or a learned model to predict shards. Or we can broadcast to all shards and aggregate results (if small number of shards). But to minimize latency, we want to route only to a subset. So we need a shard selection mechanism: maybe a coarse quantizer or a simple L2 hash? Alternatively, we can use a vector index that is itself sharded and we need a top-level index to route. Or we can use a system like Milvus, which supports sharding and has a proxy that can route queries. We can design a shard router that uses a small in-memory index (e.g., product quantization codes) to map query to likely shards.
Vector Shards: each shard is a separate instance of a vector database (e.g., Faiss, HNSW, ScaNN, Milvus) with a subset of vectors. They perform similarity search and return top-k results from their shard.
Retriever Aggregator: collects results from all queried shards, merges (deduplicate if needed), re-ranks perhaps, and selects top-N context documents.
Guardrail Modules: we can apply guardrails at multiple stages:
Input guardrail: before processing, check query for malicious content, policy violations, PII, etc. Possibly modify or block.
Retrieval guardrail: ensure retrieved documents are safe, maybe filter out documents with undesirable content (e.g., adult, violent). Could be done via metadata tags or content classifiers.
Generation guardrail: before sending to LLM, we might have a prompt template that includes system messages with safety instructions. Also after generation, we might have an output filter to detect and block harmful responses. Could also use a moderation model (e.g., OpenAI Moderation) or custom classifiers.
Latency guardrails: not safety but performance, like setting timeouts, fallback strategies.
LLM Generator: takes the query and retrieved context, constructs a prompt, and calls the LLM (could be a local model or external API). It should respect latency budgets, so we might set generation parameters (max tokens) and timeouts.
Caching: to reduce latency and load, we can cache frequent queries or results at various levels: query embedding cache, retrieved results cache, LLM response cache (if deterministic). Cache invalidation strategies.
Latency Budgeting: we need to allocate time for each stage (retrieval, generation) and monitor actual times. Implement timeouts and fallback: if retrieval takes too long, maybe use fewer shards or a smaller index; if generation times out, return partial or error. Also we can parallelize retrieval across shards to stay within budget.
Monitoring & Observability: logging, metrics (latency per stage, error rates), tracing. Sliding windows for budgets.
Scaling: autoscaling of shards based on load.
Fault tolerance: if a shard fails, the system should degrade gracefully (maybe skip that shard, or use a fallback).
Let's structure the architecture in layers:
Ingestion Layer: For indexing new documents. Not the focus but we may need to handle vector sharding during ingestion too.
Query Layer: Handles user queries.
API Gateway: accepts HTTPS requests, handles auth, rate limiting, etc.
Query Service: core logic.
Input Guardrail: sanitize/validate query.
Query Embedding: compute embedding using an embedding model (could be separate microservice). Cache embeddings.
Shard Router: decides which shards to query based on embedding and maybe metadata. Could also use a consistent hashing on doc IDs? Actually sharding is by vectors; we need to know which shard contains which vectors. Usually we assign vectors to shards by some partitioning of the ID space (e.g., range of doc IDs) or by using a hash of the vector? But for ANN, you want to partition the vector space to preserve locality. A common approach is to use a coarse quantizer and assign vectors to shards based on their centroid. Then the query's nearest centroids indicate shards to search. So we need a global coarse index (maybe stored in the router) to map query to shards. Alternatively, we can broadcast to all shards but that might be inefficient.
Parallel Retrieval: send query to selected shards concurrently, with per-shard timeout (a fraction of total retrieval budget).
Result Aggregation & Re-ranking: combine results, possibly deduplicate, then re-rank using a cross-encoder or original scores, then select top K (context window size).
Retrieval Guardrail: filter out retrieved docs based on content.
Context Assembly: build prompt for LLM with query and selected context. Possibly truncate to token limit.
LLM Generator: call LLM with timeout and maybe streaming.
Output Guardrail: filter LLM response.
Response Construction: format response, add metadata (sources, etc.), return.
Support Services: Embedding Service, Guardrail Models, Cache (Redis), Metrics, Config.
Now latency budgets: we have an overall SLA (say 95th percentile < 500ms). We break into:
Query validation and embedding: 50ms
Shard routing: 10ms
Retrieval: 200ms (including network to shards)
Context processing: 30ms
LLM generation: 200ms
Output guardrail: 10ms
We need to enforce these via timeouts and monitoring. If any stage exceeds, we might return partial or fallback (e.g., for retrieval, if timeout, use a cached result or fewer shards). Also we can adjust budgets dynamically based on load.
Guardrails: we need to define what guardrails. We can use a combination:
Input: regex for PII, profanity, toxicity classifiers.
Retrieval: maybe a classifier on document content, or based on metadata (e.g., only include from approved sources). Could also use a "safe" vector index.
Generation: system prompt includes "You are a helpful assistant that refuses to generate harmful content." Also after generation, use a moderation model to check response; if flagged, either filter or replace with safe message.
Vector Sharding: we need to design the sharding strategy. Consider we have a corpus of N vectors. We can shard by assigning each vector to one of S shards. The shard assignment could be based on a hash of the document ID for simplicity, but that may not optimize ANN recall. Better to use clustering: pre-compute a coarse quantizer (e.g., using k-means) with centroids. Then assign each vector to the nearest centroid. Then group vectors by centroid into shards (maybe multiple centroids per shard). For query, compute its embedding, approximate nearest centroids, and query only shards that have those centroids. This reduces number of shards to query. The coarse quantizer can be stored in the router or in a distributed index. Alternatively, we can use a system like Spotify's Annoy or Facebook's FAISS which can shard indexes and have a meta-index for routing.
Implementation: Could use a service like Milvus which handles sharding and query routing internally. But since we are architecting, we can describe a custom solution.
We need to consider write path: adding new documents. We need to assign them to shards based on their vectors, updating the coarse quantizer periodically? Could be out of scope.
Now let's produce a structured answer: high-level overview, then detailed components with diagrams (in ASCII maybe). Also discuss trade-offs, scaling, and how guardrails and latency budgets are enforced.
We'll produce:
System Overview
Core Components
a. API Gateway
b. Query Service
c. Embedding Service
d. Shard Router
e. Vector Shards
f. Retriever Aggregator
g. Guardrail Services
h. LLM Service
i. Cache Layer
j. Monitoring & Observability
Optionally redacts or rejects the query (returns 400 or safe‑response).
Retrieval Guardrail – After aggregation:
Filters out passages with unsafe content (using same or specialized classifiers).
Removes duplicates (e.g., same source ID, high overlap) to improve diversity.
Output Guardrail – After LLM generation:
Moderation model (e.g., OpenAI Moderation, custom BERT) to catch harmful or hallucinated content.
If flagged, either truncate, replace with a safe fallback, or return an error.
Guardrail services are stateless and can be scaled independently. They may be gRPC/REST endpoints with low latency (< 5ms).
2.4. Embedding Service
Stateless service that computes dense vector embeddings for a given text.
Loads a pre‑trained model (e.g., BGE, text‑embedding‑ada‑002, E5).
Uses a GPU‑enabled inference server (Triton, TorchServe) for throughput.
Response includes the embedding (list of floats) and optional metadata (model version).
Cached in a Redis‑like store keyed by a hash of the input text (TTL configurable).
2.5. Shard Router
Holds a coarse‑grained global index that maps regions of the embedding space to the set of shards that contain vectors in those regions.
Typical implementation:
Pre‑compute k‑means centroids (e.g., 10 000) on the full corpus.
For each centroid, record which vector shards contain vectors assigned to that centroid (centroid → shard list). This mapping is static (or updated incrementally).
At query time: compute query embedding, find the nearest M centroids (e.g., M = 5) via brute force on the small centroid matrix.
The union of the shard lists for those centroids is the candidate set. Usually a query touches only a few shards (1–3) instead of all N.
The router itself is tiny (few MB) and can be kept in‑process or as a separate service (to allow hot updates).
2.6. Vector Shards
Each shard is an independent ANN index instance (e.g., FAISS‑IVF, HNSW, ScaNN, or a managed service like Milvus/Pinecone). Characteristics:
Sharding key: vectors are assigned to shards based on their centroid index (from the same clustering used by the router). A shard may hold many centroids.
Read‑optimised: indexes are stored on SSD (or memory‑mapped) and served via a lightweight RPC (gRPC/HTTP). Each shard runs on its own CPU core set/VM.
Scalability: Adding a new shard involves re‑balancing centroids and moving a subset of vectors; this can be done offline.
Fault tolerance: Shards are replicated (primary‑secondary) behind a load balancer; the router can fall back to replicas if a primary fails.
2.7. Retriever Aggregator (inside Query Service)
Receives top‑k results from each shard in parallel (with per‑shard timeout ~ 150 ms).
Merges results:
Deduplication: if the same document appears from multiple shards, keep the highest score.
Re‑ranking (optional): use a cross‑encoder or simple score fusion to produce a final ordering.
Token‑budget aware truncation: cut the combined passages to fit the LLM context window (e.g., 4 k tokens).
Emits a list of passages (text + metadata) for the generator.
2.8. LLM Service
Could be a managed API (OpenAI, Anthropic) or a self‑hosted model (Llama‑3, GPT‑NeoX) behind a inference server (vLLM, TensorRT‑LLM, TGIS).
Latency budget: The Query Service sets a hard timeout (e.g., 200 ms) on the LLM call; it also caps max_tokens (e.g., 256) to stay within the budget.
Fallback: If the LLM times out or returns an error, the system may return a cached answer (if available) or a safe fallback message like “I’m sorry, I couldn’t generate an answer right now.”
2.9. Caching
Embedding cache: key = SHA‑256(text); value = embedding vector. Reduces embedding recomputation for repeated queries.
Retrieval cache: key = (query embedding hash, top‑k parameters); value = list of passage IDs. Since embeddings are deterministic, duplicate queries hit cache.
LLM response cache: key = (query + context passages hash); value = LLM text. Works for deterministic models or when temperature=0.
Caches are stored in Redis with TTLs; they are sharded by key for scalability.
2.10. Monitoring & Observability
Metrics (Prometheus): latency per stage (embedding, routing, retrieval, LLM), cache hit rates, error counters, shard‑specific QPS.
Distributed tracing (OpenTelemetry) to follow a request across services.
Alerting on latency SLA breaches, error spikes, or guardrail trigger rates.
Dashboard (Grafana) to visualise budgets vs. actual.
3. Data Flow (Step‑by‑Step)
Receive Request → API Gateway → Query Service.
Input Guardrail scans the query; if unsafe → reject early.
Check Embedding Cache; if miss → call Embedding Service (async) while checking Retrieval Cache with query text (if embedding not yet available we cannot use retrieval cache; thus embedding is computed first).
Shard Router takes the embedding, finds nearest centroids, resolves the set of target shards.
Parallel Retrieval: Fire gRPC calls to each selected shard with the embedding and k (e.g., k=100). Each shard performs ANN and returns top‑k local results with distances.
Retrieval Aggregator merges results, re‑ranks, picks top‑p (e.g., p=5) passages that fit the token budget.
Retrieval Guardrail filters passages; if too few remain, may broaden search (fallback to more shards or lower similarity threshold) or return “no safe information found.”
Prompt Assembly – System message with safety instructions + user query + context passages.
LLM Call – Send prompt to LLM Service with timeout and max‑tokens.
Output Guardrail checks the LLM response; if unsafe, replace with safe fallback.
Response Formatting – Add citations (passage IDs/sources) and return JSON.
4. Vector Sharding Strategy
Goal: Minimise the number of shards queried while preserving high recall.
Implementation:
Offline clustering: Run k-means (k = 10 000) on a sample of the corpus (or the full set if feasible) to obtain centroids.
Assign vectors: For each vector, find its nearest centroid and assign the vector to the shard that owns that centroid. Multiple centroids can be mapped to the same shard (e.g., 100 centroids per shard for 100 shards). The mapping centroid → shard is static.
Global index for routing: Store the centroid vectors (10 k × d) in a separate FAISS index (or a simple numpy array) loaded by the Shard Router. This index is tiny (d=768 → ~30 MB) and fits in memory.
Query routing:
Compute query embedding.
Search the centroid index for the nearest M centroids (M ~ 5–10). This is cheap (O(kd) or using an inner product search on the centroids).
Look up the shard(s) that own these centroids and form the candidate shard set (deduplicated).
Optionally, if the candidate set is too large (e.g., all shards), fall back to a smaller M or use a hierarchical approach.
Write path: When ingesting new documents, compute their embedding, assign to the nearest centroid, then write the vector to the corresponding shard. The mapping centroid→shard must be known to the ingestion service.
Why this works: The coarse centroids act as a “lookup table” for the embedding space. Because ANN search is most effective locally, querying only shards whose centroids are close to the query yields high recall with far fewer shard hops.
5. Guardrails in Detail
Stage
Technique
Tools / Models
Action on Violation
Input
Regex/PII scanning, Toxicity classifier
presidio (PII), detoxify (toxicity), custom BERT
Block request, return 400 with reason
Retrieval
Content‑based filtering, Source whitelist
Same classifiers as input (faster), metadata tags
Drop the passage, optionally log for audit
Generation
System‑prompt instructions, post‑moderation
OpenAI moderation endpoint, custom safety model
If flagged: truncate, replace with safe message, or error
Latency
Hard timeouts, circuit breakers, fallback caches
N/A (infrastructure)
Return cached response or safe fallback; alert
Guardrail services are deployed as side‑cars or separate microservices behind a load balancer to avoid singletons.
6. Latency Budget Management
Total SLA: 95th percentile ≤ 500 ms (example). Budgets can be tuned per deployment.
Stage
Budget (ms)
Enforcement
Input guardrail
20
Early exit on failure
Embedding (compute + cache lookup)
50
If cache miss, async; if >50ms, use cached embedding if stale? Typically compute is ~30 ms on GPU; we allow 50.
Shard router
10
In‑process, negligible
Retrieval (including network)
200
Per‑shard timeout 150 ms; max‑shards=3; if any exceed, cut off early.
Aggregation & retrieval guardrail
30
Simple merging; guardrail <5 ms.
Prompt assembly & LLM call
200
LLM timeout = 200 ms; max_tokens=256.
Output guardrail
10
Fast classifier.
Response formatting
10
Serialization.
Total
530
Over‑budget → may drop to cached answer or safe fallback.
Mechanisms:
Deadlines: Each stage gets a sub‑deadline derived from the overall SLA (using a Stopwatch or context.WithTimeout in Go).
Circuit breakers: If a shard fails repeatedly, the router temporarily skips it.
Adaptive budgets: If system load is high, the orchestrator can shrink retrieval budget first (ask for fewer shards, smaller k) to preserve core functionality.
Priority inheritance: If LLM is slow, we may abort retrieval early and serve from cache.
7. Scalability & Fault Tolerance
Shards: Stateless apart from their index; can be scaled horizontally by adding more shards and re‑balancing centroids. Load balancer spreads read traffic.
Replication: Each shard can have a read‑replica; router can pick any healthy replica.
Cache: Redis Cluster for sharded caching; high hit rates reduce load on embedding and retrieval.
Stateless orchestrator: Multiple instances behind a load balancer; any instance can handle any request.
Graceful degradation:
Shard unavailable: router removes it from candidate set; may increase number of shards queried to maintain recall (up to a limit).
Embedding service down: fall back to a simpler model or cached embeddings; else reject.
LLM unavailable: use a smaller local model or return a static “I cannot answer now” message.
Observability: Continuous health checks, auto‑scaling based on CPU/latency.
8. Additional Considerations
Security: All inter‑service communication over mTLS or within a VPC. Secrets (API keys for external LLMs) stored in a vault (e.g., HashiCorp Vault).
Cost: Caching reduces LLM and embedding costs; LLM token limits are enforced.
Index updates: Ingestion pipeline writes new vectors to shards and updates the coarse centroid‑to‑shard mapping if needed. Periodic re‑clustering may be required as corpus drifts.
Evaluation: Regular recall‑@‑k tests on a held‑out set to ensure sharding strategy does not degrade quality.
Multi‑tenant: If serving multiple organisations, use separate vector shards and guardrail profiles; the router can include tenant ID in its decision.
9. Summary
This architecture delivers a production‑grade RAG service that:
Scales via vector sharding and parallel query execution.
Remains safe through multi‑stage guardrails (input, retrieval, output).
Meets latency SLAs by subdividing budgets, using timeouts, caching, and fallback strategies.
Is observable, fault‑tolerant, and cost‑effective.
The design is modular; each component can be swapped (e.g., different embedding model or ANN library) without affecting the whole pipeline.