Design a multi-tenant AI platform with per-tenant RAG and billing
Many AI startups end up building the same thing: a platform where each customer uploads their own documents, configures assistants or agents on top, and pays based on usage. The AI pieces (RAG, agents) are covered in other case studies. What is specific here is tenancy: keeping each customer's data isolated, stopping one big customer from slowing everyone else down, and metering usage accurately enough to bill for it. Get these wrong and you have either a security incident or a margin problem.
Requirements
Functional
- Tenants (organizations) with users, roles and SSO.
- Per-tenant knowledge bases: upload files, connect sources, automatic chunking and embedding.
- Per-tenant assistants and agents with their own prompts, tools, models and knowledge bases.
- Usage-based billing: plans with included credits, overage, and per-model rates; tenants can see usage in real time.
- Admin controls: data retention, model allowlists, bring-your-own-key for some tenants.
Non-functional
- Strict data isolation: no query, cache, log or model call ever mixes tenants.
- Fairness: a tenant running a bulk ingestion job must not degrade others' chat latency.
- Billing accuracy: usage events are not lost or double counted.
- Enterprise options: dedicated deployment, regional data residency.
Scale estimates (assumptions)
| Quantity | Assumption | Result |
|---|---|---|
| Tenants | 5,000 | long tail: most small, top 50 drive half the usage |
| Documents per tenant | 2,000 median, 2M for the largest | heavy skew |
| Total chunks | 1.5B | mostly from big tenants |
| Chat and agent requests | 30M/day | about 1,000/s at peak |
| Usage events | 3 per request (LLM, embedding, tool) | about 90M events/day |
The skew is the key fact. A design that gives every tenant the same physical resources wastes money on the long tail and starves the big ones.
High-level architecture
Rendering diagram…
Request flow
Rendering diagram…
Components
| Component | Responsibility | Notes |
|---|---|---|
| Gateway | Authenticate, resolve tenant, attach tenant context, enforce plan limits | Tenant id comes from the token, never from the request body |
| App services | Assistants, agents, conversations | Every query carries tenant id; enforced by the database too |
| Postgres with RLS | Relational data: tenants, users, assistants, conversations | Row level security policies keyed on a session tenant setting |
| Vector store | Per-tenant namespaces or collections | Pinecone namespaces, Qdrant or Weaviate multi-tenancy, or pgvector with RLS |
| Ingestion queues | Parse, chunk and embed per tenant | Fair scheduling so one bulk upload cannot monopolize workers |
| LLM gateway | Provider routing, tenant-level quotas, BYOK | Same pattern as a company LLM gateway, keyed by tenant |
| Metering | Collect, dedupe and aggregate usage events | Append-only ledger is the billing source of truth |
| Billing system | Plans, credits, invoices, payment | Stripe Billing meters, Metronome, Orb, or in-house |
Data model
CREATE TABLE tenants (
id UUID PRIMARY KEY,
plan TEXT,
isolation_tier TEXT, -- pooled | dedicated_index | dedicated_stack
region TEXT,
credit_balance NUMERIC(14,4)
);
CREATE TABLE knowledge_bases (
id UUID PRIMARY KEY,
tenant_id UUID NOT NULL,
name TEXT,
embedding_model TEXT,
vector_namespace TEXT -- e.g. "t_<tenant>_kb_<id>"
);
ALTER TABLE knowledge_bases ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON knowledge_bases
USING (tenant_id = current_setting('app.tenant_id')::uuid);
CREATE TABLE usage_events (
event_id TEXT PRIMARY KEY, -- idempotency key from the producer
tenant_id UUID NOT NULL,
kind TEXT, -- llm_input_tokens | llm_output_tokens | embedding_tokens | tool_call | storage_gb_hours
model TEXT,
quantity NUMERIC(18,4),
unit_price NUMERIC(12,8), -- price at the time of the event
occurred_at TIMESTAMPTZ,
source_request UUID
);
Two details carry a lot of weight. Row level security makes the database itself refuse cross-tenant reads even if application code forgets a WHERE tenant_id = .... And event_id as a primary key makes usage ingestion idempotent, so retries never double bill.
Deep dives
Choosing a tenancy model for vectors
| Model | How | Good for | Cost |
|---|---|---|---|
| Shared index, metadata filter | One index, tenant_id filter on every query | Many tiny tenants | Cheapest; isolation depends on never forgetting the filter |
| Namespace or collection per tenant | Separate logical partition per tenant | Most SaaS | Strong logical isolation, easy offboarding (delete the namespace) |
| Dedicated index or cluster | Physical separation | Large or regulated tenants | Expensive; operational overhead |
Pinecone's docs, for example, recommend one namespace per tenant for serverless indexes and note namespaces are stored separately and can be deleted to offboard a tenant. I default to namespace per tenant for everyone and promote the largest or most regulated tenants to dedicated indexes. The isolation_tier column makes that a per-tenant setting rather than a separate codebase.
Isolation everywhere, not just the database
Cross-tenant leaks rarely come from the main query. They come from the edges:
- Caches: every cache key (retrieval results, LLM response cache, embeddings) is prefixed with tenant id.
- Prompt caching at providers: shared system prompts are fine, but never put one tenant's data into a prefix shared with another.
- Logs and traces: tag with tenant id and restrict access; support tooling must respect it.
- Background jobs: workers set tenant context explicitly per job, including for RLS.
- Agents and tools: tool credentials are per tenant and stored in a secrets manager, injected at call time.
Add automated tests that create two tenants and try every API with the wrong tenant's ids.
Noisy neighbours and fair scheduling
A tenant uploading 500,000 documents should not delay another tenant's 10-document upload by hours. Use per-tenant queues (or a single queue with per-tenant concurrency limits) and a weighted fair scheduler across tenants, with weights by plan. For online traffic, enforce per-tenant rate limits and token budgets at the gateway, and keep separate worker pools for interactive (chat) and batch (ingestion, evaluations) workloads so batch can never starve interactive.
Metering and billing
Treat metering as a data pipeline with accounting rules:
- Producers (LLM gateway, embedding workers, tool runner, storage job) emit usage events with a unique id and the tenant id.
- Events land in a durable queue, then an append-only ledger, deduplicated by id.
- A balance service decrements prepaid credits in near real time so you can enforce limits (block or alert when credits run out).
- Aggregates per tenant, meter and period are pushed to the billing system for invoicing.
Record the unit price at event time, because provider prices and your rate cards change. Reconcile your ledger totals against provider invoices monthly to catch drift, and against billing system totals to catch lost events. Stripe's usage-based billing uses meters that aggregate events over a billing period, and Stripe also has a token billing offering (in preview at the time of writing); dedicated metering products like Metronome and Orb exist for more complex pricing.
Pricing what you meter
Your costs are per token per model, but customers dislike unpredictable bills. Common approaches: credits that abstract models (a premium model burns credits faster), plan-level included usage with overage, and hard spend caps per tenant. Whatever you choose, show tenants a live usage dashboard sourced from the same ledger you bill from.
Per-tenant configuration
Each tenant can pick models, chunking settings and embedding models per knowledge base. Store the embedding model on the knowledge base; queries must embed with the same model. Changing it means re-embedding that knowledge base in the background and switching atomically when done.
Trade-offs and pitfalls
- Isolation by convention. "Every query must include tenant_id" fails eventually. Enforce it in the database (RLS), the vector store (namespaces) and the cache layer.
- One size of tenant. Designing only for the median tenant breaks on the largest one. Plan promotion to dedicated resources early.
- Lost or duplicated usage. Fire-and-forget metering loses revenue; at-least-once without dedupe double bills. Use idempotent event ids.
- Margins hiding in retries. Agent retries, re-embedding and evaluation runs all cost money. Meter internal usage too, even if you do not bill it.
- BYOK complexity. Tenants bringing their own provider keys need separate rate limit handling and clear error messages when their key fails.
- Offboarding. Deleting a tenant must remove vectors, files, caches, logs and backups within your stated retention. Namespaces make the vector part easy.
Checklist
- Tenant id resolved from auth, propagated everywhere, and enforced by RLS.
- Vector isolation via namespaces by default, with a dedicated tier for large tenants.
- Every cache, log and background job is tenant-scoped.
- Per-tenant fair scheduling for ingestion; interactive and batch pools separated.
- Usage events idempotent, ledgered, priced at event time, and reconciled monthly.
- Real-time credit balance with enforced caps and a tenant-facing usage dashboard.
- Cross-tenant access tests in CI and a tested offboarding path.