Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A retrieval feature using pgvector returns poor results after adding a metadata filter WHERE tenant_id = ? to an HNSW query with LIMIT 10. Often fewer than 10 rows come back. Explain and fix.

The HNSW index does not know about tenant_id: it finds the ef_search nearest candidates across all tenants first, and only then does PostgreSQL apply WHERE tenant_id = ?, so most candidates are thrown away and fewer than 10 rows survive. We fix it by letting the index look further, either a higher hnsw.ef_search or the iterative index scans added in pgvector 0.8, by giving large tenants their own partial index or partition, and by measuring recall against exact search on a sample. We should also confirm that the query uses the same embedding model and distance operator as the index.

Why this question is asked

Adding a tenant filter is the most natural change in the world: a multi-tenant product must never show one customer another customer's documents. So it is surprising when the feature that worked yesterday now returns three results, or none, for a query that obviously has good matches. Interviewers like this bug because it tests whether we understand that an approximate index is not a B-tree: it answers a different question from the one our SQL seems to ask. In this answer, we will recap how pgvector uses an HNSW index with ORDER BY and LIMIT, reproduce the problem, explain exactly where the rows go, and then walk through the fixes from cheapest to strongest, and how to prove each one works.

1A Quick Recap: How pgvector Runs an HNSW Query

In pgvector, a similarity query is written as ORDER BY embedding <=> query_vector LIMIT k, where <=> is cosine distance. When an HNSW index exists with the matching operator class, PostgreSQL uses an index scan that returns rows in approximate distance order. HNSW, a layered graph of nearest neighbours, explores a candidate list whose size is set by hnsw.ef_search, which is 40 by default.

The important detail is what the index scan can return. It produces at most ef_search candidates from the graph walk. Any other condition in the WHERE clause is applied afterwards, as a filter on those candidates. The index has no idea that some candidates belong to other tenants.

2Reproducing the Problem

Suppose the table holds 2 million chunks from 500 tenants, and tenant 42 owns about 1 percent of them.

Java
SET hnsw.ef_search = 40; -- the default
SELECT id, embedding <=> $1 AS distance
FROM documents
WHERE tenant_id = 42
ORDER BY embedding <=> $1
LIMIT 10;
-- 0 to 3 rows, often
EXPLAIN SELECT ...;
-- Limit
-- -> Index Scan using documents_embedding_idx on documents
-- Order By: (embedding <=> $1)
-- Filter: (tenant_id = 42)
-- Rows Removed by Filter: 38
Step throughWhy only 2 rows come back
QueryHNSW indexFilter
find nearest to query vector
walk graph, keep ef_search = 40 candidates
40 candidates from all tenants
keep tenant_id = 42
2 rows, LIMIT 10 not reached

5 messages in order. Play them, or step through them one at a time.

The filter runs after the approximate search, so it can only remove rows, never find more.

The plan tells the story. The index scan hands over its 40 nearest candidates from the whole table, and the filter removes 38 of them because they belong to other tenants. If tenant 42 owns 1 percent of the data, we expect only about 0.4 of the 40 candidates to be theirs on average. Even when the tenant's documents are relevant, they are rarely among the 40 globally nearest vectors, because other tenants have many similar documents too.

3Fix 1: Let the Index Look Further

The quickest fix is to make the index produce more candidates so that enough of them survive the filter. We can raise ef_search, and with pgvector 0.8 or later we can turn on iterative index scans, which keep walking the graph and fetching more candidates until the LIMIT is satisfied or a scan budget runs out.

SQL
-- Option A: a bigger candidate list for this query only
BEGIN;
SET LOCAL hnsw.ef_search = 400;
SELECT ... WHERE tenant_id = 42 ORDER BY embedding <=> $1 LIMIT 10; -- usually 10 rows
COMMIT;
-- Option B (pgvector 0.8+): keep scanning until 10 rows pass the filter
SET hnsw.iterative_scan = relaxed_order; -- or strict_order
SET hnsw.max_scan_tuples = 20000; -- stop after this many candidates
SELECT ... WHERE tenant_id = 42 ORDER BY embedding <=> $1 LIMIT 10; -- 10 rows

Notice that raising ef_search costs latency for every query, and it only helps in proportion: for a tenant with 1 percent of the data we would need roughly 1,000 candidates to expect 10 matches. Iterative scans are smarter because they do extra work only when the filter is rejecting rows. relaxed_order may return results slightly out of distance order, which we can fix by wrapping the query and sorting again; strict_order keeps exact order at some extra cost. Check your pgvector version, because these settings do not exist before 0.8.

4Fix 2: Give Large Tenants Their Own Index or Partition

For a tenant that is large or important, the strongest fix is an index that only contains that tenant's vectors. Then every candidate the graph returns already passes the filter.

SQL
-- A partial HNSW index for one large tenant
CREATE INDEX documents_t42_hnsw ON documents
USING hnsw (embedding vector_cosine_ops)
WHERE tenant_id = 42;
-- the planner uses it when the query says WHERE tenant_id = 42
-- Or list-partition by tenant, each partition with its own HNSW index
CREATE TABLE documents_p (id bigint, tenant_id bigint, embedding vector(1536))
PARTITION BY LIST (tenant_id);
CREATE TABLE documents_t42 PARTITION OF documents_p FOR VALUES IN (42);
CREATE TABLE documents_rest PARTITION OF documents_p DEFAULT;
-- Small tenants: a B-tree on tenant_id lets the planner do an exact search
CREATE INDEX ON documents (tenant_id);

For small tenants the opposite approach works: if a tenant has 5,000 chunks, an exact search over those rows, found through a B-tree on tenant_id, is fast and has perfect recall. The planner may choose this on its own when the filter is very selective, which is worth checking with EXPLAIN. For customers who need strong isolation, a separate table or schema per tenant gives each its own index and makes data deletion and access control simpler, at the cost of more objects to manage.

5Measuring Recall Instead of Guessing

Every one of these fixes is a trade-off between speed and quality, so we measure. Recall at 10 is the share of the true 10 nearest rows that the indexed query returns. The true answer comes from an exact search with index scans disabled.

SQL
-- ground truth for one sample query
BEGIN;
SET LOCAL enable_indexscan = off;
SELECT id FROM documents WHERE tenant_id = 42
ORDER BY embedding <=> $1 LIMIT 10; -- exact top 10
COMMIT;
-- compare with the indexed query; repeat for 200 sampled queries
-- recall@10 = |indexed ids INTERSECT exact ids| / 10
-- before: 0.18 with iterative scan: 0.96 with partial index: 0.99

We run this over a few hundred realistic queries per tenant size and pick settings that reach the recall target, often 0.95, within the latency budget. The numbers in the comment are only illustrative; what matters is that we tune against a measurement rather than raising ef_search until it feels right.

6Also Check the Model and the Operator

Poor results are not always the filter. If the query text is embedded with a different model, or a different version of the model, than the stored documents, the vectors live in different spaces and distances are meaningless. That often happens when someone upgrades the embedding model for new documents only. We store the model name and version with each row and check that the query uses the same one.

The distance operator must also match the index operator class. An index built with vector_cosine_ops serves <=>; a query that uses <-> for L2 distance cannot use it and falls back to an exact scan, which is slow rather than wrong. If the model expects normalised vectors with inner product and we use L2 on unnormalised ones, the ranking itself changes. So we confirm the model, the normalisation and the operator before tuning anything else.

7Follow-up questions

Why not just set ef_search very high for every query?

Because latency grows with the candidate list, and unfiltered queries do not need it. A query that examines 1,000 candidates is several times slower than one that examines 40. Iterative scans or per-tenant indexes give the extra effort only to the queries that need it.

Can I put tenant_id inside the HNSW index?

Not as a filter the graph understands. pgvector indexes a single vector column. Partial indexes and partitions are the way to restrict the graph to one tenant, and some dedicated vector databases offer filtered HNSW that applies metadata conditions during the graph walk.

Is it a security problem that other tenants' rows were candidates?

No, as long as the WHERE clause or row-level security is applied, other tenants' rows are never returned. The problem is quality, not leakage. Still, keeping tenant filtering in the database, ideally with row-level security, is better than filtering in application code after the query.

8Conclusion

In this answer, we saw that an HNSW index scan returns at most ef_search approximate neighbours from the whole table, and the tenant filter is applied afterwards, so a selective filter leaves fewer than LIMIT rows. We fixed it by letting the index look further with ef_search or pgvector 0.8 iterative scans, by giving large tenants partial indexes or partitions and letting small tenants use exact search, by measuring recall against exact results, and by checking that the model and distance operator match the index.

What to say in the interviewAbout 80 seconds aloud

Open with

The problem is the order of operations. With an HNSW index, pgvector's index scan walks the graph and returns about ef_search candidates, 40 by default, that are nearest to the query across the whole table.

Then, if they want more

The WHERE tenant_id filter is applied to those candidates afterwards. If the tenant owns one percent of the rows, only a handful of the forty belong to them, so the LIMIT 10 is never reached, and EXPLAIN shows it as Rows Removed by Filter.

To fix it, the cheapest option is to let the index look further: raise ef_search for these queries, or on pgvector 0.8 and later enable iterative index scans, which keep fetching candidates until enough pass the filter, with a cap on scanned tuples.

For large tenants I would create a partial HNSW index with WHERE tenant_id equals that tenant, or list-partition by tenant, so every candidate already matches. Small tenants can use a B-tree on tenant_id and an exact search, which has perfect recall. I would measure recall at 10 against exact search on a few hundred sample queries before and after.

And I would check that the query and documents use the same embedding model and that the operator matches the index's operator class.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Redis documentation, MongoDB manual
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A retrieval feature using pgvector returns poor results after adding a metadata filter...": https://scrivio-interview-library.netlify.app/databases/nosql-fundamentals/580626f860/