Interview Study Guide

Guide / AI engineering Fundamentals

16. Embeddings, ANN indexes and vector databases

Created · Updated · 10 min read

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#

IndexHow it worksProsCons / edge casesUse when
Flat (brute force)Compare query to every vector100% recall, no build time, trivial updatesO(n) per query; slow beyond ~100K–1M vectorsSmall 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 bucketsLow memory, fast build, good with quantizationNeeds training on representative data; recall drops if data distribution shifts; boundary vectors missedLarge static-ish datasets, memory-constrained
HNSW (graph)Multi-layer proximity graph; greedy walk from top layer downBest 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 connectivityDefault 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 mathRecall loss; usually needs rescoring with full vectorsBillion-scale, cost-sensitive; combine with IVF or HNSW
DiskANN / SPANNGraph or cluster index kept on SSD with compressed vectors in RAMBillion-scale on one machine at low RAM costSSD latency, more complex opsVery large corpora where RAM cost dominates
ScaNN (Google)Anisotropic quantization + treeExcellent speed/recallLibrary, ecosystem mostly GoogleHigh-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#

DatabaseTypeStrengthsWeaknesses / limitationsChoose whenAvoid when
pgvector (Postgres)Extension; HNSW + IVFFlatVectors next to relational data, SQL joins and filters, ACID, one system to run, cheapSingle-node scaling limits (tens of millions comfortably, more with tuning/partitioning); HNSW build is memory-heavy; filtered queries need careYou already run Postgres; < ~10–50M vectors; need transactions with metadataBillion-scale or very high QPS vector-only workloads
PineconeFully managed, serverlessZero 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 flexibilitySmall team wanting production vector search fastStrict data residency, heavy custom querying, tight budgets at huge scale
QdrantOpen source (Rust), managed cloud availableFast, strong filtered search (payload indexes), quantization, sparse vectors, good multi-tenancyYou operate it if self-hosted; smaller ecosystem than Postgres/ElasticSelf-hosted or cloud, filter-heavy RAG, performance focusYou need full relational queries
WeaviateOpen source (Go), managed availableBuilt-in hybrid search (BM25 + vector), modules for embedding/rerank, GraphQL API, multi-tenancyMemory-heavy at scale, more moving partsHybrid search out of the box, schema-rich objectsMinimal-ops tiny deployments
Milvus / ZillizOpen source, distributed (Zilliz = managed)Billion-scale, many index types (IVF, HNSW, DiskANN, GPU indexes), separates storage/computeOperationally complex (several components), overkill when smallVery large-scale vector searchSmall to mid projects
Elasticsearch / OpenSearchSearch engine with kNN (HNSW)Mature full-text + vector hybrid in one place, aggregations, filters, existing ops knowledgeJVM memory hungry, vector performance behind dedicated engines at very large scale, tuning heavyYou already run Elastic for search/logs; hybrid search mattersPure vector workload at large scale
Redis (vector search)In-memoryVery low latency, combine with caching (semantic cache)Everything in RAM = expensive at scaleSemantic caching, small hot indexesLarge corpora
MongoDB Atlas Vector SearchManaged, alongside documentsVectors next to JSON documents, one platformTied to Atlas; less tuning than dedicated enginesAlready on MongoDB AtlasNot on Atlas
Chroma / LanceDBEmbedded / lightweightEasy local dev, prototyping, LanceDB stores on object storage (columnar)Fewer production features (Chroma), smaller scalePrototypes, notebooks, edge/local appsHigh-QPS multi-tenant production
FAISSLibrary (Meta), not a DBFastest building blocks, GPU support, every index typeNo persistence, filtering, replication, or API — you build all thatResearch, custom services, offline batch similarityWhen you need a database
No vector DB (in-memory/JSON)Embeddings in a file/array, brute-force or small index in processSimplest, zero infra, exact resultsDoesn’t scale past memory/CPU, no concurrent updates, reloads on deploySmall bounded catalogue (thousands to low hundreds of thousands)Growing corpus, multi-tenant, frequent updates

16.4 How to choose (interview answer)#

  1. Size and growth (vectors now, in 2 years), QPS, latency target.
  2. Filtering and multi-tenancy needs (per-tenant isolation, ACL filters).
  3. Need for hybrid keyword search.
  4. Existing stack (Postgres → pgvector; Elastic → Elastic kNN).
  5. Ops capacity (managed vs self-hosted), data residency, cost.
  6. 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.

DatabaseEdge caseWhat happensMitigation
pgvectorSelective metadata filter + HNSWThe index returns its top ef_search candidates, then the WHERE filter removes most, so you get fewer than k rowsRaise 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
pgvectorBuilding HNSW on a large tableBuild needs lots of maintenance_work_mem; spills make it very slow; it competes with OLTP loadBuild on a replica or off-peak, CREATE INDEX CONCURRENTLY, raise memory, consider halfvec/quantization
pgvectorPlanner skips the vector indexMissing ORDER BY embedding <=> query LIMIT k shape, or the planner prefers a filter index, which leads to a full scanKeep the canonical query shape, check EXPLAIN, tune costs
pgvectorHeavy updates/deletesDead tuples and index bloat; recall and speed driftAutovacuum tuning, periodic REINDEX CONCURRENTLY
PineconeMetadata filter cardinality and size limitsVery large metadata or high-cardinality filters slow queries or hit limitsKeep metadata small; store full text elsewhere and fetch by ID
PineconeFreshness after upsertNewly upserted vectors may not appear in queries for a short timeDon’t assume read-after-write; show “processing” or query the primary store for just-created items
PineconeMulti-tenancy at scaleOne namespace per tenant is clean, but cross-tenant queries are impossible and tenant counts in the tens of thousands need planningNamespaces per tenant for isolation; shared namespace + tenant filter for cross-tenant analytics
PineconeCost and lock-inRead/write unit pricing grows with QPS and dimensions; migration means re-exporting and re-indexingModel cost early; keep raw data and embeddings in your own store so you can rebuild elsewhere
QdrantUnindexed payload filtersFiltering on a payload field without a payload index is slowCreate payload indexes for filter fields; consider tenant-aware indexing
QdrantMemory vs disk configKeeping vectors and HNSW in RAM is fast but expensive; on-disk without quantization is slowScalar/binary quantization in RAM + original vectors on disk with rescoring
QdrantSelf-hosted cluster opsResharding, replication factor and snapshots are on youManaged cloud, or practise snapshot/restore and node replacement
WeaviateMemory growthHNSW + objects in memory grow fast with many classes/tenantsQuantization (PQ/BQ), tenant offloading of inactive tenants, capacity planning
WeaviateHybrid score tuningThe alpha balance between BM25 and vector changes results a lotTune alpha on your eval set per query type
MilvusOperational complexityMany components (coordinators, query/data nodes, object storage, message queue, etcd) to run and monitorManaged Zilliz, or only adopt at real large scale
MilvusGrowing vs sealed segmentsFresh data sits in unindexed growing segments, so queries scan them more slowly until sealed and indexedTune segment size and flush intervals; expect brief latency after bulk loads
Elasticsearch / OpenSearchHNSW memory pressure on the JVMkNN graphs off-heap or in heap compete with search caches, leading to GC pauses and node instabilityDedicated vector nodes, quantization, right-size heap vs off-heap memory
Elasticsearch / OpenSearchRefresh intervalNew docs searchable only after refresh (~1 s default)Accept near-real-time or force refresh sparingly
Elasticsearch / OpenSearchMany segmentskNN searches each segment’s graph separately, so latency rises until merges happenForce-merge read-only indexes; tune merge policy
RedisEverything in RAMCost explodes with corpus size; eviction can silently delete vectors if misconfiguredUse only for small/hot sets or semantic cache; noeviction for index data; persistence on
Chroma / LanceDBConcurrency and scaleEmbedded modes aren’t built for many concurrent writers or multi-tenant high QPSPrototype here, migrate before production scale
FAISSNo persistence or filtersProcess restart loses the index unless saved; no metadata filtering or deletes for many index typesSave/load index files, keep an ID map, filter by pre-partitioning or post-filtering with large k
In-memory / JSON embeddingsCorpus growth and deploysBrute force grows O(n); every instance holds a copy; each deploy reloads; concurrent updates are awkwardFine 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.
Finished this page?Mark it done to track your progress across the guide.
Pritam Ghosh · System design & AI engineering study notes