Designing a Vector Search Stack
I'm thinking about how to create a comprehensive design for a vector search stack, which includes components like the choice of embedding models, indexing methods, and storage solutions. I should focus on choosing between algorithms like HNSW or IVF-PQ for indexing. I'll also consider hybrid retrieval, re-ranking techniques, and crucial safety measures. It's essential to outline requirements and assumptions, ingestion processes, and governance practices to ensure a robust design. I’ll include both high-level architecture and specific solutions to trade off between various approaches.Designing Vector Search Flow
I'm detailing a typical flow for a vector search: starting with the user query, normalizing it, then embedding it before applying BM25 for initial scoring. Next, I'll use approximate nearest neighbor (ANN) methods, merge results, rerank them, and finally apply post-filters before sending the response. I'll also compare different ANN choices with tables and include specifics like dimensions for embeddings, ensuring consistency and support for bilingual models. For the index, HNSW works well for under 100M entries, while IVF-PQ is better for larger scales.Implementing Dynamic Updates
I'm considering dynamic updates for our system. In hybrid retrieval, we can use BM25 with an inverted index like OpenSearch or Elasticsearch, then blend with vectors using methods like RRF or linear blending while applying metadata filters. For re-ranking, I'd use a small cross-encoder for the top 100 results and optionally a larger LLM for the top 20, with query expansion. Safety protocols include pre-ingestion scans, ACL enforcement during retrieval, and monitoring for data drift. I’ll make sure content moderation and privacy are prioritized.
1) High-level architecture (end-to-end)
Offline (ingestion)
- Collect documents → normalize (HTML/PDF → text), dedupe, language detect
- Chunking + metadata extraction (title, section, timestamps, ACLs, source, PII tags)
- Embed chunks → store vectors + metadata
- Build/maintain:
- ANN vector index (for semantic retrieval)
- Lexical index (BM25/term-based)
- Safety scanning at rest (PII, secrets, policy labels), versioning, audit logs
Online (query)
- Query normalization (spell, language, synonyms optional) + safety checks
- Produce:
- query embedding(s)
- lexical query (BM25)
- Retrieve candidates:
- ANN top K₁ (e.g., 200–1000)
- BM25 top K₂ (e.g., 200–1000)
- Merge → hybrid rank fusion (RRF or weighted blend), apply metadata filters + ACL
- Re-rank top N (e.g., 50–200) with cross-encoder / late-interaction
- Final safety pass (prompt-injection + sensitive content rules) → return results (or to RAG)
2) Embeddings layer
Model choice
Pick based on domain + latency budget:
- General semantic search: OpenAI
text-embedding-3-large/small, Voyage, Cohere, or open models like bge-large/e5-large.
- Enterprise / on-prem:
bge-*, e5-*, gte-* (good quality, easy to self-host).
- Multi-lingual:
multilingual-e5, bge-m3.
- If you need best precision at rerank stage: consider late-interaction (ColBERT-style) but it changes indexing (multi-vector).
Chunking strategy (matters as much as the model)
- Chunk by structure: headings → paragraphs → sentences.
- Typical: 300–800 tokens with 10–20% overlap.
- Store metadata per chunk:
doc_id, chunk_id, section_path, created_at, source, acl, pii_flags, quality_score.
Embedding hygiene
- Normalize vectors if using cosine similarity (or enforce inner product equivalence).
- Track embedding model/version; re-embed on major changes.
- Dedupe near-identical chunks (SimHash/MinHash) to reduce index bloat.
3) ANN (Approximate Nearest Neighbor) index
Common choices (practical guidance)
- HNSW (graph):
- Best default for many apps: high recall, fast, simple ops.
- Tradeoffs: memory-heavy; deletes/updates need care.
- IVF / IVF-PQ (inverted file + quantization):
- Best for very large corpora / cost control.
- Tradeoffs: more tuning, recall can suffer if misconfigured.
- DiskANN / ScaNN:
- Strong latency/recall with disk-friendly designs; good at large scale.
Typical configuration targets
- Vector count: 1M–100M+ chunks
- Latency: 20–150 ms for ANN query (excluding rerank)
- Candidate size:
- ANN returns K₁ = 200–1000 (then rerank)
- For HNSW: tune
M and efSearch (online) / efConstruction (build time).
- For IVF: tune
nlist (clusters) and nprobe (clusters searched).
Storage options
- Managed: Pinecone, Weaviate Cloud, Elastic vector, OpenSearch vector, Vertex AI Vector Search
- Self-host: Milvus, Qdrant, Weaviate, pgvector (smaller), Faiss (+ your own service)
4) Hybrid retrieval (lexical + semantic)
You almost always want hybrid because:
- BM25 wins on exact terms, part numbers, names, code symbols.
- Vectors win on paraphrase and semantic matches.
Implementation pattern
- Lexical index: Elasticsearch/OpenSearch (BM25, filters, highlighting)
- Vector index: dedicated vector DB or ES/OpenSearch vector field
Score fusion options
- RRF (Reciprocal Rank Fusion): robust, low tuning burden
score(d) = Σ 1 / (k + rank_i(d))
- Weighted sum: requires score normalization per retriever
score = α * norm(BM25) + (1-α) * norm(vector)
- Two-stage gating (optional): if query looks keyword-heavy (IDs, quotes), boost BM25.
Filters and ACLs
Apply hard filters (tenant, doc type, time range, ACL) as early as possible:
- Prefer pre-filtering at retrieval time (vector DB filter support)
- If not possible, post-filter but increase candidate size to preserve recall
5) Re-ranking (critical for precision)
Recommended two-stage ranking
- Candidate retrieval (hybrid) → 200–1000 docs
- Re-rank top N=50–200 using:
- Cross-encoder reranker (best quality/compute ratio)
- Examples:
bge-reranker-large, Cohere Rerank, Voyage rerank
- Optional LLM-based rerank for top 20 when stakes are high (costly)
- Return top 5–20 results (or feed to answer generation)
Practical tips
- Re-rank on (query, chunk_text + key metadata).
- Penalize low-quality sources via metadata features (e.g.,
quality_score, recency).
- Diversify results by
doc_id to avoid returning many chunks from one doc (MMR or per-doc caps).
6) Safety, security, and abuse resistance
A) Access control & data security (non-negotiable)
- Row-level ACL filtering at query time (tenant/user/group).
- Encrypt at rest + in transit.
- Audit logs: who searched what, which docs returned.
- Retention + deletion workflows (GDPR/DSAR): delete vectors + lexical entries + caches.
B) Content safety (retrieval + display)
- Ingestion-time classifiers:
- PII/secrets detection (API keys, passwords, SSNs)
- Malware scanning for file uploads
- Policy labels (confidential, internal, public)
- Query-time moderation (self-harm, illegal instructions, harassment, etc.) depending on product needs.
- Result-time redaction (mask sensitive fields) before returning/snippetting.
C) Prompt-injection & RAG-specific defenses
If results will be fed into an LLM:
- Treat retrieved text as untrusted input.
- Detect/strip common injection patterns (e.g., “ignore previous instructions”).
- Only allow retrieval from trusted corpora (or label-trust and downrank).
- Use a constrained system prompt that forbids tool/secret exfiltration.
- Optionally run a “retrieved-content safety classifier” before adding to context.
D) Poisoning / integrity
- Source allowlists + signed ingestion pipelines for high-trust collections.
- Monitor for unusual embedding clusters / sudden topic drift.
- Rate limiting + anomaly detection on query patterns.
7) Operating the stack (evaluation + monitoring)
Offline evaluation
- Build a labeled set of (query → relevant docs).
- Track: Recall@K, MRR, nDCG@10, precision@k.
- Evaluate each stage independently:
- Retrieval recall (hybrid candidates contain the answer?)
- Rerank quality (does it promote the right ones?)
Online monitoring
- Latency budgets per stage (embed, ANN, BM25, rerank).
- Zero-result rate, click-through / reformulation rate.
- Drift: embedding distribution changes, top-doc churn, index growth.
Reference configuration (good default starting point)
- Chunking: 500 tokens, 15% overlap, per-section metadata
- Embeddings:
bge-large (self-host) or text-embedding-3-small (managed)
- ANN: HNSW, return K₁=500
- BM25: ES/OpenSearch, return K₂=500
- Fusion: RRF
- Rerank: cross-encoder over top N=100
- Post-processing: per-doc cap (max 3 chunks/doc), MMR diversity
- Safety: ACL prefilter + PII redaction + prompt-injection scanning for RAG
If you share your constraints (corpus size, update rate, latency target, on-prem vs cloud, and whether this is for RAG), I can propose concrete component choices and sizing (index type, parameters, and stage-by-stage latency/cost).