One missing WHERE clause can leak a client’s data through RAG
Tenant boundaries belong in the database, vector store, encryption keys and configuration from the first design, well before the final sprint.
In brief
- A data leak between tenants can be an incident a business never recovers from, so isolation has to sit in the infrastructure as well as in application code.
- RAG systems have three models: silo isolates most strongly and costs the most, pool shares everything, and bridge falls between the two.
- Four layers need work: RLS in Postgres, one namespace per tenant in the vector store, per-tenant KMS encryption context, and one configuration record per tenant, looked up from a single source.
A user at customer A asks an internal document assistant about refund policy, and the answer quotes a whole passage from customer B’s contract. In this hypothetical Friday demo, nobody attacked the system. One query was missing its tenant_id condition.
FDEs who build AI systems will run into this sooner or later. When a platform serves many customers at once, each has its own documents, encryption keys and configuration.
AWS’s whitepaper on tenant isolation strategies defines the requirement concisely: even when tenants run in the same environment, one tenant’s resources must not be accessible to another. According to AWS, crossing that boundary even once, in any form, can be an event a SaaS business does not recover from.
Tenant isolation therefore has to be decided in the initial design. This guide covers the four layers to lock down, which are relational data, vectors, encryption keys and configuration, with a working example that ties them together.
Silo, bridge or pool: which model to choose?
AWS says plainly that no single strategy fits every case. The approach depends on the domain, compliance requirements, deployment model and the services you choose. For RAG on Amazon Bedrock Knowledge Bases, AWS describes three models, ordered by degree of isolation in the table below.
| Silo | Bridge | Pool | |
|---|---|---|---|
| Dedicated to each tenant | Knowledge base, S3 bucket, OpenSearch Serverless collection | Knowledge base only | Nothing; the entire architecture is shared |
| Per-tenant KMS key | Possible, because each tenant has its own bucket | No end-to-end encryption per tenant | One shared key |
| Filtering at query time | Already separated at the infrastructure level | By knowledge base | Relies on a tenant metadata field |
| Best for | Customers with the strictest isolation needs who accept the highest cost | Cases that need a balance | A very large number of small tenants |
Take a platform whose customers are one bank and a few dozen small retailers. The bank will almost certainly demand its own encryption key, which only the silo model can provide.
Putting the small shops in a pool makes sense. One platform can run both models, provided each tenant is explicitly assigned to an isolation tier.
Layer one: let PostgreSQL do the blocking
When relational data shares a single database, AWS guidance says row-level security (RLS) is required to maintain isolation between tenants.
RLS moves enforcement from hundreds of queries in application code to one place, the database. AWS recommends having the application set a tenant context variable at runtime instead of creating a separate database user for each tenant.
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
ALTER TABLE documents FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON documents
USING (tenant_id = current_setting('app.current_tenant')::uuid);
On the application side, every query must go through a single function:
def query_as_tenant(conn, tenant_id, sql, params):
with conn.transaction():
conn.execute(
"SELECT set_config('app.current_tenant', %s, true)",
(str(tenant_id),),
)
return conn.execute(sql, params).fetchall()
The true argument limits the value to the current transaction. If it were set at session level in a connection pool, the next request could pick up the connection with the previous request’s tenant still in place. That kind of leak is very hard to catch in testing.
Why the extra FORCE line? PostgreSQL’s documentation says superusers and roles with the BYPASSRLS attribute always bypass RLS. Table owners bypass it too, unless the table has FORCE ROW LEVEL SECURITY enabled.
Conversely, if a table has RLS enabled but no policy yet, PostgreSQL denies everything by default: no rows are visible and none can be modified. When this configuration is incomplete, the system returns nothing rather than the wrong data.
Layer two: one namespace per tenant
In a vector store, the most common mistake is to attach tenant_id as metadata and filter on it at query time. Pinecone’s documentation recommends one namespace per tenant. Each namespace is stored separately, so data is physically isolated between tenants.
With metadata filtering alone, Pinecone notes, a query still scans the entire namespace whatever the filter. The approach is both weaker and more expensive.
This may seem to contradict the table above, where Bedrock’s pool model relies on a tenant metadata field. The two are different choices: a pool on Bedrock Knowledge Bases shares the whole architecture, so the metadata filter is the only thing left to separate tenants.
Pinecone adds the option of namespaces. If your vector store has such a mechanism, keep the pool for everything else, such as the shared pipeline and KMS key, but give each small tenant its own namespace instead of relying on the filter alone.
results = index.query(
vector=embedding,
top_k=5,
namespace=tenant_cfg["vector_namespace"],
)
The detail that matters is that namespace never comes from user input. It must come from the tenant configuration, which is looked up from the authenticated session. If the namespace follows a URL parameter, the physical isolation underneath is worthless.
Layer three: bind the tenant to the encryption key
Even when tenants have to share a KMS key, encryption context lets you extend the tenant boundary into the cryptographic layer. It consists of non-secret key-value pairs that AWS KMS cryptographically binds to the ciphertext.
Decryption requires the same encryption context. It can also serve as a condition in key policies and grants to restrict permissions by tenant.
dk = kms.generate_data_key(
KeyId=tenant_cfg["kms_key"],
KeySpec="AES_256",
EncryptionContext={"tenant_id": tenant_cfg["tenant_id"]},
)
If tenant B’s code fetches tenant A’s blob and calls decrypt with B’s tenant_id as context, KMS will refuse. Encryption context is also recorded in CloudTrail, giving you a ready-made log of key usage per tenant for the customer’s audit team.
Because it is logged, however, AWS says not to put sensitive information in it. Use a meaningless UUID, and keep customer names and tax identification numbers out.
Layer four: configuration is where it all converges
The first three layers hold only if a single source answers the question “what does this tenant use?” Keep one configuration record per tenant. Every request entering the system must look it up first, and everything downstream reads from it. For the bank and shops above, two records might look like this:
- tenant_id: 8f1c2e4a-5b7d-4c21-9a3e-0d6f7b2c1a90
isolation_tier: silo
vector_namespace: ns-8f1c2e4a
kms_key: alias/tenant-8f1c2e4a
model: <customer model>
system_prompt: prompts/8f1c2e4a.md
limits: { requests_per_minute: 60 }
- tenant_id: 3a9d7c10-2e4f-4b88-b1c5-7e0a9f6d2b34
isolation_tier: pool
vector_namespace: ns-3a9d7c10
kms_key: alias/pool-shared
model: <default model>
system_prompt: prompts/default.md
limits: { requests_per_minute: 20 }
Both records use a UUID as the identifier and contain no customer name, so the value can go straight into the encryption context. The pool tenant shares a key, as the pool model prescribes, but still has its own namespace, as in layer two.
When the bank’s security team asks where its data lives and which key encrypts it, you open its record and point to each line instead of digging through code.
The configuration record also feeds the isolation test suite. The test below signs in as tenant A, then deliberately tries to read, search and decrypt B’s data:
def test_tenant_a_cannot_reach_tenant_b(conn, index, kms, b_doc_ids, b_blob):
a, b = load_tenant(TENANT_A), load_tenant(TENANT_B)
# Read: RLS must return 0 rows, even when asking for B's tenant_id directly
rows = query_as_tenant(conn, a["tenant_id"],
"SELECT id FROM documents WHERE tenant_id = %s", (b["tenant_id"],))
assert rows == []
# Search: A's namespace must not contain any of B's documents
hits = index.query(vector=PROBE_VECTOR, top_k=50,
namespace=a["vector_namespace"])
assert not {m.id for m in hits.matches} & set(b_doc_ids)
# Decrypt: KMS must reject B's blob with A's context
with pytest.raises(kms.exceptions.InvalidCiphertextException):
kms.decrypt(CiphertextBlob=b_blob,
EncryptionContext={"tenant_id": a["tenant_id"]})
Run this test in CI under the same role the application uses in production. Under the owner role, the read check may pass without showing that RLS is ever enforced for the application.
Mistakes that defeat isolation
The most common mistake is letting the application connect as the role that owns the tables, or as one with BYPASSRLS. The policy is still there but does not apply to that role, so the usual tests keep passing. Use separate roles for migrations and for the application.
The second is treating a metadata filter in the vector store as an isolation mechanism. The filter is just a condition in the query, and one piece of code that forgets to pass it is enough to let data out.
The third is choosing bridge for convenience, then discovering that the customer requires end-to-end encryption with its own key. Bridge cannot meet that requirement, so ask about encryption keys in the first discovery session.
The last is testing only the happy path. The isolation suite in layer four is valuable only when it deliberately does the wrong thing: it reads, searches and decrypts another tenant’s data, then asserts that all three attempts fail.
Turn this skill into an interview advantage
When reading job descriptions for FDE or solutions engineer roles, look for terms such as “multi-tenant,” “data isolation,” “customer-managed keys” and “compliance.” Where they appear, prepare a specific story about how you separated data, keys and configuration between customers.
On your résumé, go beyond “multi-tenancy experience.” Be specific: RLS with a tenant context variable set per transaction, one namespace per tenant in the vector store, per-tenant KMS encryption context, and automated tests that attempt cross-tenant reads. A line like that shows interviewers you know where systems break as well as the terminology.
The next time someone suggests separating tenants later, you will know what “later” can cost: one contract passage shown to the wrong customer in a demo is enough.
Was this article useful?
Thanks for the feedback!
6 sources
- SaaS Tenant Isolation Strategies: Isolating Resources in a Multi-Tenant Environment (AWS Whitepaper) · 2020-08-01
- Multi-tenant RAG with Amazon Bedrock Knowledge Bases · 2024-12-16
- Implement multitenancy (Pinecone docs)
- Row-level security recommendations - AWS Prescriptive Guidance
- PostgreSQL Documentation: Row Security Policies
- Encryption context - AWS Key Management Service Developer Guide