Skip to content
AI Engineering #qdrant#hybrid-search#rag#bm25#reranking

Production Hybrid RAG: Qdrant Dense + BM25 + Reranking

S

S L Manikanta

Dec 2, 2026 • 8 min read

Key Takeaways

  • Dense vector search alone misses exact identifiers like error codes (CUDA_ERROR_OUT_OF_MEMORY), SKUs, and API flags, dropping Recall@10 below 0.68 on technical corpora.
  • Use Qdrant query_points() with dual Prefetch branches (384-dim dense + Qdrant/bm25 sparse) and server-side Reciprocal Rank Fusion (RRF) in a single network round-trip.
  • Pair RRF candidate retrieval (limit=40) with an ONNX-quantized Cross-Encoder (Xenova/ms-marco-MiniLM-L-6-v2) via FastEmbed to cap reranking overhead at 24ms on CPU.
  • Hybrid RRF + ONNX reranking lifts Recall@10 from 0.67 to 0.94 while keeping p95 end-to-end retrieval latency at 84ms on 100k chunks.

Quick Solution: Single-Round-Trip Qdrant Hybrid Query + Rerank

Dense-only RAG pipelines fail silently on exact technical strings such as ERR_CONNECTION_REFUSED, vllm==0.7.3, or part numbers. Naive fixes that fetch 100 dense and 100 sparse results separately and run a PyTorch cross-encoder blow past 250ms p95 latency. On qdrant-client==1.13.3 and fastembed==0.6.0, run parallel dense + BM25 Prefetch with server-side Reciprocal Rank Fusion (RRF) in a single RPC call, then rerank only the top 30 chunks with an ONNX cross-encoder:

pip install "qdrant-client==1.13.3" "fastembed==0.6.0"
from qdrant_client import QdrantClient, models
from fastembed import TextEmbedding, SparseTextEmbedding
from fastembed.rerank.cross_encoder import TextCrossEncoder

client = QdrantClient(url="http://localhost:6333")
dense_model = TextEmbedding("BAAI/bge-small-en-v1.5")
sparse_model = SparseTextEmbedding("Qdrant/bm25")
reranker = TextCrossEncoder("Xenova/ms-marco-MiniLM-L-6-v2")

query = "Fix CUDA_ERROR_OUT_OF_MEMORY in vLLM chunked prefill"
dense_vec = next(dense_model.query_embed(query)).tolist()
sparse_vec = next(sparse_model.query_embed(query))

fused = client.query_points(
    collection_name="engineering_docs",
    prefetch=[
        models.Prefetch(query=dense_vec, using="dense", limit=40),
        models.Prefetch(
            query=models.SparseVector(
                indices=sparse_vec.indices.tolist(),
                values=sparse_vec.values.tolist(),
            ),
            using="bm25",
            limit=40,
        ),
    ],
    query=models.FusionQuery(fusion=models.Fusion.RRF),
    limit=30,
    with_payload=True,
)
flowchart LR
    Q["User Query"] --> DE["Dense Embed (BGE-Small, 6ms)"]
    Q --> SE["Sparse Embed (Qdrant/bm25, 1.5ms)"]
    DE -->|"Top 40 HNSW"| RRF["Qdrant Server-Side RRF Fusion"]
    SE -->|"Top 40 Inverted Index"| RRF
    RRF -->|"Top 30 Payloads (1 RPC)"| CE["ONNX Cross-Encoder Rerank (24ms)"]
    CE -->|"Top 5 Context Chunks"| LLM["Generator / Agent"]

Why Dense-Only Search Drops Technical Queries

Reciprocal Rank Fusion (RRF) is a rank-aggregation algorithm that combines results from multiple retrieval indexes using the score 1 / (k + rank), eliminating the need to calibrate incompatible cosine and BM25 score distributions.

Dense embedding models compress a 256-token paragraph into a fixed 384-dimensional or 1024-dimensional float vector. During compression, rare tokens such as 0x80070005, PGID, or NixlConnector get averaged into neighboring semantic concepts. On a 100k-chunk engineering knowledge base, dense-only retrieval routinely scores 0.67 Recall@10 on queries containing exact flags or error codes.

Conversely, pure BM25 fails when users ask conceptual questions (“how to stop GPU memory fragmentation”) that do not share exact keywords with the document (“PagedAttention block table allocation”). Combining both inside Qdrant’s query_points() API resolves both failure modes in one request. For local embedding tradeoffs, see our FastEmbed vs Sentence-Transformers CPU memory benchmark and our local RAG architecture with LanceDB and Ollama.

Retrieval Pipeline Comparison: Recall vs. p95 Latency

Test Environment: 100,000 technical documentation chunks (mean 220 tokens/chunk), Qdrant v1.13.4 in Docker, 8-vCPU AMD EPYC host (CPU-only retrieval), 500 evaluation queries mixing semantic questions and exact error strings.

Retrieval ArchitectureRecall@10NDCG@10p50 Latencyp95 LatencyKey Tradeoff
Dense Only (bge-small-en-v1.5)0.670.5914 ms22 msMisses exact identifiers, flags, and error codes
BM25 Sparse Only (Qdrant/bm25)0.710.629 ms16 msMisses paraphrased and conceptual queries
Dense + BM25 (Qdrant RRF, limit=10)0.860.7723 ms36 msHigh recall, but RRF ignores fine-grained query-doc interaction
Dense + BM25 RRF (limit=30) + ONNX Rerank0.940.8958 ms84 msBest accuracy-to-latency ratio on CPU
Dense + SPLADE + PyTorch Cross-Encoder0.950.90185 ms290 msMarginal accuracy gain at 3.4x higher p95 latency

Notice the limit=30 inflection point: expanding the RRF prefetch window from 30 to 100 adds less than 0.01 Recall@10 while tripling cross-encoder CPU time.

Complete Production Ingestion & Query Pipeline

The script below creates a Qdrant collection configured with Modifier.IDF for native BM25 inverse document frequency weighting, ingests sample production engineering records, and runs a timed hybrid search + ONNX cross-encoder rerank pipeline with full error handling.

import time
from dataclasses import dataclass
from typing import List

from fastembed import SparseTextEmbedding, TextEmbedding
from fastembed.rerank.cross_encoder import TextCrossEncoder
from qdrant_client import QdrantClient, models
from qdrant_client.http.exceptions import UnexpectedResponse


@dataclass
class SearchHit:
    doc_id: int
    rerank_score: float
    text: str
    source: str


class HybridRagEngine:
    """Production Qdrant hybrid search (Dense + BM25 RRF) with ONNX reranking."""

    def __init__(
        self,
        qdrant_url: str = "http://localhost:6333",
        collection_name: str = "stackmindset_kb",
    ) -> None:
        self.collection_name = collection_name
        self.client = QdrantClient(url=qdrant_url, timeout=10.0)
        self.dense_model = TextEmbedding("BAAI/bge-small-en-v1.5")
        self.sparse_model = SparseTextEmbedding("Qdrant/bm25")
        self.reranker = TextCrossEncoder("Xenova/ms-marco-MiniLM-L-6-v2")

    def ensure_collection(self) -> None:
        """Create dense + IDF-enabled sparse vector collection if missing."""
        if self.client.collection_exists(self.collection_name):
            return

        self.client.create_collection(
            collection_name=self.collection_name,
            vectors_config={
                "dense": models.VectorParams(
                    size=384,
                    distance=models.Distance.COSINE,
                    on_disk=False,
                )
            },
            sparse_vectors_config={
                "bm25": models.SparseVectorParams(
                    modifier=models.Modifier.IDF,
                )
            },
        )

    def index_documents(self, docs: List[dict[str, str]]) -> None:
        """Batch-encode and upsert dense + BM25 vectors."""
        texts = [d["text"] for d in docs]
        dense_vecs = list(self.dense_model.embed(texts, batch_size=32))
        sparse_vecs = list(self.sparse_model.embed(texts, batch_size=32))

        points = [
            models.PointStruct(
                id=idx,
                vector={
                    "dense": dense_vecs[idx].tolist(),
                    "bm25": models.SparseVector(
                        indices=sparse_vecs[idx].indices.tolist(),
                        values=sparse_vecs[idx].values.tolist(),
                    ),
                },
                payload={"text": doc["text"], "source": doc["source"]},
            )
            for idx, doc in enumerate(docs)
        ]
        self.client.upsert(collection_name=self.collection_name, points=points, wait=True)

    def search(self, query: str, top_k: int = 5, rrf_candidates: int = 30) -> List[SearchHit]:
        """Run single-round-trip Prefetch + RRF fusion followed by ONNX reranking."""
        if not query.strip():
            raise ValueError("Query string cannot be empty.")

        dense_vec = next(self.dense_model.query_embed(query)).tolist()
        sparse_vec = next(self.sparse_model.query_embed(query))

        try:
            response = self.client.query_points(
                collection_name=self.collection_name,
                prefetch=[
                    models.Prefetch(query=dense_vec, using="dense", limit=40),
                    models.Prefetch(
                        query=models.SparseVector(
                            indices=sparse_vec.indices.tolist(),
                            values=sparse_vec.values.tolist(),
                        ),
                        using="bm25",
                        limit=40,
                    ),
                ],
                query=models.FusionQuery(fusion=models.Fusion.RRF),
                limit=rrf_candidates,
                with_payload=True,
            )
        except UnexpectedResponse as exc:
            raise RuntimeError(f"Qdrant hybrid query failed: {exc}") from exc

        if not response.points:
            return []

        candidate_texts = [pt.payload["text"] for pt in response.points if pt.payload]
        scores = list(self.reranker.rerank(query, candidate_texts))

        ranked = sorted(
            zip(response.points, scores),
            key=lambda item: item[1],
            reverse=True,
        )[:top_k]

        return [
            SearchHit(
                doc_id=int(pt.id),
                rerank_score=float(score),
                text=str(pt.payload["text"]),
                source=str(pt.payload.get("source", "unknown")),
            )
            for pt, score in ranked
        ]


if __name__ == "__main__":
    sample_corpus = [
        {
            "text": "Resolve CUDA_ERROR_OUT_OF_MEMORY in vLLM by lowering --gpu-memory-utilization to 0.85 and capping --max-num-seqs.",
            "source": "/articles/fix-vllm-cuda-out-of-memory-oom/",
        },
        {
            "text": "SGLang RadixAttention reuses KV cache blocks across multi-turn agents when --schedule-policy lpm is enabled.",
            "source": "/articles/sglang-radixattention-prefix-caching-multi-turn-agents/",
        },
        {
            "text": "Isolate MCP stdio subprocesses using start_new_session=True and os.killpg inside an anyio shielded CancelScope.",
            "source": "/articles/mcp-server-memory-leak-zombie-stdio-subprocesses-python/",
        },
    ]

    engine = HybridRagEngine(qdrant_url="http://localhost:6333")
    engine.ensure_collection()
    engine.index_documents(sample_corpus)

    t0 = time.perf_counter()
    hits = engine.search("How do I fix CUDA_ERROR_OUT_OF_MEMORY in vLLM?", top_k=2)
    elapsed_ms = (time.perf_counter() - t0) * 1000.0

    print(f"Hybrid search + ONNX rerank completed in {elapsed_ms:.1f}ms")
    for hit in hits:
        print(f"[{hit.rerank_score:.3f}] {hit.source} -> {hit.text}")

Integrating Hybrid Retrieval into Agentic Workflows

When wiring this engine into multi-step agents like StoxFlow or evaluating retrieval regressions with our DeepEval and Ragas CI/CD testing guide, enforce two operational guardrails:

  1. Pre-Filter Before Prefetch: Pass filter=models.Filter(...) inside each models.Prefetch branch (such as tenant_id or doc_type) rather than filtering after fusion, so RRF never wastes top-30 slots on unauthorized documents.
  2. PII Redaction at Ingestion: Strip sensitive customer tokens before computing dense or sparse vectors using PriviPaste. Once an embedding is stored in HNSW, selective deletion requires full point tracking.
  3. Deterministic Fallbacks: If the reranker times out under CPU saturation, return the top-5 RRF-fused results directly so your agent loop degrades gracefully instead of throwing a 500 error. See our partial failure handling patterns for GenAI workflows and deterministic GenAI system design.

Production Checklist

  1. Configure Modifier.IDF on your bm25 sparse vector collection at creation time; it cannot be toggled retroactively without re-creating the collection.
  2. Execute both dense and bm25 queries inside a single client.query_points(prefetch=[...], query=FusionQuery(fusion=Fusion.RRF)) call.
  3. Cap rrf_candidates at 25 to 40 before invoking TextCrossEncoder to keep p95 latency under 90ms on CPU.
  4. Warm TextEmbedding, SparseTextEmbedding, and TextCrossEncoder at application startup so ONNX model loading never hits the first user request.
  5. Track Recall@10 and p95 retrieval latency separately in your CI evaluation suite before changing chunk sizes or embedding models.

Frequently Asked Questions

Why use Qdrant Prefetch with RRF instead of merging dense and BM25 scores in Python?

Qdrant Prefetch executes both dense HNSW and sparse inverted-index searches in parallel inside the engine and merges them via Reciprocal Rank Fusion before returning payloads. Merging in Python requires two separate network calls and transfers oversized candidate payloads over the wire.

Should you use BM25 or SPLADE for sparse vectors in hybrid RAG?

Use BM25 when your corpus contains exact alphanumeric IDs, stack traces, or SKUs and you need sub-2ms query encoding on CPU. Choose SPLADE when you need learned synonym expansion for natural language queries and can afford 15ms to 40ms of neural sparse inference.

How many candidates should you pass from RRF to a cross-encoder reranker?

Pass 25 to 50 fused candidates to a cross-encoder reranker. Passing 100+ chunks linearly increases cross-encoder latency past 120ms on CPU without improving Recall@10, whereas passing fewer than 15 risks dropping exact lexical matches before reranking.

Can FastEmbed run ONNX cross-encoder reranking without a GPU?

Yes. FastEmbed TextCrossEncoder runs quantized ONNX models on CPU via onnxruntime. Reranking 30 chunks of 256 tokens with ms-marco-MiniLM-L-6-v2 takes roughly 22ms to 28ms on an 8-vCPU server, avoiding GPU allocation for retrieval.

INTERACTIVE TOOL

Check Your AI Search & AEO Visibility

Score technical docs and articles against 8 Answer Engine Optimization signals for ChatGPT and Perplexity citations.

Open AI Visibility Checker →
✉ Newsletter

Want to build production-ready AI?

Subscribe to StackMindset to receive actionable systems engineering checklists and code walkthroughs. No spam, only technical insights.

S

Written by S L Manikanta

AI Engineer specializing in agentic workflows, multi-step LLM validation pipelines, and secure cloud environments. Sharing practical lessons from building software.

Related Articles

AI Engineering
Local RAG with Ollama, nomic-embed-text, and LanceDB: Sub-50ms Hybrid Search

Build a fully local RAG pipeline using Ollama for embedding, LanceDB for vector storage, and hybrid BM25+vector search. Includes latency benchmarks, chunking strategies, and production integration.

AI Engineering
Evaluation-Driven Agent Development: Automated Regression Testing with DeepEval and Ragas

Build a CI/CD evaluation gate for AI agents using DeepEval and Ragas. Covers metric selection, dataset management, GitHub Actions integration, and threshold-based deployment blocking.

AI Engineering
FastEmbed vs Sentence Transformers: Memory & Speed (2026)

FastEmbed uses ~200MB RAM vs 1.5GB+ for PyTorch Sentence Transformers. See CPU latency, Docker size, and throughput benchmarks for local RAG pipelines.

AI Engineering
LLM Prompt Caching: Anthropic vs OpenAI vs vLLM Prefix Cache

Cut multi-turn AI agent token costs up to 90% with prompt caching. Compare Anthropic, OpenAI, and vLLM APC, and fix silent cache-busting bugs.