Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 27/ 160
02. RAG

Metadata Filtering

Pre/post filters on tenant, date, ACL, and document type to keep retrieval relevant and safe.

IntermediateACL Filters · Tenant Scope3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

Before looking for matching pieces of text, the system narrows to only the pieces the user is allowed and likely to need.

Think of it like…

A library where each reader's card only opens certain rooms: the librarian (retrieval) must check the card before fetching any book, since once a book is on the reader's desk (in the prompt), you can't un-show it.

Where you’ve seen it

A legal-research assistant serves 300 law firms with confidential documents. Each chunk stores firm_id, matter_id, doc_type, effective_date and acl_groups. The API derives firm_id and group memberships from the authenticated session (never from the request body or the LLM) and always applies firm_id = :firm AND acl_groups && :groups. A nightly test uploads a canary document for firm A and verifies that firm B's queries never retrieve it.

Words you’ll hear

Pre-filter
Restrict candidates first, then search among them; accurate but may be slower.
Post-filter
Search first, then remove non-matching results; can leave too few results.
ACL (access control list)
Per-document permissions, stored as metadata and enforced at query time.
Tenant scope
A mandatory filter isolating each customer's data in a shared index.

Visual diagram

Loading interactive diagram

Theory & deep dive

Pre-filter, post-filter and filtered ANN

Post-filtering is simplest: take the top-k by similarity, then drop rows that fail the filter. With selective filters (one tenant among 2,000) most of the top-k belong to others, so you may end up with 0 to 2 results from k = 10. Increasing k helps only partly. Pre-filtering selects matching rows first and searches within them: exact and correct, but if the engine can't use its ANN index on the subset, it falls back to scanning. Filtered ANN integrates the condition into the index traversal (supported in Qdrant, Weaviate, Elasticsearch, pgvector's iterative scans and others), keeping speed and returning the requested number of results.

Match the strategy to selectivity. Very selective filters (a single tenant with 5,000 chunks) are best served by partitioning or a separate index or namespace per tenant, or by a plain filter plus exact search on the small subset. Broad filters (document type) work fine with filtered ANN. Always evaluate recall and result counts with real filters, since an index that is 98 percent recall unfiltered can be far lower when filtered.

Why post-filter fails

Top-10 by similarity across all tenants contains 1 chunk from tenant 42. Post-filtering returns 1 result, though tenant 42 has 20 relevant chunks further down. Filtered ANN or a per-tenant partition returns 10.

Key takeaway: Prefer in-index or pre-filtering; handle very selective filters with partitions or namespaces.

Designing metadata and enforcing security

Decide the metadata schema at ingestion: tenant or org id, source system and document id, document type, language, created and updated dates, version or status (draft, published, superseded), sensitivity level and permission groups or user ids. Keep it small and typed, index the fields you filter on, and keep metadata in sync with the source of truth: when a document's permissions change, update its chunks' ACL fields promptly (or check permissions again at query time).

Security rules: derive the filter on the server from the authenticated identity; never let the client or the LLM supply tenant or ACL values; apply the filter to every retrieval path, including keyword search, rerankers' candidate sets, caches and "related documents" features; log which filters were applied; and test isolation continuously with canary documents and automated cross-tenant queries. For stronger guarantees use separate indexes or databases per tenant, or row-level security in PostgreSQL. Remember cached answers and embeddings of sensitive content are data too: scope caches by tenant and permissions.

A server-built filter (pseudo-code)

filter = {"firm_id": session.firm_id, "acl_groups": {"any": session.groups}, "status": "published"}; results = store.search(vector, filter=filter, top_k=50) where session comes from the verified token, not from the request body.

Key takeaway: Server-side, identity-derived, applied everywhere, and tested with canaries.

How it works, step by step

Step 1 of 4
Design

1. Define the metadata schema

List tenant, type, date, status and permission fields, and index those used for filtering.

firm_id · doc_type · effective_date · acl_groups
Key numbers at this step
Keep
small and typed

When to use it & trade-offs

What it is

Metadata filtering restricts retrieval to chunks whose attributes match conditions: tenant_id = 42, doc_type IN ('policy', 'faq'), updated_at >= 2026-01-01, allowed_groups ∩ user_groups ≠ ∅. Filters can be applied before the search (pre-filter), during it (filtered ANN) or after it (post-filter). They serve two purposes: relevance (only current, correct-type documents) and security (users must never see chunks they aren't authorised to read).

Why it matters: Without filters, a multi-tenant RAG system can answer one customer's question with another customer's data: a serious breach, and the LLM can't be trusted to hide what it was given. With badly implemented filters, retrieval returns too few results or silently ignores the filter. This is one of the highest-stakes details in production RAG and a frequent security-review topic.

When to reach for it

  • Multi-tenant SaaS RAG
  • Permission-aware enterprise search
  • Restricting to current, published document versions

When to avoid or be careful

  • Accepting tenant ids or ACLs from the client
  • Post-filtering a small top-k with selective filters
  • Forgetting the filter on secondary paths like caches

Ways to isolate and filter data

Filter fields in a shared index
Best for: Many tenants and flexible attributes

Strengths: Simple operations; efficient use of resources.

Watch out: A missed filter leaks; selective filters stress ANN.

Namespace or partition per tenant
Best for: Selective tenant scoping at scale

Strengths: Fast, small indexes; strong logical isolation.

Watch out: More objects to manage; small tenants waste overhead.

Separate index or database per tenant
Best for: Strict compliance and enterprise customers

Strengths: Hard isolation; per-tenant deletion and keys.

Watch out: Highest operational cost.

Interview signals & numbers to know

When this topic comes up

  • “How do we stop one customer seeing another's documents?”
  • “Filtered search returns too few results”
  • “Only show current policy versions”
  • ACL-aware retrieval
  • Tenant isolation

Benchmarks & rules of thumb

0 -
cross-tenant results allowed
pre / in / post -
three filtering strategies
server-side -
where filters must be built

Common mistakes & follow-ups

Common interview mistakes

  • Letting the LLM or request body pass tenant_id, which a crafted prompt can change.
  • Updating a document's permissions in the source but not its chunks, leaving old access in place.
  • Caching generated answers across tenants with a key that ignores permissions.

Likely interviewer follow-ups

  • How would you enforce document-level permissions in RAG?
  • Why is post-filtering a problem for selective filters?
  • How would you test for cross-tenant leakage?
Interview tip: Lead with "filters come from the authenticated session on the server". Interviewers listen for that sentence in any multi-tenant RAG design.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Metadata Filtering with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
HNSW Indexes
Next topic
BM25 Keyword Search