Guide / AI engineering Fundamentals
16. Embeddings, ANN indexes and vector databases
A vector database stores embeddings with metadata and answers “find the k vectors nearest to this query vector”, usually with filters (tenant_id = 7 AND in_stock = true). Exact search compares against every vector; at millions of vectors you need approximate nearest neighbour (ANN) indexes that trade a little recall for orders-of-magnitude speed.
16.1 Embedding models — what to know#
- Dimensions: 384 (small, fast) to 3,072 (higher quality, more memory). Memory ≈ vectors × dims × 4 bytes: 10M × 1,536 × 4 B ≈ 61 GB before index overhead.
- Matryoshka embeddings: some models let you truncate vectors (3,072 → 256) with modest quality loss — cheap first pass, full vectors to rerank.
- Symmetric vs asymmetric: many models expect a prefix for queries vs documents; using the wrong one hurts recall.
- Domain and language: test on your data; multilingual (Hindi/Bengali/code-mixed) needs a multilingual model.
- Changing the model = re-embedding everything. Vectors from different models are not comparable. Plan versioned indexes and a backfill.
- Distance metric must match the model’s training (cosine for most text models; normalize vectors so dot product = cosine).
- Dense vs sparse: dense embeddings capture meaning; sparse (BM25, SPLADE) capture exact terms (SKUs, error codes, names). Hybrid search combines both.
16.2 ANN index types#
| Index | How it works | Pros | Cons / edge cases | Use when |
|---|---|---|---|---|
| Flat (brute force) | Compare query to every vector | 100% recall, no build time, trivial updates | O(n) per query; slow beyond ~100K–1M vectors | Small datasets, per-tenant tiny sets, ground truth for measuring recall |
| IVF (inverted file) | Cluster vectors (k-means) into nlist buckets; search only the nprobe closest buckets | Low memory, fast build, good with quantization | Needs training on representative data; recall drops if data distribution shifts; boundary vectors missed | Large static-ish datasets, memory-constrained |
| HNSW (graph) | Multi-layer proximity graph; greedy walk from top layer down | Best recall/latency trade-off, incremental inserts, tunable (M, ef_construction, ef_search) | High memory (graph links on top of vectors); deletes leave tombstones and degrade graph; slow to build at huge scale; filtered search can break connectivity | Default for most production RAG up to hundreds of millions of vectors |
| PQ / SQ (quantization) | Compress vectors: scalar (float32 → int8, 4×), product quantization (split into subvectors, store codebook IDs, 10–64×), binary (1 bit/dim, 32×) | Huge memory savings, faster distance math | Recall loss; usually needs rescoring with full vectors | Billion-scale, cost-sensitive; combine with IVF or HNSW |
| DiskANN / SPANN | Graph or cluster index kept on SSD with compressed vectors in RAM | Billion-scale on one machine at low RAM cost | SSD latency, more complex ops | Very large corpora where RAM cost dominates |
| ScaNN (Google) | Anisotropic quantization + tree | Excellent speed/recall | Library, ecosystem mostly Google | High-throughput search in Google stack |
Recall@k (fraction of true top-k returned) is the metric for ANN quality: tune ef_search / nprobe until recall ≥ ~0.95 at your latency budget, measured against flat search.
Filtered vector search is the hardest edge case. Post-filtering (search top-100 then filter) returns too few results when the filter is selective (only 1% of items match). Pre-filtering (filter first, then search) breaks HNSW graph traversal or degrades to brute force. Good engines do filter-aware traversal (Qdrant, Weaviate, Pinecone, recent pgvector iterative scans) or partition by the common filter (namespace per tenant).
16.3 Vector databases compared#
| Database | Type | Strengths | Weaknesses / limitations | Choose when | Avoid when |
|---|---|---|---|---|---|
| pgvector (Postgres) | Extension; HNSW + IVFFlat | Vectors next to relational data, SQL joins and filters, ACID, one system to run, cheap | Single-node scaling limits (tens of millions comfortably, more with tuning/partitioning); HNSW build is memory-heavy; filtered queries need care | You already run Postgres; < ~10–50M vectors; need transactions with metadata | Billion-scale or very high QPS vector-only workloads |
| Pinecone | Fully managed, serverless | Zero ops, scales automatically, namespaces for multi-tenancy, metadata filtering, hybrid (sparse + dense) | Proprietary, cost at scale, vendor lock-in, data leaves your VPC (unless enterprise options), limited query flexibility | Small team wanting production vector search fast | Strict data residency, heavy custom querying, tight budgets at huge scale |
| Qdrant | Open source (Rust), managed cloud available | Fast, strong filtered search (payload indexes), quantization, sparse vectors, good multi-tenancy | You operate it if self-hosted; smaller ecosystem than Postgres/Elastic | Self-hosted or cloud, filter-heavy RAG, performance focus | You need full relational queries |
| Weaviate | Open source (Go), managed available | Built-in hybrid search (BM25 + vector), modules for embedding/rerank, GraphQL API, multi-tenancy | Memory-heavy at scale, more moving parts | Hybrid search out of the box, schema-rich objects | Minimal-ops tiny deployments |
| Milvus / Zilliz | Open source, distributed (Zilliz = managed) | Billion-scale, many index types (IVF, HNSW, DiskANN, GPU indexes), separates storage/compute | Operationally complex (several components), overkill when small | Very large-scale vector search | Small to mid projects |
| Elasticsearch / OpenSearch | Search engine with kNN (HNSW) | Mature full-text + vector hybrid in one place, aggregations, filters, existing ops knowledge | JVM memory hungry, vector performance behind dedicated engines at very large scale, tuning heavy | You already run Elastic for search/logs; hybrid search matters | Pure vector workload at large scale |
| Redis (vector search) | In-memory | Very low latency, combine with caching (semantic cache) | Everything in RAM = expensive at scale | Semantic caching, small hot indexes | Large corpora |
| MongoDB Atlas Vector Search | Managed, alongside documents | Vectors next to JSON documents, one platform | Tied to Atlas; less tuning than dedicated engines | Already on MongoDB Atlas | Not on Atlas |
| Chroma / LanceDB | Embedded / lightweight | Easy local dev, prototyping, LanceDB stores on object storage (columnar) | Fewer production features (Chroma), smaller scale | Prototypes, notebooks, edge/local apps | High-QPS multi-tenant production |
| FAISS | Library (Meta), not a DB | Fastest building blocks, GPU support, every index type | No persistence, filtering, replication, or API — you build all that | Research, custom services, offline batch similarity | When you need a database |
| No vector DB (in-memory/JSON) | Embeddings in a file/array, brute-force or small index in process | Simplest, zero infra, exact results | Doesn’t scale past memory/CPU, no concurrent updates, reloads on deploy | Small bounded catalogue (thousands to low hundreds of thousands) | Growing corpus, multi-tenant, frequent updates |
16.4 How to choose (interview answer)#
- Size and growth (vectors now, in 2 years), QPS, latency target.
- Filtering and multi-tenancy needs (per-tenant isolation, ACL filters).
- Need for hybrid keyword search.
- Existing stack (Postgres → pgvector; Elastic → Elastic kNN).
- Ops capacity (managed vs self-hosted), data residency, cost.
- Update pattern (append-only vs frequent updates/deletes).
Typical answer: “Start with pgvector if we already run Postgres and the corpus is under ~10M chunks; move to Qdrant/Pinecone/Milvus when QPS, size or filter performance demand it. Keep the retrieval layer behind an interface so the store can change.”
16.5 Operational edge cases#
- Deletes and updates: HNSW handles them poorly (tombstones); schedule compaction/rebuilds.
- Multi-tenancy: namespace/collection per tenant (strong isolation, many small indexes) vs shared index with tenant filter (efficient, but filter must be enforced server-side — a missing filter leaks data across tenants).
- Consistency: many vector DBs are eventually consistent — a just-inserted document may not be searchable for a second.
- Index rebuilds: building HNSW over 100M vectors takes hours and lots of RAM; blue-green the index (build new, switch alias).
- Backups and source of truth: keep raw text + metadata in a primary store; the vector index should be rebuildable from it.
- Cost: RAM dominates; quantization and disk-based indexes cut it 4–32×.
16.6 Edge cases per vector database#
What tends to go wrong with each in production, and the mitigation to mention. Features change quickly in this space, so confirm the current behaviour in each vendor’s docs before relying on a specific detail.
| Database | Edge case | What happens | Mitigation |
|---|---|---|---|
| pgvector | Selective metadata filter + HNSW | The index returns its top ef_search candidates, then the WHERE filter removes most, so you get fewer than k rows | Raise ef_search, use iterative index scans in newer versions, partial indexes or partitions per tenant/category, or exact search on the filtered subset when it’s small |
| pgvector | Building HNSW on a large table | Build needs lots of maintenance_work_mem; spills make it very slow; it competes with OLTP load | Build on a replica or off-peak, CREATE INDEX CONCURRENTLY, raise memory, consider halfvec/quantization |
| pgvector | Planner skips the vector index | Missing ORDER BY embedding <=> query LIMIT k shape, or the planner prefers a filter index, which leads to a full scan | Keep the canonical query shape, check EXPLAIN, tune costs |
| pgvector | Heavy updates/deletes | Dead tuples and index bloat; recall and speed drift | Autovacuum tuning, periodic REINDEX CONCURRENTLY |
| Pinecone | Metadata filter cardinality and size limits | Very large metadata or high-cardinality filters slow queries or hit limits | Keep metadata small; store full text elsewhere and fetch by ID |
| Pinecone | Freshness after upsert | Newly upserted vectors may not appear in queries for a short time | Don’t assume read-after-write; show “processing” or query the primary store for just-created items |
| Pinecone | Multi-tenancy at scale | One namespace per tenant is clean, but cross-tenant queries are impossible and tenant counts in the tens of thousands need planning | Namespaces per tenant for isolation; shared namespace + tenant filter for cross-tenant analytics |
| Pinecone | Cost and lock-in | Read/write unit pricing grows with QPS and dimensions; migration means re-exporting and re-indexing | Model cost early; keep raw data and embeddings in your own store so you can rebuild elsewhere |
| Qdrant | Unindexed payload filters | Filtering on a payload field without a payload index is slow | Create payload indexes for filter fields; consider tenant-aware indexing |
| Qdrant | Memory vs disk config | Keeping vectors and HNSW in RAM is fast but expensive; on-disk without quantization is slow | Scalar/binary quantization in RAM + original vectors on disk with rescoring |
| Qdrant | Self-hosted cluster ops | Resharding, replication factor and snapshots are on you | Managed cloud, or practise snapshot/restore and node replacement |
| Weaviate | Memory growth | HNSW + objects in memory grow fast with many classes/tenants | Quantization (PQ/BQ), tenant offloading of inactive tenants, capacity planning |
| Weaviate | Hybrid score tuning | The alpha balance between BM25 and vector changes results a lot | Tune alpha on your eval set per query type |
| Milvus | Operational complexity | Many components (coordinators, query/data nodes, object storage, message queue, etcd) to run and monitor | Managed Zilliz, or only adopt at real large scale |
| Milvus | Growing vs sealed segments | Fresh data sits in unindexed growing segments, so queries scan them more slowly until sealed and indexed | Tune segment size and flush intervals; expect brief latency after bulk loads |
| Elasticsearch / OpenSearch | HNSW memory pressure on the JVM | kNN graphs off-heap or in heap compete with search caches, leading to GC pauses and node instability | Dedicated vector nodes, quantization, right-size heap vs off-heap memory |
| Elasticsearch / OpenSearch | Refresh interval | New docs searchable only after refresh (~1 s default) | Accept near-real-time or force refresh sparingly |
| Elasticsearch / OpenSearch | Many segments | kNN searches each segment’s graph separately, so latency rises until merges happen | Force-merge read-only indexes; tune merge policy |
| Redis | Everything in RAM | Cost explodes with corpus size; eviction can silently delete vectors if misconfigured | Use only for small/hot sets or semantic cache; noeviction for index data; persistence on |
| Chroma / LanceDB | Concurrency and scale | Embedded modes aren’t built for many concurrent writers or multi-tenant high QPS | Prototype here, migrate before production scale |
| FAISS | No persistence or filters | Process restart loses the index unless saved; no metadata filtering or deletes for many index types | Save/load index files, keep an ID map, filter by pre-partitioning or post-filtering with large k |
| In-memory / JSON embeddings | Corpus growth and deploys | Brute force grows O(n); every instance holds a copy; each deploy reloads; concurrent updates are awkward | Fine for bounded catalogues; set a size threshold where you move to pgvector/Qdrant; version the embedding file |
Edge cases that apply to every vector store:
- Embedding model upgrade: old and new vectors are incompatible, so build a new index in parallel, backfill, shadow-compare retrieval quality, then switch an alias.
- Duplicate and near-duplicate chunks crowd the top-k with the same content: dedupe at ingestion, or use MMR (maximal marginal relevance) to diversify results.
- Very short queries (“refund”) embed poorly: add hybrid keyword search or query expansion.
- Numbers, SKUs, dates and negation (“not waterproof”) are weak spots for dense embeddings: handle with metadata filters and keyword search.
- Score thresholds aren’t portable: cosine 0.8 means different things per model and domain, so calibrate thresholds on your eval set.
- Deleting a user’s data (GDPR) must reach the vector index, caches and backups, not just the primary DB.