Qdrant Python SDK: Production Patterns for FastAPI and AI
I run vector search in production for a retrieval-augmented generation pipeline that serves thousands of queries per day. The qdrant python sdk is the interface I touch most often and the one that has caused me the most subtle bugs. This post covers the patterns I use daily: async client lifecycle with FastAPI, hybrid dense and sparse search, metadata filtering that does not kill latency, batch upserts that do not OOM the instance, and HNSW settings that actually hold up under load.
How do I manage the async Qdrant client with FastAPI lifespan?
Create the client once at startup and close it on shutdown. Do not instantiate a new client per request. The async client holds a connection pool and reusing it avoids the handshake overhead on every call.
from contextlib import asynccontextmanagerfrom qdrant_client import AsyncQdrantClientfrom qdrant_client.http.models import Distance, VectorParamsfrom fastapi import FastAPI
_client: AsyncQdrantClient | None = None
@asynccontextmanagerasync def lifespan(app: FastAPI): global _client _client = AsyncQdrantClient( url="http://qdrant:6333", api_key="your-api-key", # or None for local timeout=30.0, prefer_grpc=True, # lower latency for high throughput ) # Ensure collection exists collections = await _client.get_collections() if "documents" not in [c.name for c in collections.collections]: await _client.create_collection( collection_name="documents", vectors_config={ "dense": VectorParams(size=1536, distance=Distance.COSINE), "sparse": VectorParams( size=0, # sparse vectors use dict format distance=Distance.COSINE, on_disk=True, ), }, sparse_vectors_config={ "sparse": VectorParams(size=0, distance=Distance.COSINE) }, ) yield await _client.close()
def get_client() -> AsyncQdrantClient: if _client is None: raise RuntimeError("Qdrant client not initialized") return _clientI used to pass prefer_grpc=False because the HTTP path felt safer. In production the gRPC path cuts p99 latency by roughly 30 percent for batch operations. The trade-off is a slightly more complex dependency chain. If you run into protobuf version conflicts pin grpcio and grpcio-tools in your constraints file.
For a deeper walkthrough of the FastAPI integration see Using the Qdrant Python Client with FastAPI.
How do I implement hybrid search with dense and sparse vectors?
Hybrid search combines a dense embedding (semantic meaning) with a sparse embedding (keyword matching). The qdrant python sdk supports this through named vectors and the FusionQuery API. I use sentence-transformers for dense and fastembed for sparse because both run locally without API costs.
from qdrant_client import AsyncQdrantClientfrom qdrant_client.http.models import ( FusionQuery, Fusion, NamedVector, SparseVector, Filter, FieldCondition, MatchValue,)from fastembed import SparseTextEmbeddingfrom sentence_transformers import SentenceTransformer
dense_model = SentenceTransformer("BAAI/bge-small-en-v1.5")sparse_model = SparseTextEmbedding(model_name="Qdrant/bm25")
async def hybrid_search( client: AsyncQdrantClient, query: str, top_k: int = 10, metadata_filter: Filter | None = None,) -> list[dict]: dense_vec = dense_model.encode(query).tolist() sparse_emb = list(sparse_model.embed([query]))[0] sparse_vec = SparseVector( indices=sparse_emb.indices.tolist(), values=sparse_emb.values.tolist(), )
results = await client.query_points( collection_name="documents", prefetch=[ FusionQuery( query=NamedVector(name="dense", vector=dense_vec), limit=top_k * 2, ), FusionQuery( query=NamedVector(name="sparse", vector=sparse_vec), limit=top_k * 2, ), ], query=FusionQuery(fusion=Fusion.RRF), limit=top_k, query_filter=metadata_filter, with_payload=True, ) return [{"id": p.id, "score": p.score, "payload": p.payload} for p in results.points]The key detail: request top_k * 2 in each prefetch stage so the Reciprocal Rank Fusion step has enough candidates. I learned this the hard way when hybrid results looked identical to dense-only because the sparse prefetch returned too few points.
Dense vectors capture intent. Sparse vectors capture exact terminology like error codes or product SKUs. If your queries are mostly natural language you can skip sparse and save the extra model load. If you support keyword-heavy lookup hybrid is worth the complexity.
When should I use payload filtering versus vector-only search?
Filter first when the metadata cardinality is low and the filter selectivity is high. For example filtering by tenant_id or document_type before vector search reduces the HNSW graph traversal significantly. The qdrant python sdk lets you pass a Filter object to query_points and scroll.
from qdrant_client.http.models import Filter, FieldCondition, MatchValue, Range
def tenant_filter(tenant_id: str) -> Filter: return Filter( must=[ FieldCondition(key="tenant_id", match=MatchValue(value=tenant_id)), FieldCondition( key="created_at", range=Range(gte="2024-01-01T00:00:00Z"), ), ] )Avoid filtering on high-cardinality fields like user_id if you have millions of unique values. The filter index becomes large and the planner may choose a full scan anyway. I benchmark both paths: vector-only with post-filter in Python versus pre-filter in Qdrant. Pre-filter wins when the filter cuts the candidate set by more than 90 percent. Otherwise the overhead of the filter evaluation outweighs the graph reduction.
Payload indexes are created automatically for fields used in filters but you can force them:
await client.create_payload_index( collection_name="documents", field_name="tenant_id", field_schema="keyword",)Do this at collection creation time. Creating indexes on a live collection with millions of points blocks writes.
How do I optimize batch upserts and scroll for large datasets?
Never upsert one point at a time. Batch size of 256 to 512 points is the sweet spot for my workloads. Larger batches increase memory pressure on the Qdrant node and can trigger OOM kills on small instances.
import asynciofrom qdrant_client.http.models import PointStruct, Batch
async def upsert_documents(client: AsyncQdrantClient, documents: list[dict]): batch_size = 256 for i in range(0, len(documents), batch_size): batch = documents[i : i + batch_size] points = [ PointStruct( id=doc["id"], vector={ "dense": doc["dense_embedding"], "sparse": doc["sparse_embedding"], }, payload=doc["metadata"], ) for doc in batch ] await client.upsert(collection_name="documents", points=points, wait=True) # Small backoff to avoid overwhelming the node await asyncio.sleep(0.05)Set wait=True only if you need immediate visibility. For bulk loads use wait=False and poll the collection info for vectors_count to confirm persistence.
Scrolling large result sets uses the same batching principle:
async def scroll_all(client: AsyncQdrantClient, filter_: Filter | None = None): offset = None limit = 512 while True: result, next_offset = await client.scroll( collection_name="documents", limit=limit, offset=offset, scroll_filter=filter_, with_payload=True, with_vectors=False, ) for point in result: yield point if next_offset is None: break offset = next_offsetI use with_vectors=False unless I actually need the vectors. Transferring 1536-dimension floats for every point saturates the network and adds GC pressure on the client side.
What HNSW parameters should I tune for production latency?
The defaults work for prototypes. In production I adjust three parameters per collection based on the latency budget and dataset size.
from qdrant_client.http.models import HnswConfigDiff
await client.update_collection( collection_name="documents", hnsw_config=HnswConfigDiff( m=16, # connections per node, higher = better recall more memory ef_construct=100, # build-time exploration, higher = better index quality full_scan_threshold=10000, # fallback to brute force below this count on_disk=True, # keep graph on disk, critical for >1M vectors payload_m=16, # for payload index HNSW ),)m=16is a safe default. Going to 32 improves recall but roughly doubles graph memory. I only increase it when recall@10 is below 0.95 and I have headroom.ef_construct=100is the build-time ef. Higher values slow down indexing. For bulk loads I set it to 200 then drop it back to 100 after the initial build.on_disk=Trueis non-negotiable once the collection exceeds available RAM. The performance hit is small compared to swapping.full_scan_thresholdprevents HNSW overhead on tiny collections. Keep it at 10k.
Monitor hnsw_indexed_vectors_count and hnsw_memory_usage_bytes in the collection info. If memory grows faster than vector count you have a payload index explosion. That usually means a high-cardinality field got indexed by accident.
Trade-offs and when not to use these patterns
- Async client with gRPC: adds
grpciodependency. If your deployment cannot compile native extensions stick to HTTP. - Hybrid search: two models means double the embedding latency. Cache sparse vectors for static documents.
- Payload filtering: creates additional indexes. Each index costs RAM and write throughput. Only index fields you actually filter on.
- Large batch upserts:
wait=Truemakes ingestion synchronous. For fire-and-forget pipelines usewait=Falseand accept eventual consistency. - HNSW tuning: there is no universal config. Benchmark with your actual query distribution.
FAQ
Does the qdrant python sdk support synchronous and asynchronous clients?
Yes. Import QdrantClient for blocking calls and AsyncQdrantClient for async. Do not mix them in the same event loop.
How do I handle sparse vectors with the qdrant python sdk?
Use SparseVector(indices=[...], values=[...]) when upserting and NamedVector(name="sparse", vector=sparse_vec) when querying. The indices must be sorted integers.
Can I filter and search in a single request?
Yes. Pass query_filter to query_points or scroll_filter to scroll. The filter runs before vector scoring.
What is the difference between upsert and upload_points?
upsert replaces points with the same ID. upload_points is a higher-level helper that batches internally and supports wait=False by default. I prefer explicit upsert for control.
Key Takeaways
- Initialize one
AsyncQdrantClientin FastAPI lifespan and reuse it everywhere. - Use hybrid search with RRF when you need both semantic and keyword matching.
- Filter on low-cardinality metadata before vector search to cut latency.
- Batch upserts at 256 to 512 points with
wait=Falsefor bulk loads. - Set
on_disk=Trueand tunemandef_constructonce you exceed RAM. - Monitor collection info metrics to catch index bloat early.
Working on something similar?
If you're building backend or AI systems and want a second set of senior eyes, let's talk.