Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Retrieval and RAG

Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers

Millions of vectors, a filter per customer and a tight latency budget: which index? Estimate memory (15,360 MB flat, 16,640 MB HNSW, about 240 MB IVF-PQ for 10 M x 384 dims, arithmetic), turn the IVF dial (recall 0.55, 0.892, 0.994, simulated), and see why filtering after the search gives the smallest customer a recall of 0.052.

Chaand Sheikh

·27 November 2026Retrieval and RAG

What you will learn

  • Name the three things every vector index trades: recall, latency and memory
  • Compare flat, HNSW and IVF-PQ, and estimate their memory out loud
  • Turn the IVF dial and read what the last bit of recall costs
  • Explain why filtering after the search starves a small tenant, and what to do instead

Before you start

  • Similarity Search: Finding the Closest Vectors
  • Vector Databases Hands-On: Chroma and pgvector

The interview version: you've got millions of vectors, a filter for each customer, and a tight latency budget. What index do you pick? Most people say "HNSW, because it's fast". A strong answer starts from the constraint, not from a favourite name.

A vector index is how a search finds the closest vectors without checking all of them. Numbers below come either from a small simulation with synthetic vectors, or from plain arithmetic, and each says which. If brute-force search is new to you, start with Similarity Search.

Three things to trade

  • Recall. Of the true ten closest, how many did we actually get back?
  • Latency. How long does one search take?
  • Memory. How much has to sit in the machine to make it fast?

Push one up, and usually another pays. On top of that sits one more question: when do you apply the customer's filter?

Knocking on every door

You're looking for a house in a big city. You could knock on every door. You'd definitely find it, and you'd be at it all year. So you use a map: go to the right neighbourhood first, and only knock there. Much faster, but if the house is just over the border, you miss it. So you check a couple of neighbourhoods and buy back some certainty with more walking. An index skips most doors on purpose, so it can miss, and you decide how much missing is okay.

Flat, HNSW and IVF-PQ

IndexHow it worksRule of thumb
FlatCompares the query with every vector; recall is 1Exact, and expensive as data grows
HNSWA graph, like roads between neighbours; the search keeps hopping to the closer neighbourSpends memory to save time
IVF-PQIVF groups vectors into lists and searches only the nearest few; PQ shrinks each vector to a short codeSaves memory, gives up some recall

HNSW in practice is shown in Vector Databases Hands-On.

The memory estimate

An interviewer usually wants a memory estimate, and you can do it out loud. This is arithmetic for illustration, not measured: 10 million vectors x 384 dimensions x 4 bytes per number.

Memory estimate: flat, HNSW, IVF-PQ Flat 15,360 MB HNSW 16,640 MB IVF-PQ about 240 MB (24 bytes per vector) Arithmetic for illustration: 10 M x 384 dims x 4 bytes, not measured
HNSW keeps every vector and adds its links. IVF-PQ is before its extra tables.

So you don't pick by name:

  • A small partition, or you need exact results: flat.
  • Memory to spare and tight latency: HNSW is usually first in line.
  • Memory is the wall: IVF-PQ, and rerank the top few to win back recall.

The dial

These indexes come with a dial. A small simulation with 20,000 synthetic vectors and 64 lists:

corpus: 20000 x 32 (synthetic)
flat             recall@10=1.000  scanned= 20000
ivf nprobe=1     recall@10=0.550  scanned=   371
ivf nprobe=4     recall@10=0.892  scanned=  1303
ivf nprobe=16    recall@10=0.994  scanned=  5075

Search one list, and recall is 0.55. Four lists, 0.892. Sixteen lists, 0.994, scanning about 5,000 vectors: a quarter of everything. The last bit of recall costs the most work. Set the dial from your recall target, then check latency at p95. No HNSW or PQ was built in this simulation, so there are no measured numbers for those.

Ask for ten, get almost nothing

Now the failure. There are eight synthetic customers, and the smallest one holds about half a percent of the vectors. Search everything, take the top ten, then filter down to that customer:

Recall per customer by filter strategy Smallest customer (0.5%) Biggest (49.8%) after, fetch 10 0.052 after, fetch 100 0.14 first, exact 1.0 first, IVF 4 lists 0.446 0.522 1.0 1.0 0.888 Simulated: synthetic vectors, eight synthetic customers, recall@10
The test you ran on your biggest customer passes. Your smallest customer gets almost nothing.

Recall at 10 is 0.052. We asked for ten and got about half of one result. The obvious fix is to fetch more: fetch 100, and recall only climbs to 0.14. For the biggest customer, the same two settings give 0.522 and 1.0. So a test on your biggest customer passes while your smallest one is starved.

Filter first, so the search only looks at that customer's vectors, and exact search gives a recall of 1 for both. But that exact search still scored every vector: we fixed the result, not the work. With IVF and four lists searched after a filter, the biggest customer gets 0.888 and the smallest gets 0.446, only 7 results out of 10, because those four lists don't hold enough of its vectors.

A graph has its own version of this: if most neighbours belong to other customers, the hops run out of matches. That's reasoning; no graph was built here. So small customers often get their own partition, and you report recall per customer, especially the smallest, before trusting an average.

The follow-ups

  • Why not filter after, with a bigger fetch? Fetching 100 gave the smallest customer only 0.14, and the fetch keeps growing as the customer shrinks.
  • HNSW or IVF-PQ? It depends whether memory is the wall. If it is, IVF-PQ, and rerank to win back recall.
  • How do filters interact with the graph? The hops can land mostly on other customers, so use a filter-aware search or a separate partition.
LevelWhat it sounds like
Weak"HNSW, because it's fast."
OkayCompares the indexes with a memory estimate, and states its assumptions.
StrongStarts from the constraint, handles filters and small customers, and keeps measured numbers apart from estimates.

Recap

IdeaRemember
Trade-offRecall, latency, memory; an index skips doors on purpose
Memoryvectors x dims x 4 bytes; let the tightest constraint choose
The dial0.55, 0.892, 0.994 recall for 1, 4, 16 lists (simulated)
FiltersFilter after starves the smallest customer (0.052); filter first, measure per customer

Try it yourself

Take a search system you know. Estimate its vectors and dimensions, work out flat memory, and name the one constraint that decides its index.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 27 of 66

Previous
Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
Next post
Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"

Related course on Udemy

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)

Related posts

What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break

A customer types "I cannot log in" and keyword search finds nothing, although a password-reset article exists. Turn meaning into numbers by hand, find the nearest point with math.dist, build a three-topic toy embedder that finds the right article at 1.00, and watch it score 0.00 on "I can't get into my account".

The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer

Ingest, chunk, embed, store, retrieve, rerank and generate, in one Python file. Follow one question through a 26-chunk employee handbook to an answer that cites its source.

Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors

Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.

Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning

A smart model has never read your company's files, and they change every month. Three ways to give it the facts: paste everything, fine-tune, or retrieve only the right pieces. Follow a refund-policy question through all three and see why RAG wins when documents change.

On this page

  • Three things to trade
  • Knocking on every door
  • Flat, HNSW and IVF-PQ
  • The memory estimate
  • The dial
  • Ask for ten, get almost nothing
  • The follow-ups
  • Recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.