All insights

AI security and compliance

How do you enforce tenant isolation beyond database rows?

Row level security answers "whose row is this?" Real products also need "which parts of this row may you see?"

Co-founder and CTO, Datics AIUpdated 8 min read

Short answer

Tenant isolation beyond database rows means enforcing boundaries per field and per role, not only per tenant ID. The same customer record can be fully visible to one party and partly visible to another, so tenant isolation has to cover columns, caches, files, payments, background jobs and every API. Any later feature, including an AI agent for reporting or support, must respect those same boundaries, because it will read whatever your platform lets it read.

On this page
  1. 01Rows are only the first boundary
  2. 02Map the visibility rules before you write code
  3. 03Enforce tenant isolation at every layer
  4. 04Where AI adds new places for customer data to meet
  5. 05Row level security that fails closed
  6. 06Common isolation mistakes
  7. 07What we see in production
  8. Frequently asked questions

01Rows are only the first boundary

Most multi-tenant products start with a tenant column and a filter on every query. PostgreSQL row security policies make this stronger by enforcing the filter in the database itself, with a default deny when no policy matches. That is a good foundation. It is not the whole answer.

Real B2B platforms often have more than one kind of party looking at the same record. A wholesale company and its dealers, a franchisor and its locations, a platform and its resellers. In these products the question is rarely "may this tenant see this row?" It is "may this role, in this tenant, see this field of this row, for this purpose?"

AWS makes a related point in its SaaS architecture guidance: authentication and authorization are not isolation. A user can be signed in and authorized for a feature and still reach another tenant's data if isolation is not enforced separately, using tenant context on every access.

02Map the visibility rules before you write code

The most useful artifact is a visibility map: for each important entity, which roles see which fields. Draw it before building, and keep it in the repository.

Visibility map showing which fields central admins, dealer admins and end customers can see for each entity
The visibility map also becomes the test plan.
DataOwning partyCentral company adminDealer adminDealer staffEnd customer
Customer profileDealerShipping details onlyFullFullOwn profile
Product catalogCentral companyFullVisibility, pricing and descriptions onlyReadPublished items
OrderDealer, then central for fulfillmentOrder and shippingFullFullOwn orders
PaymentDealer's own accountNo access to fundsSettings and refundsPer roleOwn payments
Design filesCustomer and dealerFor productionFullFullOwn files

A map like this exposes decisions early: who owns the customer, who can change price, who can refund. It also becomes the test plan.

03Enforce tenant isolation at every layer

Rows, fields and roles need enforcement in more places than the main database. The OWASP Multi Tenant Security Cheat Sheet is a good checklist. In practice we cover these layers:

Layers where tenant isolation is enforced: request context, database, API, caches and files, jobs, and logs
Test cross-tenant denial for every role on every release.
  1. 01

    Request context.

    Set the tenant on the server for every request, and treat any tenant ID sent by the client as a selector to verify, not a fact.

  2. 02

    Database.

    Use row security for tenant scoping, and column level grants or separate views for field level rules.

  3. 03

    API responses.

    Shape responses per role, so a field the role may not see is never serialized, not just hidden in the UI.

  4. 04

    Caches and search indexes.

    Include the tenant in every cache key and index filter.

  5. 05

    Files.

    Partition storage by tenant and authorize before issuing signed URLs.

  6. 06

    Payments.

    Where each tenant uses its own payment account, keep the platform out of the money flow and store no card data.

  7. 07

    Background jobs.

    Carry verified tenant context into queued messages and check it again in the worker.

  8. 08

    Logs and exports.

    Include tenant context in audit events and restrict who can read them.

Test cross-tenant denial explicitly. For each role, write tests that try to read another tenant's data and another role's fields, and run them on every release.

04Where AI adds new places for customer data to meet

AI features are a new path to the same data, and they add places where two customers' data can meet that a classic product never had. A reporting agent, a support assistant or a search tool reads through whatever interface you give it. If that interface was written for internal admins, the AI sees what admins see.

In a multi-tenant AI feature, five places have to hold:

PlaceHow it leaksHow it holds
IdentityThe tenant ID comes from the browser, the chat or the modelThe tenant comes only from the verified login token; any other value is ignored
Search and retrievalResults are ranked across all tenants and filtered afterwards, so the model has already read another customer's textFilter by tenant and role first, then rank. Check access at query time, not only when indexing.
Answer cachesThe cache key is the question alone, so two customers who ask the same thing share one answerThe key holds tenant, role and question
Chat history and tracesFull prompts from every customer sit in one trace store, readable by the whole teamEvery record carries the tenant, access is limited to named roles, and traces are deleted on a schedule
ToolsThe agent calls internal endpoints with its own broad rightsThe agent acts as the signed-in user, and permissions are checked again on every call

The cache is the one teams miss most. It looks like a performance detail, so it gets built after the security review. Then two customers ask the same question, and the second one gets the first one's answer.

A prompt is not a boundary

"Answer only for tenant 42" in a system prompt is a request, and a model can be talked out of it. The tenant has to be applied in code, in every query, from the token. The model should never choose it. If the tenant can come from anywhere but the token, every layer below can be pointed at the wrong customer.

One shared index, or one per tenant?

Most products can share one search index, filtered by tenant before ranking. Tenants that need stronger separation by contract can get their own index. Either way, deleting a source document must also remove it from the index, or a deleted contract can keep answering questions. We go deeper on the retrieval side in RAG security.

Before adding AI to a multi-tenant product, add the AI to your cross-tenant denial tests: from test account A, ask for account B's records by name, by ID and through search, and treat any answer as a release blocker. We cover the agent side in how to add AI agents to an existing SaaS product.

05Row level security that fails closed

The database is the last line, so set it up to fail closed: a bug should look empty, not leaked. This is the PostgreSQL setup we use as a reference, and we tested it on PostgreSQL 17:

  1. 01

    Turn row security on, and force it.

    On every tenant table, use FORCE ROW LEVEL SECURITY so even the table owner is bound by the policy.

  2. 02

    One policy per table.

    A row shows only when its tenant matches the tenant set for this request.

  3. 03

    A separate database role for the AI.

    Not a superuser, not the table owner, and without the right to bypass row security.

  4. 04

    Set the tenant per request.

    From the token, inside a transaction, so it never carries over to the next request on the same connection.

  5. 05

    Fail closed.

    No tenant set means no rows.

This does not replace the checks in the application. It catches the day one of them is missing.

06Common isolation mistakes

When we review multi-tenant products, these are the gaps we find most often:

  • Field rules enforced only in the UI, while the API returns the full record.
  • Admin endpoints that skip tenant filters because they were written for internal staff.
  • Reports and exports built on direct database queries that bypass the application rules.
  • Shared cache keys for data that differs by tenant.
  • Background jobs that run with a superuser connection, which row security does not constrain.
  • Impersonation or support tools without an audit trail.

Each one is easy to miss because the product looks correct from the screens. The fix is to test from the outside: call the API as each role in each tenant and check exactly which fields come back. Repeat those tests whenever a new endpoint, report or integration is added, and treat a failed test as a release blocker.

It also helps to name an owner for the visibility map. When the business adds a new party, such as a reseller or a partner, the map is updated first, and the code follows.

07What we see in production

For a premium custom print company with a wholesale dealer network, we replaced the dealer side of a 15 year old legacy system with a multi-tenant platform where each dealer runs a branded storefront with its own pricing, promotions and payment account, while every order flows back to the company for production and shipping.

Isolation had to work per field and per role, not just per tenant. The same customer is fully visible to the dealer and only partly visible to the central company: central admins see shipping details, not the full profile. The catalog stays central, and dealers control only visibility, pricing and descriptions. Dealers collect payment in their own accounts, so the platform holds no funds and stores no card data, which keeps it out of card data scope.

We added tenant filtering across backend and frontend, role based access for super admin, dealer admin, dealer staff and customer, and recommended snapshotting variant data into each order so later price changes never alter past orders. The platform runs on the client's own AWS account.

There was no AI in the delivered scope, but the scope document asked for an architecture ready for future agent based features such as intelligent reporting and AI customer support. Any such agent will have to respect the same field and role boundaries, which is far easier because they already exist in one place.

In our AI work the same rule shows up in different forms. In a cited knowledge workspace we built, retrieval fails closed when access cannot be confirmed (case study). In MIRA, an intake platform for clinics, each clinic is fully separate, and only the super admin sees all clinics (case study). In a sales assistant for dealerships, each dealer's website pages, FAQs and documents are indexed per tenant, so one dealer's content never answers for another (case study). Of the 52 AI projects in our own analysis, 12 served many customers from one product, so each customer's data had to stay apart.

To check your own product against the five places, use our free field guide, Can customer A ever see customer B's data in your AI?

Frequently asked questions

Is PostgreSQL row level security enough for tenant isolation?

It is a good foundation, not the whole answer. Row security enforces the tenant filter in the database itself, with a default deny when no policy matches. It does not cover field rules, caches, files, payments or background jobs, and jobs that run with a superuser connection are not constrained by it.

How do we test tenant isolation?

Test from the outside. For each role, write tests that try to read another tenant's data and another role's fields. Call the API as each role in each tenant and check exactly which fields come back. Run those tests on every release, and treat a failed test as a release blocker.

What changes when we add an AI agent to a multi-tenant product?

The agent is a new path to the same data, and it will read through whatever interface you give it. Give it its own access path that applies the same tenant, role and field rules as the user it acts for. Scope retrieval to the current tenant, and add the agent to your cross-tenant denial tests.

Can a system prompt keep tenants apart?

No. A prompt is a request, and a model can be talked out of it. Apply the tenant in code, from the verified login token, in every query and every tool call, so the model never chooses which customer's data it reads.

Should each tenant get its own vector index?

Not usually. One shared index, filtered by tenant and role before ranking, works for most products. Give a tenant its own index when its contract requires stronger separation. In both cases, deleting a source must also clear it from the index.

How Datics helps

Datics specializes in Brownfield AI: production AI inside software people already rely on. Already built AI? The AI Scorecard tests it on 50 of your own cases in two weeks, for $5,000, and ranks what to fix first. Once it is live, AI Care keeps it accurate for $1,500 a month per capability.

›References (4)
  1. AWS: SaaS Architecture Fundamentals, Tenant isolation
  2. PostgreSQL: Row Security Policies
  3. OWASP: Multi Tenant Security Cheat Sheet
  4. AWS Prescriptive Guidance: multi-tenant agentic AI

Related work

Case studies from our projects on the same subject.

NenoBrief by Neno Technologies

GovTech · AI gateway for a live DMS

Archive officers get cited answers inside their live document system, files never copied

Archive records could not reach an outside AI. Now the client's live document system calls our self-hosted gateway for cited answers.

Brownfield AIInside a live productCited answers
Read case study

MIRA

Healthcare · Multi-clinic intake SaaS

Clinics sign up, pay per provider and run their own AI patient intake

The AI intake worked in three practices but was hard coded. Now any clinic signs up, pays per provider and runs it, and names never reach the model.

AI-native productMulti-tenantPermission-aware
Read case study

Coast Technology

Automotive · AI sales assistant for dealers

RV shoppers get units from live stock, with towing fit computed, not guessed

Dealer sites offered static forms and filters. Now shoppers ask in plain words and get real units from the hourly feed, with the reason each one fits.

AI-native productAgentic workflowsProduction AI
Read case study

More on AI security and compliance

AI security and compliance

AI security for SaaS: protect data and pass security reviews

A practical map of AI security for established SaaS: threats, data governance, permissions, audit trails and how to answer enterprise security reviews.

Umair MajeedRead

AI security and compliance

How does RAG security scope retrieval to user permissions?

RAG security in multi-tenant SaaS starts with whose documents a question may search. Learn how to filter by tenant and permission before ranking.

Rana Umar MajeedRead

AI security and compliance

Soft delete vs hard delete in SaaS: AI, GDPR and audits

Soft delete vs hard delete: a clear comparison, SQL patterns, GDPR erasure, and how deletion reaches embeddings, search indexes and AI logs.

Engineering TeamRead

AI security and compliance

What enterprise AI security questions do buyers ask?

Enterprise AI security reviews ask where data and models run, who reaches production, what the AI may do alone and how it is logged. Here is how to prepare.

Umair MajeedRead

AI security and compliance

How does AI data security work with production data?

A practical AI data security pattern for SaaS: keep the core as the system of record, run AI in its own environment, and connect it through APIs and approval.

Rana Umar MajeedRead

AI security and compliance

LLM security: why treat model output as untrusted input?

A core LLM security rule: treat every model response like input from an unknown user. Parse it, validate it against business rules, then let it through.

Rana Umar MajeedRead

Your customers already expect AI from your product.

Let us make it real inside the product you run today.