Secure Multi-Tenant AI Platform
Serve 500 tenants on one shared AI platform while making a cross-tenant read, cache hit or model-context leak impossible rather than unlikely.
- Kind
- Case study
- Level
- Advanced
- View
- Interview prep
- Sections
- 4
- By
- Sourav Banerjee
- Last updated
- 20 Nov 2026
Practise this as a worksheet: Secure Multi-Tenant AI Platform
Interview view. The case brief, design walkthrough, technical deep dives and quick review, condensed into bullets, tables and lines to say out loud, with interactive diagrams to step through.
Want to go deep? The full casebook has the complete reasoning in prose, the original diagrams, practice questions with worked answers and the sources.
Case brief
The case in one line: one affordable AI platform for about 500 customer organisations, where no tenant's bytes ever reach another tenant through a row, a cache, a log, a queue or a prompt.
30-Second Cheat Sheet
- The product: one shared AI platform hosting LLM inference, RAG assistants and bounded agents for many customer organisations.
- The scale: about 500 tenants.
- The promise: no cross-tenant read, write, cache hit or model-context leak. Acme never sees Globex's documents.
- Why a
tenant_idcolumn isn't enough: it protects one table, and only when every query remembers to filter on it. - The shape: derive tenant context once from verified identity, freeze it, and enforce it at seven independent layers: row, object, cache, queue, log, vector index and key.
- The money and fairness rules: meter spend before the model call; fair queues stop one heavy tenant from slowing the rest.
- The default: shared infrastructure, with a dedicated tier decided by policy, not by customer size.
- The dangerous failure: a query, cache lookup, queue message or export that runs without a tenant predicate and reads whatever matches.
1. One platform, many customers, no shared bytes
The situation
- A provider wants one AI platform for many customer organisations.
- Why one platform: building and operating a separate stack per customer costs too much.
- Acme and Globex both use the platform.
- Acme must never see Globex's documents, whether the leak comes through:
- a database row
- a cache hit
- a log line
- the text placed in a model's prompt
The terms that carry the whole case
| Term | Meaning |
|---|---|
| Tenant | A customer organisation: a company with its own users, documents, policies, budget and contract |
| Tenant context | The tenant a request acts for, derived once from verified identity and frozen on the request |
| Tenant predicate | The tenant_id = … condition that scopes a read or write to one tenant |
| Dedicated tier | Its own cluster, region or keys, for tenants whose residency, risk or performance needs justify the cost |
Why one row label fails
- Putting a
tenant_idcolumn on every row does not deliver the promise.- It protects one table.
- It works only when every query remembers to filter on it.
What the design does instead
- Derives tenant context once from verified identity and freezes it on the request.
- Has seven layers enforce it independently: row, object, cache, queue, log, vector index and key.
- Meters spend before the model call.
- Uses fair queues so one heavy tenant can't slow the rest.
- Applies region rules to logs and backups as well as primary data.
- Offboarding proves that keys and copies are gone.
The core idea in its smallest form
verify identity → freeze tenant context → quota check
- Within quota → tenant-scoped retrieval → model call → audit.
- Over quota → degrade only that tenant.
Shared by default
- Shared infrastructure is the default.
- A dedicated tier (own cluster, region or keys) exists for tenants whose residency, risk or performance needs justify the extra cost.
- The platform decides that by policy, not by customer size.
2. Follow Maya's request through the platform
The request: Maya works at Acme and asks the platform's assistant about her company's contracts. Six things happen, and each one is a design decision this case explains.
SSO (single sign-on) = one company login for every application. IdP (identity provider) = the service that holds Acme's user accounts.
- SSO proves Maya belongs to Acme.
- The platform receives a signed token from Acme's IdP.
- It maps that verified identity to tenant
acmeand freezes the tenant on the request. - Nothing later in the request can change it.
- Quotas and region rules apply.
- Acme may be Frankfurt-only.
- That rule covers its logs and backups, not only its documents.
- Retrieval, cache and the model see only Acme bytes.
- Every store the request touches is scoped to Acme.
- The retrieved text is checked once more before it enters the prompt.
- If Globex is noisy, Maya is protected.
- Fair queues keep Globex's burst from making Maya wait.
- No hot cache entry is shared across tenants.
- Spend is metered before the model call.
- Acme's traffic can't consume Globex's budget.
- A bill after the fact is never the only control.
- If Acme leaves the platform, the provider reports these separately:
- verified deletion
- any inaccessible retained backups
- pending key destruction
- named retention exceptions
- It must not claim every copy is gone before those lifecycle steps finish.
Soundbite: "Verify the tenant once, enforce it everywhere, then meter and isolate."
- Arbitrary tenant plugins stay out of the platform core. Code the tenant supplies would run inside the boundary the platform is trying to protect.
3. The design task and what it covers
The task in one sentence
Design one affordable AI platform for about 500 tenants with no cross-tenant read, write, cache hit or model-context leak.
| What it hosts | In plain words |
|---|---|
| LLM (large language model) inference | The model that reads and writes text |
| RAG (retrieval-augmented generation) assistants | Fetch relevant documents first, then ask the model to answer from them |
| Bounded agents | Agents with limits on what they may do |
- The model receives only tenant-scoped inputs.
- It never decides which tenant a user belongs to or what that user may do.
The dangerous failure
- A query, cache lookup, queue message or export that runs without a tenant predicate and reads whatever matches.
- Why it's far worse than a bad answer: it discloses another customer's data.
- A good design makes a missing predicate impossible rather than unlikely.
Variants that share this platform's foundation
This case is the anchor for a group of problems that reuse the same tenant context and request path and change what dominates.
| Variant | Shared foundation | What changes |
|---|---|---|
| Secure platform for 500 tenants | Identity-derived scope, layered isolation, quotas, regional routing | Full platform design and the shared-versus-dedicated choice |
| Per-customer GenAI budgets | Same tenant context and request path | Meter before the model call; attribute spend and key caches by tenant and permission |
| One unusually active tenant | Same admission and usage ledger | Tell healthy adoption from a loop or abuse before throttling |
| Cross-tenant retrieval incident | Same retrieval and access-control boundary | Detect a mismatched request and document tenant, roll back the filter, purge the cache, notify the affected customer |
The four source cases (all kept)
| Source case | What it supplies |
|---|---|
| Anchor case | Design, requirements, sizing, enforcement, evaluation, rollout and delivery plan |
| Per-customer budgets | The cost drill |
| High-usage tenant | A scenario answer |
| Cross-tenant retrieval leak | An incident with its telemetry |
- Where they appear: the design in the walkthrough, the mechanisms in the deep dives, the drills in Practice (in the full casebook).
- Boundary with a sibling case: the Enterprise Knowledge Assistant case owns the detailed two-layer retrieval enforcement. This case applies it to tenants and extends isolation to every path that doesn't involve retrieval.
Who it's for
- Engineers preparing for Forward Deployed, solutions or applied-AI interviews.
- Especially a round asking for a shared AI platform or tenant isolation.
What it assumes you know
- Single sign-on
- Database row-level security
- Caching
- Retrieval
- Basic cloud architecture
- Each is explained where the design relies on it.
How to use the sections
- Design walkthrough: work through it in order.
- Technical deep dives: for follow-up questions.
- Practice (in the full casebook): attempt it before opening the answers. The source's external worksheet isn't connected; Practice includes a local worksheet instead.
- Quick review: return to it the night before an interview.
Quick Recall: Lines to Say in the Interview
- "One platform for about 500 tenants, with no cross-tenant read, write, cache hit or model-context leak."
- "A
tenant_idcolumn protects one table, and only when every query remembers it." - "Tenant context is derived once from verified identity and frozen on the request."
- "Seven layers enforce it independently: row, object, cache, queue, log, vector index and key."
- "Spend is metered before the model call; a bill after the fact is not a control."
- "Shared by default; dedicated by policy, not by customer size."
- "The model never decides which tenant a user belongs to."
Design walkthrough
The goal: a cost-efficient shared AI platform for 500 enterprise tenants with defensible isolation, fair performance, regional controls and a dedicated path for the exceptions.
30-Second Cheat Sheet
- Open with the outcome, not the topology: a cost-efficient shared platform with defensible isolation, plus a dedicated path for exceptions.
- Size the shape: 500 tenants, 50,000 active users, 200 QPS peak, 20x skew. The 0.4 QPS average tenant hides concentration.
- Control plane decides, data plane enforces: policy, region, quota and key come from the control plane; every gate and store enforces them.
- Tenant context once: from verified identity, never the request body, then immutable.
- Seven layers that don't trust each other: row, object, cache, queue, log, vector index, key. A missing predicate fails closed.
- Meter before the call, share fairly: token bucket for rate, weighted fair queuing for order, reserved lanes for contracts.
- Failure pattern: security defects fail closed, capacity pressure degrades, metadata leaks quarantine.
- Release gate: an adversarial isolation suite; zero confirmed cross-tenant incidents; roll out internal tenants first, dedicated tier last.
Opening line (source's version): "Support 500 enterprise tenants preserving isolation, predictable performance and regional controls. I'd clarify shared versus dedicated tenants, cross-region data limits, and success criteria per stakeholder. Default: a shared control plane with tenant-aware data and inference paths, strong authorisation at every boundary, and an escape hatch for premium tenants that need dedicated infrastructure."
1. Separate the feature from the business result
Feature versus result
- Feature asked for: one AI application for 500 enterprise tenants.
- Business result: a cost-efficient shared platform with defensible isolation, plus a dedicated path for the exceptions.
- Opening with Kubernetes, a vector database and a model gateway signals feature-first thinking. An FDE interviewer listens for exactly that.
FDE (Forward Deployed Engineer) = sits with the customer, works out the real problem and ships a working system in the customer's environment.
Map the four stakeholders before drawing boxes
- The headline ask hides a disagreement about what isolation and success mean. Each stakeholder judges the platform by a different result.
| Stakeholder | Job to be done | What they want |
|---|---|---|
| Tenant end user | Summarise internal content and answer questions without exposing anyone else's data | Fast, reliable, useful, no cross-tenant exposure |
| Tenant administrator | Configure policy once and roll it out safely | Control over access, configuration, usage and regional placement; onboarding without platform tickets |
| Platform operator | Run one shared fleet without noisy neighbours dominating it | A control plane that is observable, supportable and cheap at scale |
| Security and compliance auditor | Prove access and residency constraints are enforced consistently | Evidence: policies, logs, boundaries, retention rules, isolation guarantees that hold under failure |
Weak, average and strong answers
| Answer | What it does | What's missing |
|---|---|---|
| Weak | Microservices and Kubernetes, a tenant_id column on every row, row-level security |
Starts from the solution, names no customer outcome, treats one row label as the whole enforcement stack |
| Average | Shared platform with per-tenant authorisation, quotas, regional routing, audit logging, per-tenant latency monitoring | Never says where tenant context comes from, never makes the isolation layers agree, never defines when a customer graduates to dedicated |
| Strong | Shared by default (pooled economics across 500 tenants); context derived once from verified identity, never the request body, and immutable; control plane decides policy, region, quota and key, data plane enforces at gateway, services and every store; seven independent layers; a missing predicate fails closed; an adversarial isolation suite gates every external tenant | Nothing: this is the target |
Assumptions when the interviewer withholds answers
- Pick assumptions that protect against the most dangerous failure:
- Tenants bring their own identity provider.
- Regional restrictions apply to stored data and inference logs.
- Premium customers may pay for dedicated capacity.
- Model selection is already approved.
Line for interviewer silence: "If we do not know tenant variability yet, I will assume the shared tier must support most customers, but I will design an explicit dedicated path for customers with stricter residency or performance needs."
2. Ask the questions that change the architecture
- Only about six questions fit a forty-five-minute interview. Choose the ones whose answers change the design.
- Each answer should produce scope, an assumption, a risk or an owner.
- The table merges the interview guide's questions with the full design's discovery list.
| Question to ask | What it's really asking | What the answer decides |
|---|---|---|
| Which tenant data classes and AI tasks are in scope, and which are explicitly out for the first release? | Chat over tickets only, or also embeddings of contracts and logs of prompts? | Storage, inference and logging design; the trust surface of the first release |
| Are residency rules hard requirements, soft preferences or customer-specific exceptions? Do logs and backups count? | If a German tenant's data can't leave Frankfurt, do chat logs and backups count too? | Regional placement, routing, storage, backup and logging design; what must stay local |
| Which tenants may share infrastructure, and what qualifies for dedicated capacity, keys or clusters? | Can tenant A sit next to tenant B on the same GPU, or do banks get their own cluster? | One topology with tiered isolation, or a hybrid with an explicit premium tier; how much isolation you pay for |
| What does "predictable performance" mean per tenant: throughput, latency, queue time or fairness? Workload shape, peak skew, noisy-neighbour tolerance? | If one tenant sends 20 times the traffic, do the other 499 get slow? | Capacity, quotas or a fair scheduler: quotas, admission control, queue isolation and reserved lanes |
| Do customers federate identity or bring their own keys? Is deletion hard or best-effort, and what does verified deletion require? | When a customer leaves, can we prove every copy, keys included, is gone? | Identity federation and membership mapping, key management, data inventory, offboarding workflow |
| Which budgets are contractual, and can tenants choose model tiers? | Can a tenant burn $10k overnight on a frontier model, or do we stop them before the call? | Pre-call admission, model routing, metering and billing |
| What proof must an auditor or incident commander see: logs, policy snapshots, access reviews or data lineage? | After a suspected leak, can we show tenant B's documents never entered tenant A's context? | Isolation tests, the audit pipeline's schema, tenant-scoped audit and retention |
| Which failure is most expensive: leakage, unavailability, slow inference or misrouted regional traffic? | Where would one bad hour hurt the provider most? | Where the interview hour, and the engineering effort, is spent |
The two answers that matter most
- Residency decides whether logs and backups need regional storage. That's far harder to retrofit than a database.
- The definition of "predictable" decides whether you build more capacity, quotas or a fair scheduler: three different mechanisms (steps 4 and 8).
3. State requirements as testable constraints
- Four buckets: functional (what it does), non-functional (how well, under what constraints), explicit exclusions, hard constraints.
- The trap is premature certainty: the interviewer usually answers only half the questions.
Functional requirements, in value order
- Tenant-aware control plane. Onboard tenants, assign policies, provision configuration, manage keys, record administrator actions.
- Isolated data-plane request path. Stamp immutable tenant context from verified identity on every request. Carry tenant identity, policy context and authorisation through the whole call chain, so data, cache, queues, retrieval and inference are scoped to that tenant.
- Per-tenant policy, quotas, keys, regions, retention and configuration, without bespoke code paths per customer.
- Regional routing and retention controls. Send requests and artifacts to the correct region; retain or delete them under the tenant's policy.
- Auditable administration. Who changed what, when, under which tenant context.
- Dedicated deployment tier where justified, as an explicit escape hatch.
- Coordinated export and deletion when a tenant leaves.
- The control plane is the foundation. The dedicated tier is an escape hatch, not a default.
| Priority | What's in it | Why |
|---|---|---|
| Must-have | The first five above | Each protects against a highest-risk failure |
| Should-have | Richer quota tuning, broader automation | Useful once the core is trusted |
| Could-have | Advanced tenant analytics, convenience workflows | Never expands the core design or delays launch |
- A tenant whose must-have the shared tier can't meet safely is the justification for the dedicated path.
Out of the first release (unless the interviewer pushes)
- Each widens the trust surface or the support burden:
- arbitrary tenant-managed plugin execution inside the core platform
- cross-region active-active writes for every tenant
- fully custom per-tenant runtime stacks
- unlimited per-request model swapping; tenants choose from platform-approved models
- manual exception handling for every onboarding request
- ad hoc shared-secret administration outside the control plane
SLO (service level objective) = an internal target such as "95% of answers in under 3 seconds". p95 = the latency that 95% of requests meet.
Safety goals and operating constraints, stated so a test can fail them
| Constraint | Stated so it can be tested |
|---|---|
| Zero cross-tenant reads or writes | No exposure of another tenant's data, prompts, embeddings, outputs, logs or admin state through authorised or accidental paths. Context from verified identity, never the request body. Zero confirmed exposure; security failures fail closed |
| Bounded resource contention (fairness) | One tenant's workload can't cause unbounded latency or throughput collapse for neighbours. Shared infrastructure shares constraints |
| Tenant-scoped blast radius | A failed deploy, bad policy or revoked credential affects only the minimum necessary set of tenants |
| Latency | Per-tenant p95 measured and alerted separately, not only as a fleet average. A 2-second budget forces fewer hops and more caching; a 15-second workflow permits durable queues and async work |
| Availability | Sized for load shape, not the average. 200 queries per second at peak with 20 times skew makes any uniform-tenant assumption unsafe |
| Observability | p95 and cost measured by tenant, not only across the fleet |
| Compliance and audit | Append-only audit of tenant, actor, action, resource and decision, retained per tenant policy; control-plane changes are auditable |
| Cost | C_tenant = C_fixed/N + C_usage + C_isolation. Share when safe; pay the isolation premium only for residency, risk or performance |
Give every requirement a component
- No component → the requirement probably isn't real yet.
- No requirement → the component is probably scope creep.
- Say that aloud while presenting the table.
| Requirement | Primary component or mechanism |
|---|---|
| Tenant-aware control plane | Tenant registry, provisioning workflow, admin API |
| Isolated data-plane request path | Auth gateway, request context propagation, policy enforcement point |
| Per-tenant policy, quotas, keys and configuration | Policy store, quota service, secrets management, config service |
| Regional routing and retention controls | Traffic router, region-aware storage, retention scheduler |
| Auditable administration | Append-only audit log, admin event pipeline |
| Dedicated deployment tier | Separate cluster or namespace boundary with tenant-specific capacity |
| Zero cross-tenant reads or writes | Authorisation checks, row-level or object-level isolation, test gates |
| Bounded resource contention | Quotas, admission control, queue isolation, autoscaling limits |
| Tenant-scoped blast radius | Deployment partitions, scoped rollout, tenant-level feature flags |
| Safe onboarding and offboarding | Provisioning workflows, deletion jobs, verification checks |
Spoken answer (requirements in one breath): "Functionally, derive tenant once and enforce it at every store and model call. Non-functionally, zero cross-tenant leaks, per-tenant p95 and cost, fail closed, and isolation you can prove to an auditor."
4. Size for the load shape, not the average
The illustrative numbers
- A design plausible at average traffic fails exactly when customers feel pain. Size for average, peak, growth and skew.
- The source's numbers are round and illustrative; their only job is to force decisions.
| Assumption | Value |
|---|---|
| Tenants | 500 |
| Active users | 50,000 |
| Peak | 200 QPS (queries per second) |
| Workload skew | 20 times |
| Naive average per tenant | 200 ÷ 500 = 0.4 QPS |
Why the average lies
- With 20 times skew, a few large tenants drive a material share of the peak.
- No uniform-tenant assumption is safe for queue sizing, cache partitioning, rate limiting, retry policy or noisy-neighbour protection.
- The estimate that matters most: peak concurrency after retries, fan-out and long-tail inference latency, not raw QPS.
- A design sized exactly to the naive peak is already broken. Reserve headroom for:
- tenant concentration
- retried requests
- failover overhead
- capacity lost during deploys
- growth before the next tuning cycle
Four per-tenant controls beside pooled capacity
| Control | What it does |
|---|---|
| Token quota | Caps hourly or monthly usage to protect spend and fairness |
| Concurrency quota | Stops one tenant from saturating worker pools or model backends |
| Burst quota | Allows short spikes without immediate throttling |
| Reserved capacity | Protects contractual performance for premium tenants |
- Name the trade-off:
- Too tight → artificial failures customers see.
- Too loose → one tenant's burst consumes the shared budget and lands on its neighbours.
Anchor SLOs in the customer's workflow
- Availability: successful requests or job completions over a window.
- Latency: end-to-end response time or completion time.
- Freshness: time from a source update to the model seeing it.
- Quality: task success rate and grounded-answer rate.
- Security indicators: authorisation failures, policy denials, blocked cross-tenant attempts.
- Cost: per request, per tenant and per successful task.
- Tie one target to a workflow aloud. If the platform powers support agents, the latency budget must preserve the agent's interaction loop. A technically successful response that arrives too late isn't useful.
Unit economics settle shared versus dedicated
C_tenant = C_fixed / N + C_usage + C_isolation
| Term | What it is |
|---|---|
C_fixed / N |
Shared platform cost spread across N tenants |
C_usage |
Variable cost the tenant drives: tokens, storage, retrieval, egress, compute |
C_isolation |
Premium for stronger separation: dedicated pools, stricter network boundaries, regional duplication, customer-specific encryption, extra compliance controls |
- Pooled economics win when most tenants can share safely. Pay the isolation premium only where a requirement demands it (worked example in the unit economics deep dive).
Size the 10x case too
- The dominant risk changes, not only the numbers.
| Assumption | Current illustrative case | 10x growth case |
|---|---|---|
| Tenants | 500 | 5,000 |
| Active users | 50,000 | 500,000 |
| Peak QPS | 200 | 2,000 |
| Skew | 20x | 20x or worse |
| Shared capacity strategy | pooled plus quotas | pooled plus stricter partitioning |
| Isolation posture | shared by default, dedicated for exceptions | more dedicated pools, more explicit regional controls |
- At 10 times, noisy neighbours, cache churn and operational complexity move the design from one shared tier with guardrails to tiered tenancy with explicit partitioning, more regional partitions and more dedicated pools.
- One bigger inference pool won't cover it.
Define two things before the happy path
- Per-region recovery objectives. Together they decide replication, failover routing and queue durability.
RPO (recovery point objective) = how much data, measured in time, you can afford to lose in a disaster. RTO (recovery time objective) = how long you can afford to be down.
- The missing-tenant-predicate drill. Can a request, query, export, cache lookup or admin action cross a tenant boundary if a filter is omitted? A design without that test is incomplete.
Spoken answer: "I will size for average, peak, and growth; reserve headroom for skew and failover; give each tenant token and concurrency quotas; and tie latency and availability targets to the customer's workflow. I prefer pooled economics for the common case, but I will pay for stronger isolation when the risk, performance, or regional requirement justifies it."
5. Draw the control plane and the data plane
The organising split
| Plane | What it does | How it changes |
|---|---|---|
| Control plane | Decides who may do what, where and under which limits | Slower, more privileged, more auditable |
| Data plane | Does the work for each request and enforces those decisions | Per request |
- Moving a tenant to the dedicated tier is a controlled configuration change in the control plane, not an ad hoc code path.
The whole-platform view
- Control plane (left): customer identity federation, tenant directory, policy decision point, regional scheduler, per-tenant key context, quota and model-routing policy.
- Regional data plane (right): API gateway → immutable context → policy check → pre-call quota → tenant-aware service → vector retrieval with chunk-tenant check → fair LLM inference → typed output check → audit and usage ledger, with fail-closed and over-limit branches.
Maya's request through the data plane, in eight steps
- The API gateway validates the identity token and maps the principal through the tenant directory. It ignores any tenant ID in the request body.
Principal = the verified user or workload.
- The platform creates immutable actor, tenant, role and region context, then evaluates policy for the specific action and resource. Tenant, action or region not allowed → fail closed and audited.
- The request is routed only to an allowed region and to the shared or dedicated tier. Tenant-specific keys and retention policy are selected.
- Tokens, concurrency and budget are metered before inference. A tenant over quota is queued or rejected without stalling its neighbours.
- Tenant-aware services read and write scoped database rows, object namespaces, cache keys, queue envelopes and vector indexes. A missing scope fails closed.
- Vector retrieval applies a tenant filter at ingestion and at query time, then independently checks
request.tenant_id == chunk.doc_tenant_idbefore building the prompt. A request that needs no retrieval goes straight to inference. - The permitted request goes to fair shared or reserved LLM inference. Typed model output is validated before any persistence or downstream action.
- Tenant-scoped audit and usage events are emitted; the answer is returned only within the verified context.
The platform's agent role is narrow
- It hosts RAG assistants and bounded agents, not one universal autonomous agent.
- Every prompt, retrieval, tool call, cache hit, output and trace inherits the same immutable tenant context.
- An agent's plan is a proposal that platform policy checks.
- Model output can never establish identity or authority.
The three other views the source draws
- Control-plane view: customer IdP → identity federation → tenant directory → immutable tenant context, and → policy decision point → regional scheduler (allowed region and tier) and per-tenant key selection.
- Data-plane view (top to bottom): gateway validates shape and rejects early → authorise by role, tenant, action and region → route to region and tier → admit within concurrency, token and budget quotas → tenant-aware service → tenant-scoped stores, audit event, answer.
- Missing tenant predicate → fail closed with a rejection, a 404 or no result.
- Each gate runs before expensive work.
- Both planes, every store: dotted lines carry the immutable context into the gateway and authorisation step. The tenant-aware service fans out to:
- partitioned database
- queue with a tenant envelope
- vector index scoped at ingest and query
- cache with the tenant in its key
- audit pipeline (feeding a per-tenant usage ledger and dashboards)
- fair-queued inference workers
- namespaced object store
- plus a "fail closed" branch on a missing predicate.
What each plane holds
- Control plane: central policy definition, regional enforcement, group sync through SCIM, per-tenant retention, quotas, keys, tenant registry, provisioning.
SCIM (System for Cross-domain Identity Management) = the standard an IdP uses to push user and group changes to other systems. A removal arrives on the next push, not instantly.
- Downstream services never re-derive tenant context.
- Data plane: tenant scope in physical layout and every predicate: database partitions, object namespaces, cache keys, queue envelopes and dead letters, vector ingestion and query, envelope-encryption keys.
- Inference: fair queues and reserved lanes where required. Residency comes from the scheduler.
- Monitoring: p95 per tenant, quota rejections, cost per tenant, cross-tenant retrieval count, isolation tests, failover time.
If time is short: the compressed whiteboard
- Control side: identity federation, tenant directory, policy decision point, key manager, regional scheduler.
- Data side: API gateway, tenant-aware services, quota service, one partitioned store, cache, queue and vector index.
- Plus: an audit pipeline and the fail-closed exit on a missing tenant predicate.
Components in dependency order
- The order they must exist in, and the order they fail in. Fail closed = the request is refused. Degrade = service continues with reduced capability.
| Component | Responsibility | Trust boundary | Plane | Fails how |
|---|---|---|---|---|
| Identity federation | Authenticate the caller through the customer's IdP; deliver verified claims | External customer boundary to platform boundary | Control | Closed: no verified token, no request |
| Tenant directory | Map identity to tenant membership, posture and allowed regions | Platform authority boundary | Control | Closed: unresolved membership is denied |
| Policy decision point | Decide whether the action is permitted for this tenant, principal and region | Privileged policy boundary | Control | Closed: no decision, no admission |
| API gateway | Admit, shape and route; reject malformed or disallowed traffic early | Edge boundary | Data | Closed on auth, degrades on capacity |
| Tenant-aware services | Execute business logic using immutable tenant context only | Service boundary inside the shared platform | Data | Closed on a missing predicate |
| Partitioned databases and indexes | Persist tenant-scoped records with tenant-aware keys and predicates | Storage boundary | Data | Closed: the store refuses an unscoped read |
| Quota service | Enforce concurrency, token and budget limits per tenant or tier | Shared-resource governance boundary | Control with data-plane hooks | Degrades that tenant only; closed if the quota system is compromised |
| Per-tenant key manager | Select or issue tenant-specific encryption context | Key-management boundary | Control | Closed: no key, no read |
| Regional scheduler | Place workload into an allowed region and tier | Placement and residency boundary | Control | Closed for sensitive writes; queue or reroute otherwise |
| Audit pipeline | Capture immutable tenant-scoped events for investigation and billing | Observability and compliance boundary | Data | Degrades: the action completes, the gap is alerted |
Three boundaries to point at
- Sync/async boundary (after audit).
- Synchronous: authentication, authorisation, quota admission, region selection.
- May be async: reporting, logging, offline enrichment.
- Anything that could cross a trust boundary or consume scarce capacity is never deferred blindly to a background task.
- Systems of record.
- Tenant directory → membership. Partitioned database → tenant data. Quota service → usage. Audit pipeline → traceability.
- A boundary mistake among them is a security incident.
- Caches improve latency and are never the source of truth for membership or authorisation.
- Queues carry tenant identifiers and policy context explicitly. Backpressure is only safe when the worker knows which tenant it's slowing down.
The MVP
MVP (minimum viable product) = the smallest version real users can rely on.
- One policy service, one gateway, one tenant-aware application tier, one partitioned data store, one quota service, one regional control plane, one audit stream.
- Enough to prove isolation, performance shaping and regional routing.
- Extensions, not prerequisites: dedicated customer clusters, per-service SLOs, richer workload classification, a more granular policy language.
6. Derive tenant context once and make it immutable
Verified identity, never the request body
| Source of tenant | Trust it? | Why |
|---|---|---|
| Signed token, verified claim, server-side session | Yes | Can be authenticated and logged |
| Header or JSON field the client sets | No (unless a trusted gateway sets it) | Can be spoofed, replayed or forwarded across tenants by accident |
- That one choice governs everything downstream. Row filters, object ownership, cache keys, queue partitions, log redaction and vector-index lookups all consume the same verified context.
The strict dependency order
- Why each position: identity must come first; context must become immutable early; policy must run before expensive work; region is a control-plane decision, not a late optimisation; audit happens after the action but close to it.
- Identity federation authenticates the human or workload through the customer's IdP.
- Tenant directory maps the principal to tenant membership and allowed deployment posture.
- Policy decision point evaluates principal, action, resource and region together.
- API gateway admits, shapes and routes into the correct service tier.
- Tenant-aware services execute only after receiving immutable context.
- Partitioned databases and indexes carry the tenant key in physical layout and every predicate.
- Quota service tracks concurrency, token and budget limits.
- Per-tenant key manager selects the encryption context for tenant and tier.
- Regional scheduler decides which region and cluster class may serve the request.
- Audit pipeline records tenant-scoped activity.
Narrate the happy path with a customer reason per step
| Step | Customer reason |
|---|---|
| Authenticate through federation | The customer keeps its own identity source |
| Derive immutable tenant context | One company may have several subsidiaries; the platform must decide which one is acting |
| Authorise against policy | Authorisation must be explainable and centrally governed |
| Route to the allowed region and tier | Location control is part of the product promise |
| Apply quota before inference | Shared must not mean noisy neighbour |
| Read and write only tenant-scoped resources | Isolation |
| Emit a tenant-scoped audit event | Enterprise buyers need traceability |
The same order as a sequence
- Happy path: gateway validates identity → receives immutable context from the directory → "Allow" from the policy decision point → placement decision from the scheduler → "Admit" from the quota service → forwards the request.
- Failure branch: the tenant-aware service queries without a tenant key → the store rejects it or returns no result → a failed-access audit event records the reason → the user gets a denied response.
- If your diagram doesn't make the missing-predicate case obvious, the design is still too vague.
- The strongest signal is how you narrate identity, data, state and failure moving through the diagram, more than the drawing.
Three production identity problems (none is authorisation)
| Problem | What to do |
|---|---|
| Token validation | Check the signature against the IdP's published keys, the issuer, the expiry and the audience (issued for this application), before any permission logic |
| Group mapping | The customer's Okta or Microsoft Entra ID (formerly Azure AD) groups are the source of truth, mapped into the platform's role vocabulary. That mapping is configuration and drifts silently when a group is renamed: alert on renamed groups and mapping drift |
| Just-in-time provisioning | Create the first local user record from the token's claims, scoped to the customer, granting the minimum local role by default |
- The data model that holds this context is in the tenant context deep dive.
7. Enforce isolation at seven layers that do not trust each other
Why one row label isn't enough
- Easy to omit in application code, ad hoc queries, background jobs and admin tools.
- Covers nothing in backups, object storage, search indexes, caches, analytics pipelines or service-to-service authentication.
- So seven layers enforce independently: one missed check doesn't become a full breach.
| Layer | What must be true | Enforced rule |
|---|---|---|
| Row | Every query includes the tenant predicate; the database enforces it where possible | DB or session policy refuses an unscoped query, with a non-owner app role that has neither superuser nor BYPASSRLS; FORCE ROW LEVEL SECURITY also subjects an owner to the policy; app convention alone isn't enough |
| Object | Files, blobs and embeddings namespaced or separately authorised by tenant | Blob and embedding namespaces are tenant-scoped |
| Cache | Every key includes the tenant ID; a shared cache never returns data with ambiguous authorisation context | Key includes tenant, permission signature and version; a cross-tenant hit is an incident |
| Queue | Messages never expose payload metadata across tenants, especially in shared dead-letter and retry channels | Envelope and dead-letter path preserve tenant scope |
| Log | Logs never expose secrets, raw prompts or cross-tenant identifiers that let someone reconstruct another customer's state | No raw prompt, secret or other tenant's identifiers in shared telemetry |
| Vector index | Tenant scoping at ingestion and at query time; semantic search otherwise surfaces neighbouring content | Tenant-scoped at ingestion and search, with a post-retrieval tenant invariant |
| Key | Tenant-scoped encryption keys with envelope encryption, so one compromise doesn't span the fleet | Raw storage yields only ciphertext; a leaked tenant key opens one tenant, not all; crypto-shredding requires destroying all recoverable tenant decryption paths |
The tenant predicate: the mechanism this case owns
RLS (row-level security) = the database returns only the rows the current session may see.
- The store itself refuses to return a row unless the request is already scoped to one tenant.
- RLS does that when bound to the verified session context.
- PostgreSQL precondition:
- Use a non-owner app role without superuser or BYPASSRLS privilege.
- FORCE ROW LEVEL SECURITY subjects a table owner to the policy. It doesn't constrain superusers or BYPASSRLS roles.
- Isolation then never depends on every engineer remembering
WHERE tenant_id = …. A future API that forgets the clause returns nothing, not another company's data. - Partitioning by tenant helps only if each tenant's partition sits behind its own credentials.
The same predicate in retrieval and cache
- The predicate is compiled into the vector-search filter and into the cache key (tenant, permission signature, version).
- The Enterprise Knowledge Assistant case's two-layer retrieval pattern applies unchanged:
- Layer 1: the tenant predicate in the search (pre-filter, makes search cheap).
- Layer 2: the post-retrieval invariant
request.tenant_id == chunk.doc_tenant_id(post-check, makes it authoritative).
- The cross-tenant leak incident (deep dives) shows what happens when layer 2 is skipped.
- Tenant isolation must also extend to every path that doesn't involve retrieval.
Pick a tenancy level and justify it
| Level | What it means | When |
|---|---|---|
| Shared infrastructure, tenant ID on every row | One database, one set of tables; every row tagged, every read and write includes the tag | The default: cheapest, fastest to ship |
| Separate schema or namespace per tenant | Same cluster; one tenant's tables aren't another's | Stronger isolation without an extra deployment |
| Dedicated deployment per tenant | Separate cluster, region and encryption keys | Contracts or risk policy rule out sharing, often in banking and healthcare |
- Start at level 1 and make that default honest with two follow-ups:
- The database enforces the tenant, not the application.
- Regulated customers get a named escalation path from a tagged row to their own keys, region or deployment.
- The tenancy tiers deep dive traces one tenant through each level.
Per-tenant keys
- The question they answer: "what happens if someone gets raw read access to the storage layer?"
- Per-tenant data keys wrapped by a master key → storage access alone yields only ciphertext.
- A leaked tenant key opens one tenant, not the fleet.
- Cryptographic erasure requires destroying every recoverable decryption path, not deleting one wrapped data-key record.
- A backup containing that wrapped key can still be decrypted while its shared wrapping key remains usable.
- One platform-wide key: a single leak exposes every customer at once.
- The master key still guards everyone, so it lives in the KMS (key management service) and never leaves it.
Two more principles for the board
- Least privilege: each service identity sees only the tenant scope it needs, only for the operation it performs.
- Blast radius as the design unit: measure what a failure can reach by tenant, region, workflow and dependency.
- Negative isolation tests matter more than positive ones. Prove the wrong tenant can't read, infer, cache, dequeue or search another tenant's data.
Spoken answer: "I'd start with shared infrastructure and a tenant id on every record, that's the right default. The filter has to live in the data layer, not in application code: the store should refuse to return a row unless the request is tenant-scoped. For regulated customers I'd escalate to a separate schema or a dedicated region and keys, not just a different tag in the same table."
8. Meter before the call and share fairly
Budgets before the call
- Apply quota and budget before inference, storage growth or batch fan-out, never after.
- A budget checked after the call is a bill, not a control, and here budgets are contractual.
- The quota service enforces token, concurrency, burst and monetary limits per tenant or tier.
- The usage ledger attributes every request to a tenant.
- Quota alerts fire before the limit, not at it.
Rate limiting and fairness are different problems
| Mechanism | Question it answers | How |
|---|---|---|
| Rate limit | May this request proceed at all? | A ceiling on one tenant's own allotment; a token bucket per tenant caps rate |
| Fair queue | In what order are requests served when workers are busy? | Weighted fair queuing across per-tenant queues feeding a shared pool; throughput shared proportionally, not first come, first served |
| Reserved lanes | Does a premium tenant's contract survive contention? | Held capacity, without forcing a dedicated cluster |
- Without fairness, a large tenant's burst can make a small, well-behaved tenant wait, even though the small tenant never exceeded any limit.
- The admission and fairness deep dive traces both with numbers.
Contain a noisy neighbour in two steps
- Per-tenant controls: quotas, rate limits, concurrency caps, workload classification.
- Isolate the expensive parts: admission control before inference, queue partitioning, reserved capacity for premium tenants, circuit breakers when a tenant goes past its envelope.
- Noise from a bug → fast detection and a kill switch.
- Legitimate burst demand → fairness, not punishment.
- Autoscaling alone doesn't solve it: it adds capacity without deciding who gets it.
One tenant's usage is unusually high: diagnose before throttling
- Segment by: API key, user, feature, time, model route, prompt version, tokens per request, batch jobs, agent steps.
- Decide: healthy adoption, a loop, abuse or a missing quota?
- Healthy adoption → capacity planning.
- Loops and abuse → throttle or pause.
When to move a customer to dedicated
- When shared tenancy no longer satisfies risk, performance or operational requirements at acceptable cost.
- Triggers:
- regulatory residency constraints
- unusually strict latency SLOs
- high-value workloads with low tolerance for contention
- a customer policy demanding a harder boundary
- Avoid "big customers get dedicated": define measurable thresholds and an exception review path.
9. Route by region and keep policy central
Central definition, regional enforcement
- Regional controls reshape routing, storage, backup and logging. Settle early: hard requirement or customer exception?
- Balanced answer: central policy definition with regional enforcement, unless residency or availability forces local control.
| Option | Gain | Cost |
|---|---|---|
| Central control plane | Consistent policy | Can become a latency and residency problem |
| Fully regional | Better locality | Duplication, rollout complexity, policies drifting apart |
Residency covers every artifact
- The regional scheduler places work in an allowed region and tier as a control-plane decision.
- A tenant's residency rule includes data, prompts, outputs, inference traces, logs, backups and derived indexes. They follow the tenant's policy, not the platform's convenience.
- Retention is part of the data model: it attaches to the tenant record or a versioned policy the record references. No service rediscovers policy from scattered flags or brittle configuration.
Control-plane outage: serious, not always a full outage
- Policy distribution, deployment coordination and config updates may be impaired while requests still flow.
- Monitor control-plane health separately from the data plane; alert when the local authority source stops refreshing.
| During the outage | Action |
|---|---|
| Safe reads with locally held verified policy and preloaded keys | Keep serving |
| Sensitive changes | Fail closed |
| Non-critical writes | Queue where safe, or reroute |
| Irreversible action on stale control state | Never silently continue |
- Recover: restore the regional controller, reconcile queued changes, confirm sync with the authoritative policy source.
- Prevent: design for tolerance of stale control state, cache the minimum policy state locally, rehearse regional failover, keep distinct emergency access paths.
Export and deletion across regions
- A tenant inventory and deletion workflow span every store: relational rows, blobs, embeddings, caches, queues, logs, backups and derived artifacts.
- Export assembles a complete package with clear ownership and time bounds.
- Deletion is a coordinated job with verification, named retention exceptions and an auditable completion record.
- A database delete alone is not offboarding.
- Backup deletion follows retention windows and restore controls, not ad hoc surgical erasure (the offboarding deep dive explains why).
10. Fail closed on security, degrade on capacity
Memorise the pattern, not the table
- Security defects fail closed: the request is refused.
- Capacity pressure degrades: slower or with less, for the affected tenant only.
- Metadata leaks quarantine the affected path and escalate to a human.
- Control-plane loss depends on whether local enforcement still holds.
| Scenario | Recommended behaviour | Why |
|---|---|---|
| Missing tenant predicate, or a request routed to a disallowed region | Fail closed immediately; reject, audit and stop the affected path | An unscoped read or write is a security defect, not a transient error |
| Cache key omits tenant ID | Fail closed: disable the path, invalidate affected entries, inspect what was served | A shared cache hit can leak across tenants even when the database is safe |
| Shared queue leaks payload metadata | Fail closed, quarantine the queue, investigate, rotate credentials if needed | Message metadata can reveal customer identity or workflow state |
| One tenant exhausts model quota | Throttle or degrade that tenant only; keep service fair for the rest | Shared capacity should protect neighbours and preserve fairness |
| Regional control-plane outage | Queue, reroute or degrade by dependency criticality | Control-plane loss shouldn't take down data-plane operations if local enforcement still works |
| Key or policy authority unavailable | Fail closed for protected data or actions | No verified key or decision means no safe read or change |
| Vector index surfaces a neighbour's chunk | Fail closed on the post-retrieval tenant invariant; block the response | Usually a tenant filter missing or wrong at query time (as in the leak incident), or chunks ingested without a tenant tag |
| Misrouted regional traffic | Reject at the scheduler; alert; audit the route | Sending protected data to an unauthorised region is a residency breach |
The drill shape: detect, refuse and log, contain, recover, prevent
- The first five scenarios each have a rehearsed drill in the source tutorial; all share this shape. Worked for a repository method called without a tenant predicate:
- Detect through code review, automated tests and runtime alerts on any query reaching a repository without tenant scope. Detection never depends on a customer ticket.
- Refuse and log with a security error, never a silently substituted default tenant. Log the identity, trace, operation and the fact that scope was missing.
- Contain.
- Before production: block the release.
- In production: disable the feature path, rotate credentials, freeze logs and traces as evidence.
- In-flight retries keep failing closed rather than retrying into a different scope.
- Recover. Re-run affected requests through the corrected path; verify no cross-tenant result was returned; confirm idempotency keys and replay logs can't bypass the fixed check.
- Prevent. A negative test that fails if any unscoped repository method is reachable, plus static linting of query shape. The unscoped path becomes hard to call, not merely discouraged.
The cache drill candidates underrate
- Looks harmless because the database stays protected, but a shared cache replays the wrong tenant's object if the key misses tenant scope.
| Drill step | Action |
|---|---|
| Detect | Instrument key components in metrics and traces |
| Contain | Disable the cache path or namespace, invalidate suspect entries, fall back to the source of truth |
| Recover | Rebuild from correctly scoped reads; re-check responses served in the affected window |
| Prevent | Tenant ID required in every cache-key helper; centralised key construction; a negative test asserting a cross-tenant lookup is a miss |
- If the cache holds authorisation-sensitive material, it's a security incident, not a performance bug.
Production failure behaviour separates a toy from a system
- Timeouts tight enough to avoid pile-ups of stale work.
- Retries only for transient failures, never for authorisation failures or malformed requests.
- Idempotency on writes, billing events and workflow triggers, so a repeated request can't apply twice.
- Circuit breakers on dependencies that keep failing.
- Dead-letter queues hold poison messages for inspection rather than reprocessing them forever.
- Human escalation for policy corruption, suspected isolation failure or ambiguous tenant ownership.
- An honest design says which failures recover automatically and which need a human with authority.
- What breaks first at 10 times: noisy-neighbour risk and cache churn. Pooled-plus-quotas becomes pooled-plus-partitioning, with more dedicated pools and more explicit regional controls.
11. Gate the release on an adversarial isolation suite
The suite proves the central promise
- Goal: show the system fails safely and visibly under attack, not prove perfection.
- A single unexplained boundary failure halts promotion.
- Target for confirmed cross-tenant incidents: zero.
- It tries: cross-tenant object reads with wrong-tenant IDs, stale-cache hits, replayed tokens, malformed filters, namespace collisions, missing predicates, cross-tenant vector retrieval.
SRE (site reliability engineering) = the team and practice that keeps production running.
| Metric | Good threshold | Bad threshold | Test dataset | Owner |
|---|---|---|---|---|
| Cross-tenant incident count | Zero confirmed | Any incident halts promotion | Incident reports and audit-log review | Security / incident commander |
| Isolation-test pass rate | Full pass | Any new boundary failure blocks release | Adversarial negative-test suite: cross-tenant object access, stale cache reads, replayed tokens, malformed filters, namespace collisions, missing predicates | Security engineering |
| Per-tenant p95 latency | Within SLO per tenant, not in aggregate | Sustained breach | Request telemetry segmented by tenant | SRE |
| Quota rejection rate | Low and explainable per tenant class | Mis-sized quotas or poor onboarding | Admission and quota logs | Platform ops + product |
| Cost per tenant | Within the band for the tenant class | Above band | Billing mapped to tenant usage | Finance + platform |
| Regional failover time | Within the agreed RTO | Recovery exceeds target | Game-day and failover drills | SRE |
Keep metric layers apart
- Technical health, model quality, adoption, business outcome stay separate. Once they blur, you can't tell an engineering problem from a product-fit problem or customer behaviour.
- Trace a complaint to telemetry in one chain: "document processing feels slow" → request arrival → quota admission → queue depth → inference duration → retrieval latency → cache hit ratio → regional routing.
Evidence to hold before launch
- The isolation test deep dive shows the interview-sized test proving one invariant at the API level. Also hold:
- access logs showing tenant context derived from identity
- the negative isolation tests
- role and permission reviews
- queue and cache namespace checks
- key-rotation procedures
- incident runbooks for suspected boundary failures
Soundbite: "The question isn't 'do we have security?' It's 'can we prove the system fails in the right direction, and recover without widening the blast radius?'"
- Every external dependency and irreversible action needs an explicit failure and recovery policy.
- The absence of a policy is itself a policy, and it usually fails open.
12. Roll out internal tenants first and the dedicated tier last
Done means adopted and supportable
- Done only when users adopt it, the workflow improves and the operating team can support it.
- A staged rollout with measurable gates, named owners and rollback paths answers "when can this be trusted in production?"
| Phase | Owner | Exit criteria | Go / no-go |
|---|---|---|---|
| 1. Onboard internal test tenants | Platform engineering; security and product review | Authentication, tenant resolution, row-level filtering, storage partitioning and logging work; every access path carries tenant context end to end; every admin action attributable | Stop if identity propagation is inconsistent, tenant data is queryable from the wrong context, or support can't trace a request |
| 2. Run the adversarial isolation suite | Security engineering; platform engineering fixes | Repeatable negative tests: cross-tenant object access, stale cache reads, replayed tokens, malformed filters, namespace collisions, missing predicates | Passes consistently before any external tenant; one unexplained boundary failure halts promotion |
| 3. Introduce small shared tenants | Product operations; support and reliability on call | Low-risk customers in the shared tier under conservative quotas and strict monitoring | Continue only if boundaries hold, latency stays in target, and operators explain every incident without guessing |
| 4. Offer a dedicated tier by policy and economics | Product management + platform operations; finance and security input | A dedicated option for customers whose regulatory, residency, workload or risk profile makes shared a poor fit, as a deliberate policy choice | The team can explain shared versus dedicated, and the cost and support implications of each |
- Gates between phases: identity and isolation clean → the suite passes consistently → latency and boundaries hold under real load → dedicated tier.
The source plan in weeks
| Weeks | Work |
|---|---|
| 0 to 1 | Name stakeholders, the dangerous failure and explicit exclusions |
| 1 to 2 | Internal tenants |
| 2 to 3 | The isolation suite |
| 3 to 4 | Hold promotion until it passes |
| 5 | Low-risk shared tenants under conservative quotas |
| 6 to 8 | Validate boundaries, latency and operator understanding |
- After the pilot, open the dedicated tier on measurable thresholds, not for whoever asks loudest.
Rollout is more than code promotion
- Canary: a tiny slice of low-risk traffic first.
- Rollback: to the prior configuration by tenant and region, with no data loss and no cross-tenant contamination of caches or data.
- Migration: moves tenant metadata, quotas and routing with validation at each step.
- Training: support and customer-facing teams fluent in the guarantees and the non-guarantees.
- Documentation: setup, limits, escalation paths, and what a quota error means.
- Audited admin actions and operator runbooks are part of delivery, not follow-up work.
Named ownership
| Owner | Owns |
|---|---|
| Platform engineering | Runtime and the predicates |
| Security | Isolation gates and boundary validation |
| SRE | Service health, failover and its rehearsals |
| Product | Tiering policy |
| Support | First-response triage |
Keep four kinds of thing apart
- Anything re-implemented per customer is a sign the platform is turning into a bundle of one-off projects.
| Kind | What it is | Examples |
|---|---|---|
| Configuration | Varies per customer without code | Quotas, region preferences, feature flags, retention, routing policy |
| Adapters | Absorb external variance | Identity providers, storage systems, logging sinks, approval workflows |
| Shared services | Expensive to rebuild, central to reuse | Tenant registry, policy enforcement, metering, audit, failover orchestration |
| Core product | Defines the platform | Isolation, admission, data access boundaries, observability primitives, internal APIs |
Risk register
| Risk | Owner | Mitigation | Trigger |
|---|---|---|---|
| Missing tenant predicate | Platform engineering | Negative tests, code review checklists | Any request reaching a non-tenant-scoped path |
| Cache bleed | SRE + platform engineering | Tenant-keyed cache design, namespace validation | Any cache hit crossing tenant boundaries |
| Misrouted regional traffic | Infra + security | Region-aware routing rules, deployment checks | A route sending protected data to an unauthorised region |
Name the failure conditions
- Cost went down but users don't adopt → not succeeded.
- Users adopt but support can't operate it → not succeeded.
- Fast but unable to prove tenant boundaries → not succeeded.
Quick Recall: Lines to Say in the Interview
- "The business result is a cost-efficient shared platform with defensible isolation, plus a dedicated path for the exceptions."
- "200 QPS across 500 tenants looks like 0.4 each, but 20x skew means a few tenants drive the peak."
- "The control plane decides; the data plane enforces."
- "Tenant context comes from verified identity, never the request body, and it is immutable."
- "The store refuses an unscoped read; a forgotten WHERE clause returns nothing."
- "A budget checked after the call is a bill, not a control."
- "Rate limits cap a tenant's own allotment; weighted fair queuing decides order under contention."
- "Security defects fail closed, capacity pressure degrades, metadata leaks quarantine."
- "One unexplained boundary failure halts promotion; the target is zero confirmed cross-tenant incidents."
Technical deep dives
What this part covers: the mechanisms behind the follow-up questions. Tenant context, row-level security, per-tenant keys, tenancy tiers, fair queuing, unit economics, offboarding, a real cross-tenant leak and the isolation test.
30-Second Cheat Sheet
- Authenticate before you authorise: signature, issuer, audience, expiry, then the tenant directory. Body
tenant_idand client headers are untrusted. - Four records, four boundaries:
Tenant,Membership,UsageLedger,AuditEvent. Writes need an idempotency key and optimistic concurrency. - RLS works only if the app role can't bypass it: non-owner, no superuser, no BYPASSRLS; FORCE for owners. The failure is "no data", never "all data".
- Envelope encryption: per-tenant data keys wrapped by a KMS master key. Crypto-shredding needs every decryption path gone, backups included.
- Tiers trade cost for separation; escalate on documented thresholds. Regulated industry alone doesn't force dedicated.
- Token bucket meters rate; weighted fair queuing schedules. Acme's 4 requests wait ~10 s behind Globex's 400 in FCFS, ~0.2 s with fair queues.
- Isolation pays only where required: $420 a month shared versus about $9,000 extra for dedicated (illustrative).
- The leak was an isolation failure, not a hallucination: filter v3 dropped tenant equality and a connector flag skipped the ACL.
1. Tenant context, authority and the data model
Authentication before authorisation
- Validate the token's signature, issuer, audience and expiry with the customer's IdP before any permission logic.
- The tenant directory then maps the verified principal to membership, allowed region and deployment posture.
- Customer-owned groups may sync through SCIM. A renamed group or drifting mapping can silently change who holds which role: alert on both.
Establish once, make immutable, propagate
- Just-in-time provisioning grants the minimum local role for that tenant on first sign-in.
- Untrusted: a
tenant_idin the request body, and any header the client sets rather than a trusted gateway. - Propagate the context to services, database sessions, cache helpers, queue messages, vector filters, inference and audit.
- "Immutable" = no downstream component can replace the tenant on the request object. A service that needs a different tenant must fail rather than rewrite it.
Four records, four ownership boundaries
| Record | Fields | Owns |
|---|---|---|
Tenant |
id, region, tier, key_ref, retention_policy |
Data ownership: placement, key and retention policy |
Membership |
user_id, tenant_id, role, status |
Authority: who may act for the tenant, and how |
UsageLedger |
tenant_id, period, tokens, requests, cost |
Commercial control: metering and attribution |
AuditEvent |
tenant_id, actor, action, resource, decision |
Defensibility: evidence that the control ran |
Two protections at every write boundary
| Protection | What it does |
|---|---|
| Idempotency key | Identifies the intended operation, so a retried request returns the original result instead of writing twice |
| Optimistic concurrency | Attaches an expected version to a write, so a concurrent writer's change causes a conflict instead of being silently overwritten |
- Model output never flows raw into the system: it's parsed into a typed schema and policy-checked before persistence or any downstream action.
2. Row-level security and the tenant predicate
Follow one query
- The app opens a database session and sets the verified tenant on it (for example a session variable holding
acme). - An RLS policy says rows are visible only when their
tenant_idequals that session value. - A developer writes a new report query and forgets
WHERE tenant_id = …. - The database applies the policy, so the query still returns only Acme's rows.
- If no tenant was set, the policy must fail closed: no rows or an error.
- The failure is "no data", never "all data".
Connection-pool rules
- Scope the tenant setting to the current transaction and clear it before a pooled connection is reused.
- Test Acme followed by Globex on the same connection.
- A session variable isn't authenticated by itself: untrusted SQL must not be allowed to replace it.
The precondition the source states precisely (PostgreSQL)
| Role | Subject to RLS? |
|---|---|
| Superuser | Never: always bypasses |
| BYPASSRLS role | Never: always bypasses |
| Table owner | Normally bypasses; FORCE ROW LEVEL SECURITY can subject it to the policy |
| Separate non-owner app role without bypass privileges | Yes |
- An app that connects as the table owner (a common development default) has silently switched the protection off.
- Connect as a separate non-owner role; use FORCE for owner coverage where required.
- Test row visibility and INSERT/UPDATE checks. A read-only test doesn't prove writes can't cross tenants.
Partitioning alone isn't isolation
- If one database credential can read every partition, a missing predicate still reads across them.
- Partitioning becomes an isolation layer only when each tenant's partition sits behind its own credentials.
The same predicate at every other layer
- Vector chunks get tenant metadata at ingestion; every query compiles a tenant filter; a final check compares request tenant with each chunk's tenant before prompt assembly.
- Cache keys carry tenant, permission signature and source or policy version, so a permission or content change can't replay an old entry.
- Queue and dead-letter envelopes carry tenant context.
- Logs omit raw prompts and secrets.
- The Enterprise Knowledge Assistant case's pre-filter plus authoritative post-check is the retrieval form of this rule. Tenant isolation must also cover every path that doesn't retrieve.
3. Per-tenant keys and envelope encryption
Two levels of key
KMS (key management service) = the service that stores and rotates encryption keys, so the wrapping key stays inside it.
- Each tenant's data is encrypted with that tenant's own data key.
- The data key is stored only wrapped (encrypted) by a master key held in the KMS.
- A conventional application may temporarily hold a plaintext data key while encrypting or decrypting. Minimise that lifetime and remove it from memory after use.
- To read Acme's data: a service asks the KMS to unwrap Acme's data key for an authorised request, then decrypts.
Three events traced through the design
| Event | Result |
|---|---|
| Raw read access to the storage layer | Ciphertext only: no data key is stored in plaintext |
| Acme's data key leaks | One tenant exposed, not the fleet |
| Acme leaves | Inventory plaintext and wrapped data-key copies, replicas, cached keys and exports before claiming cryptographic erasure |
- A per-tenant wrapping key with controlled deletion can make the remaining ciphertext unusable once every recovery path is gone.
- Deleting only the active wrapped-key row doesn't erase a backup that retains it under a usable shared master key.
- That distinction decides whether crypto-shredding actually occurred.
Compare one platform-wide key
- A single leaked key exposes every customer at once.
- There's no per-tenant way to make one customer's data unreadable.
- The master key still protects everyone in the envelope design, which is why it stays inside the KMS and never leaves it.
- For a dedicated tenant, the per-tenant key can be a customer-managed key, one of the triggers in the tiers deep dive.
4. Tenancy tiers and the dedicated threshold
- The three tiers trade cost for separation. The boundary moves from a database predicate, to a schema boundary in one cluster, to a separate deployment with its own region and keys.
| Tier | Acme's request | Boundary | Cost |
|---|---|---|---|
| Shared rows with database enforcement (default) | Acme's rows sit in the same tables as Globex's, tagged with tenant_id; the session carries acme; RLS returns only Acme's rows |
A predicate: strength depends on the database enforcing it and on the six other layers | Lowest; fastest to ship |
| Separate schema or namespace per tenant | Routed to the acme schema; database grants stop Acme's role reading Globex's tables |
Stronger, no second deployment | More objects to migrate and monitor per tenant |
| Dedicated cluster, region and keys | The regional scheduler routes to Acme's own deployment, sharing no database, cache or inference pool with Globex | Strongest | Most expensive: the isolation term is largest here |
- Schema caveat: a schema name or
search_pathsetting alone doesn't revoke cross-schema privileges. - Compute default (source's trade-off pairs): namespace isolation with strong network policy, admission control, resource quotas and service identity.
Escalate on documented thresholds, not size
- Triggers: residency rules, strict latency SLOs, contention the shared tier can't absorb, a customer policy that demands harder separation.
- The source's fact-check limits the regulated-industry argument:
- US Department of Health and Human Services guidance says HIPAA doesn't require single-tenant hosting.
HIPAA = the Health Insurance Portability and Accountability Act, the US law protecting health data.
- US banking regulators' third-party guidance is risk-based, not a single-tenant mandate.
- US Department of Health and Human Services guidance says HIPAA doesn't require single-tenant hosting.
- So regulated industry alone doesn't force the dedicated tier. A specific contract, risk assessment or residency rule does.
5. Admission, rate limits and weighted fair queuing
Two mechanisms, two jobs
| Mechanism | Job | How |
|---|---|---|
| Token bucket | Meters one tenant's rate | Holds up to B tokens, refills at r tokens per second; each request spends tokens; empty → delayed or rejected. B = burst, r = sustained rate |
| Weighted fair queuing | Schedules | One queue per tenant; the shared pool takes from queues in proportion to weights, not arrival order |
- RFC 2697 describes this kind of meter. The source's note: a token bucket meters rate, it doesn't schedule fairly.
- Demers, Keshav and Shenker's 1989 analysis is the classic description of fair queuing sharing a saturated resource proportionally.
The trace (illustrative, invented numbers)
- Assume equal-cost, non-blocking work units and a pool serving 40 requests per second.
- Globex submits 400 requests in one burst, all within its contractual quota. A moment later Acme submits 4.
| Scheduler | Acme's wait | Globex's burst |
|---|---|---|
| One FCFS queue | Behind all 400: about 10 seconds, although Acme exceeded nothing | Completes |
| Per-tenant queues, equal weights | Scheduler alternates; Acme's 4 served within roughly the first 8 slots, about 0.2 seconds | Completes at nearly the same time; the pool stays fully used |
- Rate limits alone couldn't do this, unless set so low that Globex's legitimate burst was refused.
- For LLM calls with unequal lengths: fair scheduling must account for estimated tokens or service work as well as request count, and bound non-preemptible long requests.
FCFS = first come, first served.
Reserved lanes and budgets before inference
- Reserved lanes: a slice of capacity held for contractual tiers, so a premium tenant's latency target survives contention without a dedicated cluster.
- Enforce token, concurrency, burst and monetary budgets before inference.
- Reserve, then reconcile:
- Atomically reserve an upper-bound charge from input size, output cap and allowed branch fan-out.
- Reconcile actual usage.
- Release the unused reservation.
- Concurrent calls must not each spend the same remaining balance.
- A post-call bill is not a budget gate.
- Attribute tokens, storage, retrieval, egress and reserved capacity per tenant in the usage ledger.
- Too tight → artificial failures. Too loose → one tenant's burst shifts onto its neighbours.
One high-usage tenant
- Segment by key, user, feature, time, prompt version, tokens per request, batch jobs and agent steps.
- Decide: healthy adoption, a loop, abuse or a missing quota.
- Healthy adoption → capacity planning.
- The others → throttle or pause, then add contract-aligned budgets and alerts.
6. Unit economics: when isolation pays
Three terms, three levers
C_tenant = C_fixed/N + C_usage + C_isolation
| Term | What changes it |
|---|---|
C_fixed/N |
Adding tenants shrinks it |
C_usage |
Model routing, caching and quotas |
C_isolation |
Tier choice |
Worked example (illustrative, invented figures)
| Item | Value |
|---|---|
| Shared platform cost | $60,000 a month |
| N | 500 tenants |
| Fixed share per tenant | $60,000 ÷ 500 = $120 |
| Typical tenant usage | $300 |
| Typical shared tenant total | $120 + $300 = $420 a month, no isolation premium |
| Dedicated cluster, own keys, regional duplication | Might add $9,000 of isolation cost, about twenty times the shared tenant's total |
| Fixed share at 5,000 tenants | $12, which widens the gap further |
- The lesson (the source's): pooled economics win when most tenants can share safely. The isolation premium is paid only where a requirement demands it, then priced into that tenant's contract.
- Use the equation to justify the dedicated threshold with numbers, never "big customers get dedicated".
7. Region, outage and offboarding contracts
Residency and retention
- Define policy centrally; enforce it regionally where feasible.
- A residency rule includes data, prompts, outputs, traces, logs, backups and derived indexes such as embeddings.
- Retention attaches to the tenant record or a versioned policy it references, not scattered service flags.
- Decide RPO and RTO per region before designing replication and failover routing.
Regional controller outage
- Safe reads may keep serving from valid local policy and preloaded keys.
- Sensitive changes fail closed.
- Work queued during the outage is reconciled after recovery against the authoritative policy source.
Export and deletion
- Inventory every tenant-owned surface: relational rows, objects, embeddings, caches, queues, logs, derived artifacts.
- A verified deletion job runs across that inventory, records completion and lists retention exceptions named up front.
Backups need honesty
- Erasure follows restore and retention semantics. Never claim an immediate surgical delete the backup design can't provide.
- UK ICO guidance (right to erasure): backups may be put "beyond use" until overwritten on schedule.
- GDPR Article 17 sets the erasure duty itself.
- Per-tenant keys strengthen the answer: verified destruction of every tenant decryption path can make remaining ciphertext unreadable before backups age out.
- Record pending KMS deletion separately from completed destruction, and clear cached plaintext keys.
- Neither a scheduled deletion nor one deleted database row proves immediate erasure.
8. Reading the cross-tenant retrieval leak
The setup
- Acme uses an enterprise support copilot over customer contracts, escalation policies and entitlements.
- The vector database stores chunks from several enterprise customers in one collection. Each chunk carries:
tenant_id,doc_tenant_id,visibility,source_connector,acl_hash,metadata_filter_version
- The intended invariant: request
tenant_idmatchesdoc_tenant_idon every retrieved chunk, and the ACL service authorises each chunk before it reaches the prompt.
ACL (access-control list) service = records who may read each resource.
The incident
- On 2026-07-08 an Acme support agent asked whether Acme customers could receive premium onboarding under the 2026 renewal terms.
- The assistant said yes and cited a "Premium Success Addendum" that belonged to Globex.
The source's telemetry
2026-07-08T09:12:44.129Z level=warn service=rag-api env=prod region=eu-central-1
trace_id=trc_7f91c2 request_id=req_acme_88421 query_id=q_20260708_091244_19
user_id=u_acme_support_044 tenant_id=acme user_role=support_agent
workflow=contract_entitlement_answer retriever_version=2026-07-07
metadata_filter_version=v3 filter_expression="visibility in ['public','internal']"
expected_filter_expression="tenant_id == 'acme' AND visibility in ['public','internal']"
2026-07-08T09:12:44.388Z level=info service=vector-retriever
trace_id=trc_7f91c2 collection=enterprise_contract_chunks index=contracts_hnsw_v22
retrieval_k=12 returned_k=12 top_score=0.81
retrieved_chunk_ids=[chk_globex_9921,chk_acme_1710,chk_acme_1709,chk_globex_9922]
retrieved_doc_ids=[doc_globex_renewal_2026,doc_acme_msa_2025]
doc_tenant_ids=[globex,acme,acme,globex]
2026-07-08T09:12:44.421Z level=error service=acl-enforcer
trace_id=trc_7f91c2 acl_check=skipped reason="pre_authorized_connector_flag=true"
connector=sharepoint connector_scope=tenant_shared acl_cache_key=acl:v2:sharepoint:contracts
request_tenant_id=acme doc_tenant_id=globex policy_decision=not_evaluated
2026-07-08T09:12:45.221Z level=error service=response-evaluator
trace_id=trc_7f91c2 eval=tenant_isolation_violation severity=critical
response_served=true citation_doc_id=doc_globex_renewal_2026 citation_chunk_id=chk_globex_9921
tenant_id=acme doc_tenant_id=globex human_review=false
Read the four lines as one trace (trace_id=trc_7f91c2)
| Line | Service | What it shows |
|---|---|---|
| 1 | rag-api |
Request correctly stamped tenant_id=acme, but filter v3 applied only visibility in ['public','internal']; the expected expression also had tenant_id == 'acme' |
| 2 | vector-retriever |
The consequence: doc_tenant_ids include globex twice |
| 3 | acl-enforcer |
Second layer fails: check skipped because pre_authorized_connector_flag=true, so policy_decision=not_evaluated |
| 4 | response-evaluator |
Critical isolation violation flagged only after response_served=true, citation pointing at the Globex renewal document |
The source's root cause
- A retrieval deploy on 2026-07-07 introduced filter version v3 to support global product documentation.
- The filter builder treated connector-level "pre-authorised" documents as safe and omitted the tenant equality predicate for one SharePoint collection.
- The ACL service then skipped chunk-level checks because it trusted the connector-level scope.
- The rollout reached 15% of Acme traffic at 08:45 on 2026-07-08, so the live filter version and canary cohort are part of the diagnosis.
- Two supposedly independent layers both trusted the same connector shortcut. That's exactly what the seven-layer independence rule exists to prevent.
A confidentiality incident, not a hallucination
- The model accurately summarised text it should never have received.
- So enforcement belongs outside the LLM and outside prompt instructions.
- With weak filters, a malicious user could deliberately query for rare phrases that retrieve neighbouring tenants' documents. No prompt wording would stop that.
- OWASP's guidance on vector and embedding weaknesses (LLM08:2025) lists this cross-tenant leak from missing vector access controls.
- The response, containment and prevention are worked as a drill in Practice (in the full casebook).
9. The interview-sized isolation test
What it proves
- One invariant at the API level, not only in the database: a secret created under one tenant is invisible to another, and the other tenant doesn't even learn it exists.
- 404, not 403, is the point: "forbidden" would confirm the ID is real.
import pytest
class TenantSession:
def __init__(self, tenant_id, store, next_id):
self._tenant_id = tenant_id
self._store = store
self._next_id = next_id
async def create_secret(self, value):
secret_id = str(self._next_id())
self._store[(self._tenant_id, secret_id)] = value
return type("Secret", (), {"id": secret_id})()
async def get_secret(self, secret_id):
if (self._tenant_id, secret_id) not in self._store:
return type("Response", (), {"status_code": 404})()
return type("Response", (), {"status_code": 200, "value": self._store[(self._tenant_id, secret_id)]})()
class FakeApi:
def __init__(self):
self._store = {}
self._next_id_value = 1
def _next_id(self):
current = self._next_id_value
self._next_id_value += 1
return current
def as_tenant(self, tenant_id):
if not tenant_id:
raise ValueError("tenant context required")
return TenantSession(tenant_id, self._store, self._next_id)
@pytest.mark.asyncio
async def test_cross_tenant_ids_are_invisible():
api = FakeApi()
created = await api.as_tenant("alpha").create_secret("A")
response = await api.as_tenant("beta").get_secret(created.id)
assert response.status_code == 404
Trace it
as_tenant("alpha")refuses to build a session without a tenant: it mirrors failing closed on missing context.- The store is keyed by the pair
(tenant_id, secret_id), so the tenant is part of the address, not a filter applied afterwards. - Alpha creates secret
1. - Beta asks for secret
1; the lookup key("beta", "1")doesn't exist, so beta gets 404.
- The IDs are sequential and shared, which makes the test meaningful: beta can guess alpha's ID and still learns nothing.
Say what it omits
- Authentication middleware, request signing, database transactions, observability hooks and retry wrappers are deliberately left out. Say so in the interview.
- It's one row of the adversarial suite. The full suite repeats the same shape for stale cache reads, replayed tokens, malformed filters, namespace collisions, missing predicates and cross-tenant vectors.
- Owner: security engineering.
10. References
What the references qualify
- PostgreSQL RLS, transaction-local settings, AWS data keys and KMS deletion support the specific claims beside them.
- The casebook doesn't assert anything newer about the products named.
Reference list
| Reference | What it supports |
|---|---|
| OWASP Authorization Cheat Sheet | Trust only verified tokens, claims or sessions, never client-set fields |
| New name for Azure Active Directory (Microsoft Learn) | Azure AD is now Microsoft Entra ID |
| PostgreSQL docs: Row Security Policies | Superusers and BYPASSRLS always bypass RLS; FORCE can subject the table owner to it |
| PostgreSQL RLS and transaction-local settings | The RLS and session-setting claims |
| AWS data keys and KMS deletion | Data-key and key-deletion claims |
| HHS: Guidance on HIPAA and Cloud Computing | HIPAA doesn't require single-tenant hosting |
| OCC Bulletin 2023-17: Interagency Guidance on Third-Party Relationships | Bank rules are risk-based, not a single-tenant mandate |
| AWS KMS cryptography essentials (envelope encryption) | What per-tenant data keys wrapped by a master key protect |
| Demers, Keshav, Shenker 1989: Analysis and Simulation of a Fair Queueing Algorithm | Fair queuing shares a saturated resource proportionally |
| RFC 2697: A Single Rate Three Color Marker | A token bucket meters rate; it doesn't schedule fairly |
| ICO: Right to erasure | Backups can be kept "beyond use" until overwritten on schedule |
| GDPR Article 17: Right to erasure | The erasure duty itself |
| OWASP GenAI LLM08:2025 Vector and Embedding Weaknesses | Cross-tenant leaks from missing vector access controls |
Quick Recall: Lines to Say in the Interview
- "Validate signature, issuer, audience and expiry before any permission logic runs."
- "A service that needs a different tenant must fail rather than rewrite it."
- "If the app connects as the table owner, RLS is silently off. Use a non-owner role and FORCE."
- "The failure is no data, never all data."
- "Deleting one wrapped-key row doesn't erase a backup that still holds it under a usable master key."
- "A token bucket meters rate; weighted fair queuing schedules. Acme waits 0.2 seconds, not 10."
- "Regulated industry alone doesn't force dedicated; a contract, risk assessment or residency rule does."
- "The leak was a confidentiality incident, not a hallucination: two layers trusted the same connector shortcut."
- "404, not 403, so the other tenant doesn't even learn the ID exists."
Quick review
One sentence: derive tenant context from verified identity once; enforce it independently everywhere; meter before LLM inference.
30-Second Cheat Sheet
- The rule: verify the tenant once, enforce it at seven independent layers, meter before the call.
- Planes: the control plane decides policy, region, tier, keys and budgets; the data plane enforces scope at every store and inference boundary.
- Seven layers: row, object, cache, queue, log, vector index, key.
- Numbers (illustrative): 500 tenants, 50k users, 200 QPS peak, 20x skew; 0.4 QPS mean per tenant hides concentration.
- Fairness: token bucket caps rate, weighted fair queuing decides order, reserved lanes protect contracts.
- Failure defaults: security defects fail closed, capacity degrades, metadata leaks quarantine.
- Leak drill: filter v3 dropped tenant equality and a connector flag skipped the ACL. An isolation failure, not a hallucination.
- Release: adversarial isolation suite; zero confirmed cross-tenant incidents; internal tenants first, dedicated tier last.
1. The rule and the request flow
The rule
- Derive tenant context from verified identity once; enforce it independently everywhere; meter before LLM inference.
- Control plane decides tenant policy, region, tier, keys and budgets.
- Data plane enforces scope at every store and inference boundary.
The flow
verified IdP → tenant directory → immutable context → policy and allowed region → pre-call quota → tenant-scoped stores and retrieval → chunk-tenant post-check → LLM inference → typed output check → audit and usage
- The platform hosts assistants and bounded agents. Their plans, prompts, tools, caches and traces inherit tenant context.
- Model output can't establish identity or authority.
Ask first
- Data classes in scope?
- Residency for data, logs and backups?
- Shared versus dedicated exceptions?
- Peak skew and per-tenant SLO?
- Federated identity and keys?
- Contractual budgets?
- Verified export and deletion?
- Audit evidence?
2. Seven layers, numbers and the tier trade-off
Seven layers
Row · object · cache · queue · log · vector index · key
| Layer | The rule to say |
|---|---|
| Row | The store refuses an unscoped read through RLS, with an app role that is not owner, superuser or BYPASSRLS |
| Vector index | Scoped at ingest, at query and at final context assembly |
| Cache | Key includes tenant, permission signature and version |
| Key | Per-tenant data keys under a KMS master key: storage access yields ciphertext; crypto-shredding needs verified destruction of every decryption path |
Numbers (illustrative sizing)
| Item | Current | At 10x |
|---|---|---|
| Tenants | 500 | 5,000 |
| Active users | 50k | |
| Peak | 200 QPS | 2,000 QPS |
| Skew | 20x | |
| Strategy | pooled plus quotas | partitioning replaces pooled-plus-quotas |
- A mean of 0.4 QPS per tenant hides concentration.
- Cost:
C_tenant = C_fixed/N + C_usage + C_isolation.
The tier trade-off
shared enforced rows (default) → separate namespace → dedicated region, cluster and keys
- Escalate when risk, residency, SLO or contention justifies it, on measurable thresholds.
Rate, order, contracts
- Rate limits cap a tenant's own usage with a token bucket.
- Weighted fair queuing decides order under contention.
- Reserved lanes protect contracts.
- Budgets are checked before the call.
3. Failure defaults and the leak drill
Failure defaults
| Trigger | Default |
|---|---|
| Missing predicate or mismatched retrieved chunk | Fail closed, audit, stop the path |
| Cross-tenant cache hit | Security incident; disable, purge, inspect the served window |
| Queue leaks metadata | Quarantine, investigate, rotate credentials if needed |
| One tenant over quota | Degrade that tenant; the fair queue protects others |
| Policy or key unavailable | Block the protected operation |
| Regional control outage | Safe local-policy reads only; queue or block sensitive changes |
- The pattern: security defects fail closed, capacity pressure degrades, metadata leaks quarantine.
- The drill: detect → refuse and log → contain → recover → prevent.
The leak drill
- What happened: an Acme request cited a Globex document, because filter v3 dropped tenant equality and a connector flag skipped the ACL.
- Respond:
- Roll back v3.
- Purge caches.
- Block mismatched chunks.
- Search mismatch traces.
- Notify the customer.
- Prevent:
- a non-bypassable predicate
- a post-retrieval check
- a negative release gate
- It's an isolation failure, not a model hallucination.
4. Release, rollout and the closing lines
Release gate
- An adversarial isolation suite passes.
- Any unexplained boundary failure blocks promotion.
- Confirmed cross-tenant incident target: zero.
- Track separately: per-tenant p95, quota rejections, cost per tenant, isolation-test pass rate, regional failover time.
Rollout
internal tenants → adversarial suite → small shared tenants on conservative quotas → policy-justified dedicated tier
- Each phase has an owner, a go/no-go and rollback by tenant and region.
Lines that carry the round (from the source)
- "Tenant context comes from verified identity, never the request body, is established once, and becomes immutable."
- "The control plane decides; the data plane enforces."
- "Seven layers enforce independently, so one missed check is not a breach."
- "A missing tenant predicate fails closed. It never reads whatever matches."
- "The store refuses to return a row unless the request is already tenant-scoped."
- "Security defects fail closed; capacity pressure degrades; metadata leaks quarantine."
- "Size for the load shape, not the average. 20x skew means a few tenants drive peak."
- "Pay the isolation premium only where a requirement demands it."
- "A cache hit across tenants is a security incident, not a performance bug."
- "Blast radius is the design unit."
Closing line: success is adoption, an improved workflow and an operations team that can support the platform, with tenant boundaries it can prove.
Flashcard Drill
Quick Recall: Lines to Say in the Interview
- "Verify the tenant once, enforce it everywhere, meter before the call."
- "Row, object, cache, queue, log, vector index, key."
- "500 tenants, 200 QPS at peak, 20x skew: the 0.4 average hides the shape."
- "Token bucket for rate, weighted fair queuing for order, reserved lanes for contracts."
- "Fail closed on security, degrade on capacity, quarantine metadata leaks."
- "Filter v3 dropped tenant equality and a connector flag skipped the ACL: isolation failure, not hallucination."
- "One unexplained boundary failure blocks promotion."
- "Blast radius is the design unit."
Where next
- Practise this as a worksheet
- Secure Multi-Tenant AI Platform
- Revise the concepts