Skip to content

    AI Architect Case Files

    Case: Multi-Tenant Retrieval Isolation

    A B2B SaaS assistant filtered tenants in application code after search, and a red team found a leak. Moving the filter below the app fixed it.

    By Published 7 min read

    • ai-architect
    • case-file
    • industry-saas-b2b
    • pattern-access-control-retrieval
    • failure-data-leak
    • kind-composite
    Share

    Composite scenario, not a real company. Assembled from common industry patterns; every number is illustrative and its assumptions are listed at the end.

    This case belongs to Data and Retrieval Architecture for AI Systems.

    Context

    • A B2B expense-management product has 600 customer companies (tenants). Each uploads its own travel policy, approval rules and past finance tickets.
    • An in-product assistant answers employees' questions, such as "What is our hotel limit in Berlin?", from that tenant's own documents.
    • All tenants share one vector index of 12 million chunks.
    • Within a tenant, some documents, such as executive travel rules, are restricted to named groups.
    Tenant size Tenants Chunks each Chunks in total Share of index
    Large 20 about 400,000 8 million 67%
    Small 580 about 6,900 4 million 33%

    Problem statement

    The first version searched the whole index and then dropped rows that did not belong to the caller's tenant, in application code.

    Finding Value
    Red-team attempts (5 synthetic tenants, 20 ordered pairs, 6 entry points) 120
    Attempts that returned another tenant's snippet 4 (3.3%)
    Small tenants Often got "I don't know" for questions their documents answered
    Goal 0 leaks in 120 attempts on every release, and an answer for small tenants whenever their own data contains one

    Constraints

    • Fixed: no tenant may see another tenant's data, including a snippet, a citation title or a cached answer.
    • Fixed: group restrictions inside a tenant must hold.
    • Fixed: tenants have contractual rights over where their data sits; a few may demand a dedicated index.
    • Negotiable: the partitioning scheme and the cost of one extra index per large tenant.
    • Limit: the platform team can operate a handful of index types, not 600 separate stacks.

    Why the traditional approach fell short

    Approach Why it fell short
    Keyword search per tenant Safe, because every query runs in a tenant-scoped database session, but it cannot answer a paraphrased policy question
    Shared index with an application filter Simplest way to add semantic search, but isolation depends on every code path remembering to filter. Two paths did not: a "related questions" endpoint and a response cache keyed by question text only

    Isolation that depends on developer discipline fails at the first new feature.

    Options considered

    Option Why accepted or rejected
    A. Keep keyword search, no AI: already tenant-scoped, no new risk Kept as the fallback and for tenants who opt out of the assistant; does not handle paraphrases
    B. Shared index, filter in the application after search (the first version) Rejected: leaks through unfiltered paths and loses recall
    C. Filter enforced below the application: the Retriever owns the index credentials, builds the tenant filter from the signed token, and large tenants get partitions Accepted. A separate stack per tenant (a silo) is stronger still and stays available for tenants whose contract demands it

    Solution architecture

    Figure 1. Where the tenant boundary is enforced

    Tenant isolation in the retrieval pathClient app to API gateway; API gateway to Orchestrator; Orchestrator to Retriever; Retriever to Policy engine; Retriever to Vector index (tenant scope); Retriever to Vector index (tenant scope); Orchestrator to Model gateway; Model gateway to LLM providerTENANT BOUNDARY ENFORCED HEREClient appClient appAPI gateway: verifies tokenAPI gatewayverifies tokenOrchestrator: tenant from claimsOrchestratortenant fromclaimsModel gatewayModel gatewayLLM providerLLM providerPolicy engine: user groupsPolicy engineuser groupsRetriever: builds tenant filterRetrieverbuilds tenantfilterVector index: large-tenant partitionVector indexlarge-tenantpartitionVector index: shared partitionVector indexshared partitiontenant scopetenant scope

    How to read this: the request carries no tenant field the caller can edit, and the only route to the index passes through the Retriever.

    Figure 2. One question with the defence-in-depth check

    sequenceDiagram accTitle: Runtime path for a tenant-scoped question accDescr: The gateway verifies the token and the orchestrator passes the tenant to the retriever. The retriever gets the user's groups from the policy engine, searches with tenant and group filters in the vector index, and checks that every returned row belongs to the tenant. A row from another tenant is dropped and raises an alert. autonumber participant C as Client app participant G as API gateway participant O as Orchestrator participant R as Retriever participant P as Policy engine participant V as Vector index participant M as Model gateway C->>G: Question and session token G->>O: Question and verified tenant claim O->>R: Query with tenant scope R->>P: Groups for this user P-->>R: Group list R->>V: Search where tenant matches and group is allowed V-->>R: Top chunks alt Every row has the caller's tenant R-->>O: Passages O->>M: Answer from passages M-->>O: Answer O-->>C: Answer with citations else A row has another tenant Note over R: Drop the row, alert security, log the path R-->>O: Empty result O-->>C: No answer found end

    How to read this: the filter is applied inside the search, and the check after it is a second lock that should never fire.

    How AI solved it, step by step

    Step through one question from tenant A, then switch to "Without the fix".

    One tenant-scoped question (interactive when JavaScript is on)

    As designed

    1. Verify the token. An employee of tenant A asks about hotel limits. The gateway verifies the session token and takes the tenant id and user id from its signed claims.
    2. Forward the scope. The Orchestrator forwards the question with that tenant scope. The request body has no tenant field to trust.
    3. Build the filter. The Retriever asks the Policy engine for the user's groups, then builds the filter: tenant equals A, and the chunk's group is public to the tenant or in the user's groups.
    4. Route by tenant. A large tenant has its own partition. A small tenant's rows sit in the shared partition, where the filter selects about 6,900 rows and an exact search over them is cheap.
    5. Check every row. The Retriever checks that every returned row is tagged with tenant A. Any foreign row is dropped, the result is empty and security is alerted.
    6. Answer. The Model gateway drafts an answer from the passages, and the answer cites the tenant's own documents.
    7. Cache and trace. The response cache key includes the tenant id, and the Trace store records tenant, user, filter and the ids returned.

    Without the fix

    1. Search the whole index. The first version searches all 12 million chunks, whoever is asking.
    2. Drop rows afterwards. Application code removes rows that do not belong to the caller's tenant. Every code path must remember to do this.
    3. Two paths forget. A related-questions endpoint skips the filter, and a response cache keyed by question text only can serve one tenant's answer to another.
    4. Red-team result. 4 of 120 cross-tenant attempts return another tenant's snippet, and small tenants often get no answer.

    Under the hood

    The key step is where the filter runs. Pre-filtering restricts the candidates before ranking, so only the tenant's rows compete. Post-filtering ranks everything and then removes rows, which loses recall as well as safety.

    The pgvector README documents this for approximate indexes: "With approximate indexes, filtering is applied after the index is scanned", and, as its example, "If a condition matches 10% of rows, with HNSW and the default hnsw.ef_search of 40, only 4 rows will match on average." Its listed remedies are iterative index scans, partial indexes for a few distinct values, and partitioning for many. The same arithmetic with an illustrative candidate list of 40:

    Tenant Rows Share of 12 million Expected own rows in 40 candidates
    Large 400,000 3.3% 40 x 0.033 = 1.3
    Typical small 6,897 0.0575% 40 x 0.000575 = 0.023

    This assumes the tenant is uncorrelated with similarity, which is roughly true for generic questions such as "expense limits" that every tenant's documents match.

    Hence the tiering. Large tenants get partitions. Small tenants' scope is small enough for an exact scan: 6,897 vectors x 1,024 dimensions is 7,062,528 multiply-adds per query, so no approximate index is needed for them. Details are in Under the hood: Access control in retrieval.

    What went wrong / failure modes

    Failure Mitigation
    A new endpoint skips the filter Application code has no index credentials; only the Retriever does, and it requires a tenant scope argument to run any query
    Cache without the tenant in the key: a cached answer for tenant A is served to B Tenant id is part of every cache key, and cross-tenant tests cover the cache
    Tenant taken from the request: a caller edits a field The tenant comes only from verified token claims
    Group restriction ignored: a user sees a restricted document of their own tenant The group filter is part of the same pre-filter and is tested like the tenant filter
    Partition mis-routing: a tenant is moved and its old rows remain A migration step deletes and verifies, and the post-search check would flag a foreign row

    Results

    These are illustrative targets, not measurements.

    Measure Baseline Target
    Leaks in 120 red-team attempts 4 (3.3%) 0 on every release; any non-zero result blocks the release
    Small-tenant recall 0.023 expected own rows in a 40-row candidate list A search over all of the tenant's rows
    Cost none One partition per large tenant: 20 extra indexes to operate

    Tradeoffs and when NOT to use this approach

    • Partitions cost operations effort. With 20 tenants, a shared index with a strict pre-filter is probably enough.
    • An exact scan stops being cheap as a tenant grows; move it to its own partition when it passes an agreed size.
    • A shared index leaves no physical boundary. Where the contract or the regulator demands one, use a silo per tenant and accept the cost.
    • Do not rely on the post-search check as the control. It is a tripwire.

    Design rules extracted

    1. Enforce tenant and group filters below the application, in the one service that holds the index credentials.
    2. Take the tenant from verified claims, never from the request body.
    3. Filter before ranking; post-filtering both leaks and loses recall.
    4. Include the tenant in every cache key.
    5. Test isolation adversarially: every tenant pair, every entry point, zero leaks as a release gate.

    Assumptions

    All numbers are illustrative.

    • 600 tenants: 20 large at 400,000 chunks (20 x 400,000 = 8,000,000) and 580 small sharing 4,000,000 chunks (4,000,000 / 580 = about 6,897 each). Total 12,000,000.
    • Shares: 400,000 / 12,000,000 = 3.33%; 6,897 / 12,000,000 = 0.0575%. Expected rows: 40 x 0.0333 = 1.33; 40 x 0.000575 = 0.023.
    • The candidate list of 40 follows the default in the pgvector README example (https://github.com/pgvector/pgvector, read 2026-10-21); the post-filter arithmetic is this page's own application of that example, not a measurement. It assumes tenant is uncorrelated with similarity.
    • Embeddings have 1,024 dimensions: 6,897 x 1,024 = 7,062,528 multiply-adds.
    • Red team: 5 tenants give 5 x 4 = 20 ordered pairs, times 6 entry points = 120 attempts; 4 / 120 = 3.3%.
    • The product, the tenants and the red-team result are invented.

    Last verified: 2026-10-22

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments