Indexing: build an index of the document embeddings.
Query: convert the query to an embedding and search the index for nearest neighbors.
Hybrid Retrieval:
Combine the results from ANN with a traditional retrieval method (e.g., BM25 for keyword matching).
Methods:
a. Use both and then combine the scores (e.g., reciprocal rank fusion, weighted sum).
b. Use a learned model (e.g., a cross-encoder) to combine the two.
Alternatively, use a multi-vector approach (e.g., dense and sparse vectors) in a single index (like in Elasticsearch with dense vector and text fields).
Re-ranking:
After the initial retrieval (which might be fast but not perfect), we re-rank the top N results with a more computationally expensive model.
Typically use a cross-encoder model that takes a query and a document and outputs a relevance score.
Or use a more sophisticated model (e.g., BERT-based) that considers more context.
Safety:
Filter out unsafe content (e.g., hate speech, violence, adult content) at various stages.
Options:
a. Pre-processing: filter documents at indexing time (if we have a safety classifier).
b. Post-processing: filter the search results before presenting to the user.
c. Use a safety model to score each result and then set a threshold.
Also consider the safety of the embedding model (e.g., if the model itself is biased or toxic).
Now, let's design the flow:
Step 1: Indexing
a. For each document in the corpus:
- Check safety (if we have a pre-indexing safety filter). If unsafe, skip or tag.
- Generate an embedding using the embedding model.
- (Optionally) also generate a sparse representation (e.g., BM25 features) if we plan to do hybrid.
b. Build an ANN index with the embeddings (and store the document IDs and any other metadata).
c. (If using hybrid) Build a separate index for the sparse representation (e.g., an inverted index for BM25) or use a system that supports both.
Step 2: Query Processing
a. Check the query for safety (if the query itself is unsafe, we might reject or warn).
b. Generate an embedding for the query.
c. ANN search: retrieve top K (e.g., 100) nearest neighbor documents from the ANN index.
d. (If using hybrid) Also do a sparse retrieval (e.g., BM25) and get top M (e.g., 100) documents.
e. Combine the two sets (if hybrid) using a method like reciprocal rank fusion (RRF) or a weighted score. This gives us a combined list of top N (e.g., 50) documents.
Step 3: Re-ranking
a. Take the top N documents from the previous step (e.g., 50) and pass them through a re-ranking model (cross-encoder) that scores each (query, document) pair.
b. Sort by the re-ranker score and take the top R (e.g., 10) to present.
Step 4: Safety Filtering (post-retrieval)
a. For each of the top R documents, run a safety classifier (if not already done at indexing) to check for unsafe content.
b. Remove any that are above a safety threshold.
c. If we remove too many, we might need to fall back to the next in the re-ranked list.
Step 5: Return the final list.
However, note that safety can be applied at multiple stages. We might want to do:
Option A (index-time safety):
- Only index safe documents. Then we don't have to worry about unsafe documents in the index.
- But we might miss context: a document that is safe in isolation might be unsafe in the context of the query? (less likely, but possible)
Option B (query-time safety):
- We check each retrieved document at query time. This allows for context-aware safety (e.g., if the query is about a sensitive topic, we might be more strict).
Since safety models can be slow, we might do:
code
- Pre-indexing safety: use a fast safety model to filter out obviously unsafe documents. Then at query time, we use a more accurate (but slower) safety model on the top results.
Alternatively, we can have two safety models: one fast (for indexing and initial filtering) and one more accurate (for final filtering).
Let's adjust:
Indexing:
- Fast safety check: if document is unsafe, do not index.
- Generate embedding and index.
Query:
- Fast safety check on query: if query is unsafe, reject or sanitize.
- Retrieve (ANN and hybrid) -> get top N.
- Fast safety check on the top N (if we didn't pre-index with a fast model, but we did, so maybe skip?).
- Actually, we already pre-indexed only safe documents, so we assume the top N are safe? But note: the safety model might have changed, or we might want a more accurate check.
So we can do:
code
Indexing: fast safety filter.
Query:
- After retrieval, run a more accurate (and slower) safety model on the top N (or top R after re-ranking) to be sure.
Alternatively, if we are using a two-stage safety model, we can have:
code
Stage 1 (fast): used at indexing and also at query time on the retrieved set to quickly filter out obvious unsafe.
Stage 2 (accurate): used only on the final top R.
But to avoid too many safety checks, we might just do:
code
Indexing: fast safety filter (to keep the index clean).
Query:
- After re-ranking, run the accurate safety model on the top R.
However, if the re-ranker is a cross-encoder that already looks at the content, we might want to run safety before re-ranking to avoid wasting computation on unsafe documents? But then we might re-rank unsafe documents and then remove them, which is a waste.
So:
code
Option:
Step 2: After hybrid retrieval (top N), run a fast safety check on these N documents. Then re-rank only the safe ones.
Then after re-ranking, run an accurate safety check on the top R.
But note: the fast safety check might have false negatives (unsafe documents that pass). So we still need the accurate one at the end.
Alternatively, we can skip the fast safety check at query time if we are confident in the index-time filter, and just do the accurate one at the end.
Let's decide:
code
Implementation:
Let's define:
code
N_hybrid = 100 # number of documents from hybrid retrieval
N_re rank = 100 # we re-rank all 100
N_safety_check = 30 # we run accurate safety on the top 30 by re-ranker score
N_final = 10 # we want to return up to 10 safe documents
Steps:
code
1. Hybrid retrieval: get 100 documents (with hybrid scores).
2. Re-rank these 100 with a cross-encoder -> get 100 re-ranker scores.
3. Sort the 100 by re-ranker score (descending).
4. Take the top N_safety_check (30) and run the accurate safety model on each (if not already done at indexing? we did a fast one at indexing, but now we do accurate).
5. From these 30, filter out the unsafe ones.
6. Take the top N_final (10) by re-ranker score from the safe ones.
If we have less than 10 safe in the top 30, we return fewer.
Alternatively, if we want exactly 10, we can:
code
- If after step 5 we have less than 10 safe, then we take the next (30 - current count) from the re-ranked list (i.e., from rank 31 to 60) and run safety on them until we get 10 safe or run out of the 100.
But note: we only re-ranked 100, so we have scores for 31-60. We can do:
code
Let safe_docs = []
Let considered = top 30 (by re-ranker score) -> run safety, add safe ones to safe_docs.
If len(safe_docs) < 10:
Let next_batch = next 30 (ranks 31-60) from the re-ranked list.
Run safety on next_batch, and add the safe ones to safe_docs.
Then take the top 10 from safe_docs (by re-ranker score).
But note: the re-ranker scores for 31-60 are lower than the top 30, but we are adding them only if we don't have 10 safe from the top 30.
However, we are running safety on 60 documents now (30+30). We can set a maximum of 60.
Alternatively, we can keep going until we have 10 safe or we run out of the 100.
But note: the safety model might be slow, so we want to limit the number of safety checks.
Let's set:
code
max_safety_checks = 60 # we are willing to run the accurate safety model on up to 60 documents.
Algorithm:
code
re_ranked_docs = sorted by re-ranker score (top 100)
safe_docs = []
for i in range(0, 100, 30): # in batches of 30
batch = re_ranked_docs[i:i+30]
safe_in_batch = [doc for doc in batch if accurate_safety_model(doc) is safe]
safe_docs.extend(safe_in_batch)
if len(safe_docs) >= 10:
break
Then take the top 10 from safe_docs (by re-ranker score).
But note: we are breaking as soon as we have 10 safe, even if we haven't checked all 60. That's okay.
However, we are checking in batches of 30. We might check the first 30 and get 5 safe, then the next 30 and get 10 safe? Then we have 15 safe in total, and we take the top 10 by re-ranker score (which are from the first 30 and then the next 30, but we have to sort all safe_docs by re-ranker score?).
Actually, we are adding safe_in_batch in order of the re_ranked_docs (which is sorted). So safe_docs will be in the order of the re_ranked_docs? Not exactly: we are appending each batch, and the batches are in order. So if the first batch has 5 safe (with high scores) and the second batch has 10 safe (with lower scores), then safe_docs will have the 5 high and then 10 lower. Then taking the top 10 by re-ranker score would be the 5 from first batch and then the top 5 from the second batch? But note: the re-ranker scores in the second batch are lower than the first batch? Not necessarily: the first batch is the top 30, so the second batch (31-60) has lower scores than the first 30. But within the second batch, the scores are lower than the first batch, but we are only taking safe ones. So we want to take the 10 highest scoring safe documents. Since the first batch is already higher scoring than the second batch, we would take all 5 from the first batch and then the top 5 from the second batch (by their re-ranker score, which are the highest in the second batch). But note: we are appending the safe_in_batch in the order of the batch, which is by re-ranker score (because the batch is taken from the re_ranked_docs which is sorted). So safe_in_batch for the second batch will be in the order of the re_ranker score (from 31st to 60th). So we can just take the first 10 of safe_docs? Not exactly: because the first batch might have 5 safe, then the second batch might have 10 safe, but the safe ones in the second batch are not necessarily in order of their re-ranker score? Actually, the batch is taken from the re_ranked_docs in order, so the safe ones in the batch are in the order of the re_ranker score (since the batch is contiguous in the sorted list). So when we append, we are maintaining the order by re-ranker score? Not globally: because the first batch has higher scores than the second batch, so the safe ones in the first batch are all higher than any in the second batch. Therefore, if we take the first 10 of safe_docs, we get the 5 from the first batch (which are the highest) and then the first 5 from the second batch (which are the highest in the second batch). That is correct.
But wait: what if the first batch has 10 safe? Then we break after the first batch and safe_docs has 10 safe, and we take the first 10 (which are the top 10 safe by re-ranker score). That is correct.
So the algorithm:
code
re_ranked = list of 100 documents with re-ranker scores (sorted descending)
safe_docs = []
for start in range(0, 100, 30):
end = start + 30
batch = re_ranked[start:end]
safe_batch = []
for doc in batch:
if accurate_safety_model(doc.content) is safe:
safe_batch.append(doc)
safe_docs.extend(safe_batch)
if len(safe_docs) >= 10:
break
final_docs = safe_docs[:10] # because safe_docs is in order of re_ranker score (since batches are in order and within batch we kept order)
However, note: within a batch, we are iterating in the order of the batch (which is by re-ranker score) and appending safe ones. So safe_batch will have the safe documents in the order of the batch (which is by re-ranker score). Then when we extend safe_docs, we are appending in that order. And since the batches are in descending order of re-ranker score, safe_docs will be in descending order of re-ranker score (because all documents in batch i have higher scores than batch i+1). Therefore, taking the first 10 of safe_docs gives the top 10 safe by re-ranker score.
But what if we break in the middle of a batch? We break when we have at least 10 safe. Then we take the first 10. That is the top 10 safe by re-ranker score because we are processing batches in order and within a batch in order.
However, note: we might break after adding a batch that pushes us over 10. Then we have more than 10 safe, but we only take the first 10. That is correct.
But what if we don't break? Then we have less than 10 safe after processing all 100? Then we take all safe_docs (which is less than 10).
This algorithm works.
However, we are running the accurate safety model on up to 60 documents (if we need two batches to get 10 safe). We can adjust the batch size and the maximum number of safety checks.
Alternatively, we can run safety on the top 30, and if we don't get 10, then we run on the next 30, and so on until we get 10 or run out.
But note: the accurate safety model might be slow, so we want to minimize the number of checks.
We can also consider: what if the top 30 are all unsafe? Then we have to check the next 30. But maybe the next 30 are also unsafe. So we might have to check many.
We can set a maximum of 60 (two batches) and if we still don't have 10, we return fewer.
This is a design decision.
Putting it all together:
We have:
code
Indexing:
for each document:
if fast_safety_model(document) is safe:
embedding = embedding_model(document)
index_ann.add(embedding, document_id)
(optional) index_bm25.add(document) # for hybrid
Query:
if fast_safety_model(query) is unsafe:
return error or empty
# Hybrid retrieval
ann_results = ann_index.search(query_embedding, k=100) # returns (doc_ids, scores)
bm25_results = bm25_index.search(query, k=100) # returns (doc_ids, scores)
# Combine (using RRF or weighted sum)
combined = combine(ann_results, bm25_results, top_k=100)
# Get the documents for the top 100 combined
docs = [get_document(doc_id) for doc_id in combined]
# Re-rank the top 100 with cross-encoder
re_ranked_scores = cross_encoder.predict([(query, doc.content) for doc in docs])
re_ranked = sorted(zip(docs, re_ranked_scores), key=lambda x: x[1], reverse=True)
# Now we have 100 documents with re-ranker scores.
# Safety:
safe_docs = []
for start in range(0, 100, 30):
batch = re_ranked[start:start+30]
safe_batch = []
for doc, score in batch:
if accurate_safety_model(doc.content):
safe_batch.append((doc, score))
safe_docs.extend(safe_batch)
if len(safe_docs) >= 10:
break
# Now safe_docs is sorted by re-ranker score (because we processed in order and within batch we kept order)
final_docs = [doc for doc, score in safe_docs[:10]]
return final_docs
7. Additional considerations:
code
a. Caching: We might want to cache query results (including the final safe documents) to avoid recomputation.
b. Monitoring: Log the safety decisions and the re-ranker scores for analysis.
c. Fallback: If the vector model fails (e.g., no results from ANN), we can fall back to BM25 only.
d. Diversity: We might want to ensure diversity in the results (e.g., not all from the same source). We can add a diversification step after re-ranking.
e. Personalization: If we have user data, we might want to personalize the results.
f. Multi-lingual: If we have multiple languages, we need embedding models that support them.
g. Scalability: The ANN index should be scalable (sharding, etc.)
h. Update: How often do we update the index? We need a way to add/remove documents.
i. The safety models: we need two (fast and accurate). The fast one for indexing and query (on the query itself) and the accurate one for the final results.
j. The embedding model: we might want to use a model that is good for retrieval (e.g., fine-tuned on MS MARCO).
k. The cross-encoder: typically a model like 'cross-encoder/ms-marco-MiniLM-L-6-v2' for re-ranking.
l. The hybrid combination: we can use RRF (reciprocal rank fusion) which is parameter-free, or we can learn weights.
m. The BM25 index: we can use Elasticsearch or Lucene.
n. The ANN index: we can use FAISS, HNSWlib, or a managed service.
o. We might want to store the embeddings in a vector database that supports hybrid search (like Weaviate, Qdrant, or Elasticsearch with dense vector).
p. If we use a vector database that supports both dense and sparse, we can do hybrid in one index (e.g., Elasticsearch with dense_vector and text fields, or Weaviate with modules).
q. Alternatively, we can use two separate indices and combine the results.
8. Example with Elasticsearch:
code
Elasticsearch (with the dense vector plugin) can store both the dense vector and the text. Then we can do:
- Index: store the document with the dense vector and the text.
- Query: use a script to combine the dense vector similarity and the BM25 score? Or use the hybrid search plugin (if available) that does RRF.
But note: Elasticsearch's hybrid search (as of now) might not be as flexible as doing it externally.
Alternatively, we can do:
- Use Elasticsearch for BM25 and a separate FAISS index for dense vectors, then combine.
But if we use a vector database that supports both, it's easier.
9. Example with Weaviate:
code
Weaviate supports vector search and also has a module for hybrid search (BM25 + vector). It also supports re-ranking with a module (e.g., using a cross-encoder). And we can add a safety filter as a post-processing step.
So we can design:
- Use Weaviate as the vector database.
- Index: store the document with the vector and the text.
- Query: use hybrid search (with BM25 and vector) to get top 100.
- Then use Weaviate's re-ranking module (if available) to re-rank the top 100? Or do it externally.
- Then apply safety filter.
But note: Weaviate's re-ranking might be done in the same query? Actually, Weaviate has a "nearText" and "hybrid" search, and then you can apply a re-ranker module (like cross-encoder) as a post-processing step? I think Weaviate's re-ranker is applied during the query? We need to check.
Alternatively, we can do:
- Query Weaviate with hybrid to get top 100.
- Then externally re-rank these 100 with a cross-encoder.
- Then externally apply safety.
This is similar to our design above.
10. Conclusion:
code
The design is modular and can be implemented with various tools. The key is the flow:
Indexing:
- Fast safety filter -> embedding -> ANN index (and optionally BM25 index)
Query:
- Fast safety on query.
- Hybrid retrieval (ANN + BM25) -> top 100.
- Re-rank top 100 with cross-encoder.
- Accurate safety on the re-ranked list (in batches until we get 10 safe or checked 60).
- Return top 10 safe.
We can adjust the numbers (100, 30, 10, 60) based on performance and quality.
We also need to consider:
- The speed of each component (embedding, ANN, BM25, cross-encoder, safety models).
- The accuracy of each component.
We might want to do A/B testing to adjust the parameters.
Also, note that the re-ranker and safety models might be on different hardware (GPU for re-ranker, CPU for safety?).
We can also parallelize the safety checks in a batch.
Finally, we must log the queries and results for monitoring and improving the system.
This is a high-level design. Each component can be implemented with various tools and models.
I'll design a comprehensive vector search stack with all the components you've requested. This architecture balances performance, relevance, and safety for production-grade applications.
Commercial: Azure Content Safety, Google Cloud DLP, AWS Comprehend
Custom: Fine-tune on domain-specific harmful content
Safety Metrics to Track:
False positive rate (safe content blocked)
False negative rate (unsafe content passed)
PII detection recall/precision
User appeal rate
Deployment Architecture
Option A: Microservices (Most Flexible)
code
Load Balancer
│
├── Embedding Service (GPU cluster)
├── ANN Service (CPU/Memory optimized)
├── Hybrid Service (CPU)
├── Re-ranking Service (GPU cluster)
├── Safety Service (CPU + GPU for LLMs)
└── API Gateway (orchestration)
Freshness decay test (how fast do results degrade?)
Multi-lingual recall
Failure Modes:
ANN index corruption recovery
Embedding model fallback chain
Circuit breaker for slow components
Cost Optimization Tips
Embedding cache: TTL-based caching for frequent queries
Re-ranking budget: Only re-rank when confidence low
ANN quantization: 8-bit PQ for 4x memory reduction
Spot instances: For stateless embedding/re-ranking workers
Tiered storage: Hot/warm/cold for document corpus
Key Trade-offs to Consider
Decision
Speed
Quality
Cost
Complexity
Small vs large embeddings
↑
↓
↓
↓
ANN vs exact search
↑
↓
↓
↓
1-stage vs 2-stage rerank
↑
↑
↑
↑
Pre-filter vs post-filter safety
↑
↓
↓
↓
Custom vs managed services
↓
↑
↑
↓
This stack provides a balance of performance (sub-500ms p99), relevance (NDCG@10 > 0.45 on domain benchmarks), and safety (>99% toxic content detection). Start with the MVP, measure everything, and iterate based on your specific domain requirements and constraints.
We want to balance speed and safety.
Proposed:
Indexing:
- Use a fast safety model (e.g., a small classifier) to filter out unsafe documents. Index only the safe ones.
Query:
- Fast safety check on the query itself (if query is unsafe, we might not want to proceed).
- Retrieve top N (using ANN and hybrid).
- Re-rank the top N (since we already filtered at index time, we assume these are safe, but we might still want to run a safety check because the safety model might have improved?).
- Then, for the top R after re-ranking, run an accurate safety model (which might be slower but more accurate). Remove any that are unsafe.
Why not run the accurate safety model on the top N? Because N might be large (e.g., 100) and the accurate model might be slow.
So we run the accurate model only on the final top R (e.g., 10). This is acceptable because R is small.
But what if the re-ranker brings an unsafe document to the top? Then we would have to remove it and maybe show the next one? We can do:
- After re-ranking, we have a list of R documents with re-ranker scores.
- Then we run the accurate safety model on these R documents and remove the unsafe ones.
- Then we take the top min(R, remaining) safe documents.
If we remove some, we might want to refill from the next in the re-ranked list? But note: the re-ranker gave a score, and the next one might be safe but lower score. We can do:
- We have the re-ranked list of N (or we only re-ranked top N, so we have a list of N with scores). Then we take the top R that are safe.
But note: we only re-ranked top N. So if we remove some from the top R, we can take the next from the re-ranked list (which is already computed) until we have R safe ones.
Alternatively, we can re-rank more than R (say N=100) and then take the top R safe ones. Then we don't need to worry about refilling.
However, re-ranking 100 documents with a cross-encoder might be slow. So we might re-rank only 50, then take the top 10 safe ones.
Let's set:
N (for retrieval) = 100 (from hybrid)
Then we re-rank these 100? That might be too slow. Alternatively, we can re-rank top 50 from the hybrid results.
So:
Step 1: Hybrid retrieval -> top 100.
Step 2: Re-rank top 50 of these 100 (the top 50 by hybrid score) -> get 50 re-ranker scores.
Step 3: Sort the 50 by re-ranker score, then take the top 10 that are safe (by accurate safety model).
But note: what if the 51st is safe and the 10th is unsafe? Then we would only have 9 safe in the top 10. We can take up to 10 safe from the 50.
So we can do:
- Re-rank 50 (the top 50 from hybrid).
- Then, from these 50, run the accurate safety model and then take the top 10 by re-ranker score that are safe.
If we get less than 10, we can go to the next in the hybrid list (the 51st to 100th) and run the accurate safety model on them until we get 10? But note: we didn't re-rank them, so we don't have a re-ranker score for them.
Alternatively, we can re-rank more (like 100) to avoid this, but that's slower.
Another idea: re-rank 100, but in a batched way and with a smaller model? Or use a faster re-ranker?
Given the trade-offs, let's assume we re-rank 100 and then take the top 10 safe. But if we are concerned about speed, we can do:
- Re-rank 50, then if we don't get 10 safe, we take the next 50 (from the hybrid list) and re-rank them? That would be two batches.
This is getting complex.
Simpler: re-rank 100 and then take the top 10 safe. If we are using a GPU, re-ranking 100 might be acceptable (a few hundred ms). If we are on CPU, maybe not.
Alternatively, we can use a two-stage re-ranker:
Stage 1: a fast re-ranker (e.g., a smaller model) on the top 100 to get a rough score, then take top 50.
Stage 2: a more accurate re-ranker on the top 50.
But that might be overkill.
Let's stick to:
Hybrid retrieval: top 100.
Re-rank top 100 with a cross-encoder (if we can afford it) -> get 100 scores.
Then run accurate safety on the top 10 (or top 20) and remove unsafe ones.
But note: the accurate safety model might be slow, so we only run it on the top 10 (or 20) after re-ranking.
However, if we remove unsafe ones from the top 10, we might have less than 10. Then we can take the next from the re-ranked list (which we already have scores for) until we have 10 safe ones.
So:
Let L be the list of 100 documents with re-ranker scores (sorted by re-ranker score).
Then we take the first 10 from L that are safe (by accurate safety model). If there are less than 10 safe in the first 10, we continue to the 11th, 12th, etc. until we have 10 safe or run out.
But note: the accurate safety model might be slow, so we don't want to run it on too many. We can run it on the top 20 and hope to get 10 safe. If not, we can return less than 10.
Alternatively, we can run the accurate safety model on the top 20 and then take the top 10 safe by re-ranker score from those 20.
So:
Step 1: Hybrid -> top 100.
Step 2: Re-rank top 100 -> get 100 scores.
Step 3: Take the top 20 by re-ranker score and run accurate safety on them.
Step 4: From these 20, take the top 10 that are safe (by re-ranker score).
If we get less than 10, we can either return less or go to the next 20 (21-40) and repeat? But then we are running safety on 40, which might be acceptable.
Let's set a limit: we are willing to run safety on up to 30 documents. So:
- We have 100 re-ranked.
- We take the first 30 by re-ranker score and run safety on them.
- Then we take the top 10 safe from these 30.
This way we don't have to run safety on too many, and we have a good chance of getting 10 safe.
But what if the top 30 are all unsafe? Then we return less than 10.
Alternatively, we can do:
- Run safety on the top 30, if we get at least 10 safe, return top 10.
- If we get less than 10, then we take the next 30 (31-60) and run safety on them, and then combine the two sets (top 30 and next 30) and then take the top 10 safe by re-ranker score.
But note: the re-ranker scores are only for the first 100, so we have scores for 31-60 as well.
However, the re-ranker might have given a lower score to 31-60, but if the top 30 are unsafe, we might have to settle for lower scores.
This is a business decision: how many safe documents do we need? And how much computation are we willing to do?
Given the complexity, let's assume we are okay with returning up to 10 safe documents, and we are willing to run the accurate safety model on up to 30 documents (the top 30 by re-ranker score). If we get 10 safe in the top 30, we return the top 10. If we get less, we return what we have.
We can adjust the number 30 based on the typical safety rate.