A reference architecture for multi-tenant AI SaaS: Postgres RLS, tenant-scoped retrieval, usage metering, AI pricing, and model cost controls.

tenant_id column and Postgres row-level security is the right default. Schema and database per tenant solve specific enterprise or compliance problems.set_config(..., true) so it survives connection pooling.identifier for at least 24 hours) from an outbox.Classic SaaS architecture grew up around a comfortable fact. Once you paid for servers, the marginal cost of one more page view, one more API call, or one more report was close to zero. Pricing could be per seat, gross margins sat comfortably high, and a heavy user was mostly a happy user.
AI features change that. Every model call is priced in tokens, and the bill scales with what users do, not how many there are. One power user can cost more than their subscription, and a runaway background loop can burn a month of margin overnight.
AI also makes multi-tenancy harder. Tenant data flows through embedding pipelines, vector indexes, caches, conversation memory, tool calls, and context windows, and each is a place where one customer's data can end up in another customer's answer.
This article is a reference architecture for multi-tenant AI SaaS in 2026, focused on the decisions that are expensive to change later: isolation, tenant context, metering, pricing, and model cost control. The code is TypeScript and SQL. Provider prices and APIs were checked against vendor documentation in October 2026; they change often, so check them again before you commit to a pricing model.
If you have a working prototype and are planning the path to production, our article on moving from AI proof of concept to a scalable product covers the process side. This article is about the architecture underneath.
Before going deep on any one component, it helps to see the whole system. A multi-tenant AI SaaS has the same bones as any SaaS application, plus three additions: an AI gateway that every model call passes through, a metering pipeline that turns work into billable usage, and a retrieval layer that has to respect tenant boundaries as strictly as the main database does.

The control plane holds everything about tenants rather than tenant data: organizations, users, roles, SSO configuration, API keys, plans, budgets, and kill switches. It answers "who is this, which tenant are they acting for, and what may they do?" The data plane holds tenant data and does tenant work: the application database, object storage, vector indexes, job queues, and the AI gateway. Every data plane component receives a tenant context from the control plane and enforces it. Keeping the planes separate means an enterprise customer's dedicated database is a data plane move, and a second model provider is a gateway change.
The single most important architectural decision in this article is that no application code calls a model provider directly. Every model call goes through one internal service or library, the AI gateway, which:
Without a gateway, each concern is reimplemented, inconsistently, in every feature. With one, cost control is a configuration change instead of a code audit. It can start as a library inside your monolith.
There are three classic ways to isolate tenant data in a relational database, plus a hybrid that most mature products end up with.

The practical recommendation is to start with shared schema plus RLS, and build tenant-aware connection routing from day one even if every tenant routes to the same database. That routing function is the seam that lets you move one tenant to a dedicated database later without touching application code. Note that your database's tenancy model does not automatically apply to your vector store, caches, or object storage. Part 3 covers those.
Postgres row-level security (RLS) attaches policies to a table so every query, including ones a developer forgets to filter, sees only the rows the policy allows. When RLS is enabled and no policy grants access, Postgres applies default deny. Three rules make it hold up in practice:
FORCE ROW LEVEL SECURITY applies policies to the owner too, but the cleaner pattern is an owner role for migrations and a separate role for the app.BYPASSRLS. Both skip every policy, and managed Postgres services often hand out a default admin role with one or both.set_config('app.tenant_id', $1, true) is local to the transaction and disappears at commit or rollback.Here is a complete, working setup:
The tenant-first primary key keeps index lookups tenant-scoped. USING governs which rows are visible; WITH CHECK governs which rows can be written, so tenant A cannot insert a row labeled tenant B. And nullif(..., '') matters because a custom setting set earlier in a session reads back as an empty string, not NULL, after the transaction ends.
Prove the isolation with a test. This script runs as a superuser in a test database and switches to the application role:
In CI, this catalog query catches the most common regression, a new table nobody protected:
Referential integrity checks (unique constraints, foreign keys) bypass row security, so a constraint error can reveal that a value exists in another tenant. Keep unique constraints tenant-scoped (UNIQUE (tenant_id, email)). Views run with the owner's privileges unless created with security_invoker = true (Postgres 15 and later), and SECURITY DEFINER functions run as their owner. And RLS does nothing for data you copy into a search index, a cache, or a prompt.
If you need stronger separation later, a routing seam makes it manageable. Every data access goes through one function that picks the database for a tenant and sets the tenant for the transaction:
Dedicated databases keep the same schema, policies, and app.tenant_id setting, so there is one code path, one migration set, and one test suite. A dedicated database becomes an operational choice, not a different product.
RLS protects one database. An AI product moves tenant data through many more places: HTTP handlers, queues, workers, caches, embedding pipelines, vector indexes, and the model's context window. The tenant has to be an explicit, verified value at every hop, and every store has to be scoped by it.

Resolve the tenant once per request from a verified credential (session, signed token, or API key), never from a header the client controls, and carry it in request-scoped context. In Node.js, AsyncLocalStorage does this without threading a parameter through every function:
An authentication middleware verifies the credential, builds this context once, and calls runWithContext(context, () => next()). ctx() throws when there is no context, so code that touches tenant data outside one fails loudly instead of running as a default tenant.
Queues are where tenant context most often gets lost. Make tenantId a required field of every job envelope, and wrap every handler so it re-creates the context and transaction before doing work:
The lookupActivePlan check matters because jobs outlive requests: a tenant can be suspended or deleted between enqueue and execution.
Retrieval is where cross-tenant leaks are most likely and hardest to detect, because leaked content is paraphrased into an answer rather than shown as a row. OWASP lists "Vector and Embedding Weaknesses" as LLM08 in its 2025 Top 10 for LLM applications. With pgvector, the simplest strong option is to keep embeddings under the same RLS policy as everything else:
There is a performance trap. An HNSW index returns candidates first and filters afterward, so when a tenant owns a small share of the table, RLS filters out most candidates and the query returns too few results. pgvector 0.8.0 added iterative index scans for this: the scan continues until enough rows pass the filter or hnsw.max_scan_tuples (20,000 by default) is reached.
Partitioning the table by tenant_id, or partial indexes for your largest tenants, also help, with RLS kept as the safety net. With a dedicated vector database, use its native isolation primitive rather than a metadata filter. Pinecone's documentation recommends one namespace per tenant on serverless indexes, notes that namespaces are stored separately and query cost scales with namespace size, and that offboarding is deleting the namespace. A forgotten metadata filter queries every tenant; a namespace makes the tenant part of the address. Either way, enforce scoping in one retrieval function and never let feature code build raw vector queries. For a deeper look at retrieval design itself, see our guide to agentic RAG retrieval patterns that survive production.
Provider prompt caching caches the processed prefix of a prompt, not the response, and only hits on an identical prefix. Anthropic isolates caches between organizations (and, on the Claude API, between workspaces); OpenAI does not share caches across organizations. All your tenants share your organization, though, so put shared static content (instructions, tool definitions) first and tenant content after it.
Application response caching is the dangerous one. A semantic cache not keyed by tenant will return tenant A's answer, built from tenant A's documents, to a similar question from tenant B. Every cache key starts with the tenant id, and semantic caches are partitioned per tenant:
You need three kinds of identity: people who sign in, enterprises that manage those people centrally, and programs that call your API. Treat all three as principals acting for a tenant.
Users belong to tenants through memberships, because the same person will eventually need two organizations. Roles live on the membership:
Keep authorization in one permission map from role to permissions rather than role checks scattered through handlers. AI features deserve their own permissions: using the assistant, running bulk AI jobs, and changing the AI budget are different powers.
Enterprise customers expect single sign-on through their identity provider over SAML 2.0 or OpenID Connect, and often SCIM for automatic provisioning and deprovisioning. Configure SSO per tenant, keyed to a verified email domain; make enforcement a tenant setting that rejects password logins; have deprovisioning revoke sessions and the user's API keys; and map identity provider groups to membership roles. Most teams should buy SAML handling from an identity vendor, since hand-rolled signature validation has a long history of vulnerabilities, and own only the mapping from identity to membership. SSO is also a clear enterprise tier entitlement, next to AI limits.
API keys often carry the highest spend potential, because scripts do not get tired. Generate keys with high entropy, show them once, store only a hash, and look them up by a non-secret prefix:
Plain SHA-256 is fine here, unlike for passwords, because the key is 32 random bytes. Give every key scopes, its own rate limit, and an optional budget, so a leaked key's damage is capped by configuration. Control-plane tables sit outside RLS because authentication reads them before a tenant is known, so restrict them with grants and route administrative changes through permission-checked functions.
Metering turns work into money. It must be accurate enough to invoice from, fast enough to enforce limits, and durable through retries and duplicate deliveries. The pattern is the one financial systems have used for decades: immutable events, idempotent writes, and an append-only ledger.

Record one usage event per billable action, with raw token counts and cost, so you can recompute and reconcile later.
Cost is integer micros, never floating point. The unique idempotency constraint means a retried request cannot record usage twice. And cost_micros (what you paid) is separate from credits (what you charge), because margin and allowances make them diverge.
Derive the key from the unit of work, not randomly at insert time: the client's Idempotency-Key header or request id plus step for requests, the job key plus step for jobs, the run id plus step index for agents. If the same work runs twice, it must produce the same key.
Write the usage event in the same transaction as the result it pays for (the saved summary, the stored message). Both commit or neither does, which eliminates the most common metering bug.
For prepaid credits or real-time budgets, do not keep a mutable balance column. Keep an append-only ledger of signed entries and derive the balance:
The application role can insert but not update or delete, so corrections are new adjust entries. security_invoker keeps the ledger's RLS policy in force through the view. At scale, add periodic balance snapshots. Stripe's documentation describes its own credit grants as "backed by an immutable, append-only ledger"; yours is the one you can enforce against in real time.
Billing systems should receive aggregated usage, not every token event. With Stripe's Meters API, the details that matter are:
POST /v1/billing/meter_events with an event_name, a payload holding the customer id and numeric value, and optional identifier and timestamp.identifier uniqueness "within a rolling period of at least 24 hours," so a deterministic identifier is your deduplication key.v1.billing.meter.error_report_triggered. Cancellation via meter event adjustments works only within 24 hours.Use a two-step outbox: claim unbilled events and write aggregated outbox rows in one statement, then send unsent rows using the outbox id as the identifier:
Each event is either unbilled or in exactly one outbox row. Late events land in a new row for the same hour, which Stripe sums. If the sender crashes after create(), the retry reuses outbox_<id> and Stripe discards the duplicate within its deduplication window, so alert on rows unsent for hours. These workers read across tenants, so they run as a dedicated billing role, never as the application role.
Daily, compare cost_micros per provider, model, and day with the provider's usage reports. Gaps point to calls that bypassed the gateway, stale price tables, or uncounted token fields (cache writes and thinking tokens are the usual suspects).
Every pricing model implies different meters, limits, and enforcement points, so choose the pricing model first and design the events to support it.

Customers do not want to reason about tokens, and your price list should not move whenever a provider changes rates. Use an internal credit unit: each feature has a credit price per action (a chat answer is 1 credit, a summary 5, a research run 50), while the gateway tracks actual token cost for margin. You can then swap models behind a feature without changing what customers pay. Map every pricing component to a usage event before launch: a seat is a membership row, an AI action is a usage_events row with credits, an allowance is a recurring ledger grant, an overage is credits consumed beyond the allowance, and an outcome is a domain event with its own usage row.
Billing platforms rate usage, invoice, and collect payment. They are not your real-time enforcement layer. From Stripe's documentation in October 2026:
sum, count, or last and attach to metered prices, processed asynchronously.The architecture is the same either way: your application owns the real-time balance and hard limits; the billing platform owns invoices and payment.
Model cost is a formula with a handful of inputs, and every control in this section moves one of them.
For a single model call, cost is the sum of four token buckets, each at its own price:
cost = (U × P_in + W × P_write + R × P_read + O × P_out) / 1,000,000
where U is uncached input tokens, W is tokens written to the prompt cache, R is tokens read from the cache, O is output tokens (including any thinking tokens), and each P is the provider's price per million tokens. Anthropic's documentation spells out the relationship directly: total input tokens equal cache_read_input_tokens + cache_creation_input_tokens + input_tokens, and the input_tokens field only counts tokens after the last cache breakpoint.
Anthropic list prices from its documentation in October 2026 (load them from configuration, not constants):
Haiku 5.5 prompts over 100,000 tokens cost $0.50 input and $2.50 output per million. The Message Batches API halves input and output prices. OpenAI has a similar shape (default prompt caching, cached tokens in input_tokens_details.cached_tokens, a 50 percent Batch API discount), but cache rules vary by model generation.
Consider a hypothetical support assistant (illustrative numbers, not customer data). Each request sends a shared prefix of 6,000 tokens (system instructions, policies, and tool definitions), plus 4,000 tokens of retrieved context, conversation history, and the user's question, and receives about 700 output tokens.
Without caching, on Sonnet 5.5: 10,000 input tokens at $2.00 is $0.0200, plus 700 output tokens at $10.00 is $0.0070, for $0.0270 per request.
With prompt caching on the shared prefix, assume a 95 percent cache hit rate. The prefix costs 6,000 × (0.95 × $0.10 + 0.05 × $2.50) / 1,000,000 = $0.00132. The uncached 4,000 tokens cost $0.0080 and output still costs $0.0070, for $0.01632 per request, about 40 percent less.
With routing, a small classifier on Haiku 5.5 (about 800 input and 10 output tokens, $0.000085) sends the 60 percent of questions that are simple lookups to Haiku 5.5, where the same request shape costs about $0.00084. The blended cost is 0.6 × $0.00084 + 0.4 × $0.01632 + $0.000085, or roughly $0.0071 per request.
Now scale it to one tenant with 50 seats, each sending 30 requests per working day for 22 days: 33,000 requests a month.
Cache-friendly prompts and routing moved model cost from nearly half of revenue to about a tenth with no product change. It also shows the risk of seat pricing alone: a seat sending 300 requests a day costs ten times as much, and nothing in a seat price absorbs that. For offline work, a nightly job that summarizes 2,000 documents of 8,000 input tokens each, with 500 output tokens per summary, costs about $42 per run on Sonnet 5.5 at standard rates and about $21 through the Batch API.

A budget check after the call is a report, not a control. Reserve the worst-case cost before the call and settle with the actual cost after. The worst case is bounded because you set max_tokens and can count input tokens first.
The reservation commits in its own short transaction, so no lock is held during the call. A sweeper releases reservations older than your maximum call duration, and idempotent entry keys make retries safe.
Budgets cap spend per month; rate limits cap it per minute, protecting you from runaway loops and from one tenant starving others of provider quota. Anthropic rate-limits requests, input tokens, and output tokens per minute with a token bucket, so mirror that per tenant and feature:
Charge the bucket with estimated input plus max_tokens. Then cap tokens: set max_tokens per feature, summarize history beyond a fixed window, and limit retrieved chunks. Output includes thinking tokens, so effort settings (Anthropic's output_config.effort) are cost controls too.
Most products have a few task types (classify, extract, summarize, answer, act), and they do not all need your most capable model. Make routing configuration: a table keyed by task and plan returns a model, a max_tokens cap, and a batchable flag: for example, classification and extraction on Haiku 5.5, summaries and answers on Sonnet 5.5, and agent runs on Opus 5.5 for enterprise plans. Change a route only when the cheaper model passes a labeled evaluation set for that task.
Prompt caching is usually the largest lever. Put stable content first and the breakpoint after it. Anthropic uses cache_control (up to four breakpoints, 5-minute or 1-hour lifetime), reports hits in cache_read_input_tokens, and silently skips prompts under the model minimum (512 tokens on the Claude 5.5 models). OpenAI enables prompt caching by default (with a 1,024-token minimum on its newest models) and accepts a prompt_cache_key, which helps route related requests to the same cache on older models and, on newer ones, separates cache accounting per customer or workspace.
Batch processing suits anything that need not answer in seconds: summaries, evaluations, bulk classification, backfills. Anthropic's Message Batches API takes up to 100,000 requests or 256 MB per batch, finishes most within an hour, expires work not done in 24 hours, and keeps results 29 days.
Kill switches, checked on every call and cached for seconds, should exist per provider, per feature, and per tenant, so a runaway loop or injection campaign stops without a deploy.
For brevity, credits here derive from cost; most products charge a fixed credit price per action and keep cost for margin tracking. Either way, every call passes the same gates in order and ends with a settled ledger entry and a usage event.
The usage events from Part 5 contain most of what you need; traces and prompt versions add the rest.
You should be able to answer which tenants and features cost the most, and which tenants are unprofitable, with plain SQL:
Run it as an analytics role. Alert when a tenant's daily cost exceeds three times its seven-day average, or when a feature's cache hit ratio drops after a deploy.
Traces show where time and money go inside an agent run. OpenTelemetry's generative AI semantic conventions, described by the project as under active development, define attributes such as gen_ai.request.model, gen_ai.usage.input_tokens, and gen_ai.usage.output_tokens. Add your own: app.tenant_id, app.feature, app.prompt_version, and app.cost_micros on every model span. Keep tenant content (prompts, documents, answers) out of span attributes by default, because traces often flow to third-party tools with broader access.
Version every prompt template in a registry and record the version on every usage event, so "what changed?" is a query. Log full prompt content only where needed, with redaction, per-tenant retention, and an opt-out.
Set explicit timeouts per task: interactive features fail fast, batch jobs wait. Anthropic recommends streaming or batches for long requests, and its SDKs reject non-streaming requests expected to exceed 10 minutes. With streaming, add an idle timeout, and handle errors that arrive mid-stream after a 200.
In Anthropic's error reference, 429, 500, and 529 (overloaded_error) are transient, and the SDKs retry them twice by default, honoring retry-after. But a spend-cap 429 has no retry-after and keeps failing, and a workspace spend limit returns a 400. Beware retry multiplication: SDK, gateway, and queue retries stack, so one failing call becomes dozens. Give each failure type one owning layer and keep every retried unit idempotent.
Fallbacks keep features working during overloads: the same model on a second platform (Claude on Amazon Bedrock or Google Cloud), a smaller model, or another provider. Evaluate fallback routes like primary ones, expect higher cost because caches do not transfer, and pass fallbacks through the same gateway gates.
Anything that need not answer in seconds belongs on a queue, which absorbs rate limits and enables batch APIs. Add per-tenant worker concurrency limits so one tenant's 50,000-document upload does not delay everyone, weight by plan if you like, and alert on dead-letter depth.
A circuit breaker stops traffic to a failing model briefly and routes to the fallback. It handles automatic protection; kill switches handle human decisions.
AI adds one new attack surface to SaaS security: the model, which reads untrusted text and can be persuaded to act on it.
Write down an explicit isolation model: every store that holds tenant data and the mechanism that isolates it. Enterprise security reviews ask for exactly this, and the exercise usually finds a store nobody considered, such as an analytics export, a log pipeline, or an evaluation dataset.
Use TLS in transit and managed encryption at rest. For enterprise tiers, consider per-tenant keys with envelope encryption in a key management service (AWS KMS or its Google Cloud and Azure equivalents). Deleting a tenant's key makes their encrypted backups unreadable, and customer-managed keys become possible later without a storage redesign.
Prompts, completions, histories, embeddings, evaluation sets, and traces each need a retention period, configurable per tenant for enterprise plans, and deletion must reach vector indexes and caches. Embeddings are derived from customer content, so treat them as customer data. Both Anthropic and OpenAI document zero data retention arrangements for eligible customers; confirm the features you rely on work under them.
Keep an append-only log of security-relevant actions per tenant: sign-ins, SSO and role changes, API keys, budget changes, exports, and AI actions that change data or call external systems:
Expose it to tenant admins; it is one of the cheapest, most requested enterprise features.
Prompt injection is first on OWASP's 2025 list, and no model is fully immune, so limit what a successful injection can reach:
These boundaries matter more when agents reach external systems through MCP; our explainer on MCP as the integration layer behind production AI agents covers how to scope tool access per user and per tenant.
OWASP's LLM10, "Unbounded Consumption," makes every Part 7 control a security control. A leaked key without a rate limit and budget is a direct line to your model spend.
These show up repeatedly once multi-tenant AI products meet real usage.
The application connects as the table owner or an admin role. Every policy is silently bypassed. Check current_user and its attributes from inside the running application.
Tenant context set per session behind a transaction pooler. A plain SET persists on the connection and the next tenant inherits it. Use set_config(..., true).
Jobs without a tenant. Workers write data or spend money outside any tenant. Require and validate the tenant in every envelope.
A semantic cache shared across tenants. Keyed by the normalized question, it serves tenant A's answer to tenant B.
Vector search filtered after the fact. One code path forgets the filter. Make the tenant part of the query's address.
Usage recorded outside the transaction. Metered usage drifts from delivered work. Write both in one transaction.
Budgets checked after the call. An agent loop blows through the budget overnight. Reserve before, settle after.
Retry multiplication. Stacked retries turn an incident into a traffic spike and duplicate charges.
Dynamic content in front of the cache breakpoint. A timestamp at the top of the system prompt drops the cache hit ratio to near zero and costs jump with flat traffic.
Unlimited AI on a seat price. A few heavy users or scripts push model cost past their tenant's revenue. Every plan needs an allowance and a ceiling.
Pricing in raw tokens. Model upgrades change tokenization: Anthropic notes Claude Haiku 5.5 counts the same text as roughly 30 percent more tokens than Haiku 4.5. Price in your own credits.
No per-tenant cost visibility. Nobody can say which customers are profitable. Store cost per event from day one.
This order reduces risk fastest, whether you are building new or retrofitting.

withTenant transactions, job envelopes, tenant-prefixed caches, scoped retrieval.The weeks assume a small, experienced team and are a planning guide; the order matters more than the dates.
The difference between an AI feature and an AI product is mostly invisible to users: tenant context on every request, retrieval that cannot return another customer's data, usage written with the work, and a gateway that knows each call's cost before it is made. None of these patterns is new. What is new is that AI makes them mandatory from the first paying customer.
Start with isolation and metering. Add the gateway before you add the second AI feature. Price in your own units. Then let the dashboards tell you where to optimize next, whether that is a cache breakpoint, a routing rule, or a plan that needs a ceiling.
Need help designing or hardening a multi-tenant AI product? Brightter, Inc. designs and builds custom web applications and AI features, from tenant isolation and metering to model cost controls and enterprise readiness. As an official Anthropic Claude Partner and Webflow Certified Partner, we work across the stack, from production AI integrations to the marketing site that sells them. Talk to our team about an architecture review or a build.
For most B2B AI products, a shared schema with a tenant_id column and Postgres row-level security is the best default because it is cheaper and simpler to operate. Schema per tenant or database per tenant makes sense for regulated or large enterprise customers, and a tenant routing layer lets you move those customers later without rewriting the application.
Scope retrieval by tenant at the storage layer, either with row-level security on the embeddings table or with one namespace per tenant in a vector database. Key every response cache by tenant, keep one tenant per model context, and never let a tool accept a tenant id from model output.
Record a usage event with raw token counts, cost, and a deterministic idempotency key in the same database transaction as the result it pays for. Keep credits in an append-only ledger, then aggregate unbilled events into an outbox and send them to your billing platform with stable identifiers so retries never double bill.
Multiply uncached input tokens, cache write tokens, cache read tokens, and output tokens by their own per-million prices and add the results. Output includes any thinking tokens, and prompt caching, model routing, token caps, and batch processing are the main levers that lower the total.
Reserve the worst-case cost of a call in a per-tenant ledger before sending it, then settle with the actual cost from the provider's usage data afterward. Combine this with token-bucket rate limits per tenant and feature and with kill switches, because billing platforms invoice usage but do not stop requests at a zero balance.
New articles, one framework, and what we are seeing in AI and search. Once a month, five minutes to read.
Reading is a good start. A 30 minute call with a senior lead is faster.