🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Multi-Tenant AI: Isolation, Routing and Cost Control

đŸŸĸ Free Lesson

Multi-Tenant AI

Prerequisites

  • !HTTP APIs and bearer-token authentication
  • !How LLM inference is metered in tokens
  • !Relational schema design basics

What You'll Learn

  • 1Pick a pooled, siloed or dedicated isolation model by reasoning about blast radius versus cost
  • 2Resolve a trusted tenant identity on every request and never accept a tenant claim from the request body
  • 3Enforce per-minute and per-day budgets with a token bucket that runs before generation starts
  • 4Attribute every token of spend to the correct account so billing and anomaly alerts work

A request lands and nothing on the stack knows whose it is

Northwind Support ships an AI-drafted reply feature to twelve business customers. There is one provider key, one conversations table, and one worker queue. Then a gaming customer runs a launch promotion and pushes forty requests per second through the shared queue. Response time for a clinic customer climbs from 700 ms to nine seconds, and when an engineer dumps recent rows to debug the spike, clinic notes sit next to game chat logs in the same result set.

Two failures are wearing one costume here. The first is missing tenant identity: nothing carried the customer's identity from the API key through the queue into the completion call and the usage ledger. The second is missing resource boundaries: one customer's burst consumed the capacity another customer had already paid for. Multi-tenancy in AI systems is the craft of fixing both, and it is decided at four layers — identity, data, compute, and money — long before anyone writes a prompt.

Isolation models and their blast radius

Every multi-tenant design is a point on the same spectrum: how much does one customer break, and how much does the isolation cost?

ModelWhat is sharedBlast radiusRelative costTypical buyer
Pooled, row-level tenancyModel, queue, databaseAll tenants at once1×Self-serve SMB SaaS
Shared compute, siloed dataInference workers, index namespaceAvailability only, not data1.2–1.5×Most RAG products
Dedicated deploymentNothingSingle tenant5–20×Healthcare, finance, government
Pooled with warm spareModel weights, spare capacityRegional incident1.5–3×Tiered enterprise plans

The economics work against perfect isolation: cost rises close to linearly while risk falls far more slowly, because a pooled platform with strong identity and encryption already removes most of the damage path. The practical answer for nearly every startup is a pooled default plus a documented silo escape hatch — a configuration flag that provisions a dedicated deployment when a contract requires it, rather than a second codebase written under deadline pressure.

Resolving the tenant before the model runs

Tenant identity must be derived server-side from a credential you can verify, then attached to the request as context that downstream stages cannot rewrite.

python
import hashlib
import time
from dataclasses import dataclass


@dataclass(frozen=True)
class TenantConfig:
    tenant_id: str
    plan: str
    model_tier: str          # "fast" | "balanced" | "frontier"
    rpm_limit: int
    daily_token_limit: int
    data_region: str
    siloed: bool = False


class TenantResolver:
    """Maps a bearer key to a trusted tenant configuration."""

    def __init__(self, db, cache_ttl: int = 60):
        self.db = db
        self.cache = {}
        self.cache_ttl = cache_ttl

    @staticmethod
    def key_hash(raw_key: str) -> str:
        return hashlib.sha256(raw_key.encode("utf-8")).hexdigest()

    def resolve(self, authorization: str) -> TenantConfig:
        if not authorization.startswith("Bearer "):
            raise PermissionError("missing bearer token")
        raw = authorization.removeprefix("Bearer ").strip()
        digest = self.key_hash(raw)

        cached, loaded_at = self.cache.get(digest, (None, 0))
        if cached and time.time() - loaded_at < self.cache_ttl:
            return cached

        row = self.db.execute(
            "SELECT t.id, t.plan, t.model_tier, t.rpm_limit, "
            "       t.daily_token_limit, t.data_region, t.siloed "
            "  FROM api_keys k JOIN tenants t ON t.id = k.tenant_id "
            " WHERE k.key_hash = %s AND k.revoked_at IS NULL",
            (digest,),
        ).fetchone()
        if row is None:
            raise PermissionError("unknown or revoked key")

        cfg = TenantConfig(*row)
        self.cache[digest] = (cfg, time.time())
        return cfg

Four properties matter more than the code itself. The configuration is read from your database, so a client cannot claim a higher plan by editing a header. Revocation takes effect within one cache TTL instead of requiring a deploy. The siloed and data_region fields give the router real branching material later in the pipeline. And because the resolver runs once at the edge, every later stage reads the same frozen object rather than re-deriving identity from a user-supplied field.

âš ī¸Never trust a tenant claim in the body

If your completion endpoint accepts tenant_id as JSON, any caller can bill their work to a competitor or read another customer's conversation history. Derive identity from the credential only, and pass it server-to-server.

Where the data actually gets separated

Identity tells you who is calling; it does not by itself keep one customer's corpus out of another's answers. Separation happens at three storage layers, and each one needs an explicit decision.

Documents and conversation history sit in a shared relational table, so isolation is enforced by the query layer. Row-level security policies are the reliable option because the constraint lives in the database and survives every new endpoint your team writes; a WHERE tenant_id = $1 sprinkled through application code works until the one handler that forgets it ships on a Friday.

Vector indexes need a namespace decision. A shared index with a tenant filter has cheaper operations and one index to tune, but a bad filter becomes a data leak with plausible deniability. A namespace or collection per tenant costs more memory and complicates recall comparisons, yet makes deletion a drop operation — which is exactly what a GDPR erasure request needs.

Model weights and adapters are the third layer. Almost every platform shares base weights, and that is fine: weights memorise style, not customer records, as long as you are not fine-tuning on a tenant's private data with a low epoch count. When a contract forbids shared training entirely, the siloed flag from the resolver is what routes that tenant to its own deployment.

Rate limits that hold when a tenant bursts

Two counters are needed, because they catch different failures: a short burst of requests and a long slow drain of tokens. A token bucket handles the first; a daily ledger handles the second. Crucially, both run before generation, so you never produce a bill you cannot charge.

python
import time


class TokenBucket:
    def __init__(self, capacity: int, refill_per_sec: float):
        self.capacity = capacity
        self.refill = refill_per_sec
        self.tokens = float(capacity)
        self.updated = time.monotonic()

    def allow(self, cost: int) -> bool:
        now = time.monotonic()
        self.tokens = min(
            self.capacity,
            self.tokens + (now - self.updated) * self.refill,
        )
        self.updated = now
        if self.tokens < cost:
            return False
        self.tokens -= cost
        return True


def preflight(cfg: TenantConfig, bucket: TokenBucket,
              spent_today: int, prompt_tokens: int, max_tokens: int):
    if not bucket.allow(1):
        return False, "429: per-minute request limit reached", 30
    projected = spent_today + prompt_tokens + max_tokens
    if projected > cfg.daily_token_limit:
        return False, "402: daily token budget exhausted", None
    return True, "ok", None

Estimate the prompt with your tokenizer and add the requested max_tokens; that projected number is what you reserve. Return Retry-After with the 429 so a well-behaved client backs off instead of hammering you, and return 402 rather than silently degrading quality — a customer who hits a hard cap should learn about it from the invoice screen, not from truncated answers.

Routing each tenant to the right model

Pricing tiers only mean something if the tier selects infrastructure. Keep the mapping in data, not scattered through handlers, so a plan change is a row update rather than a release.

python
ROUTING_TABLE = {
    "fast":     {"model": "gpt-4o-mini", "max_tokens": 1024, "timeout_s": 15},
    "balanced": {"model": "gpt-4o",      "max_tokens": 4096, "timeout_s": 45},
    "frontier": {"model": "gpt-4.1",     "max_tokens": 8192, "timeout_s": 90},
}


def pick_route(cfg: TenantConfig, prompt_tokens: int, deadline_ms: int) -> dict:
    route = dict(ROUTING_TABLE[cfg.model_tier])
    if cfg.siloed:
        route["endpoint"] = f"https://{cfg.data_region}.inference.internal"
    if deadline_ms < 2000:
        # Degrade deliberately instead of timing out at the edge.
        route["model"] = "gpt-4o-mini"
        route["downgraded"] = True
    if prompt_tokens > 100_000:
        route["needs_long_context"] = True
    return route

Downgrading under a deadline is a design decision, not a bug, but it must be visible: set a downgraded flag, log it, and surface it to support. A customer told "we served your summarisation request on the fast model to meet your 2-second SLA" forgives a rougher answer; the same answer arriving without explanation reads as an outage.

Charging every token back to the right account

Without a ledger, multi-tenancy is a hobby. Record usage at the moment of generation, in an append-only table keyed by tenant, and reconcile it daily against the provider invoice.

python
PRICING = {  # USD per 1M tokens: (input, output)
    "gpt-4o-mini": (0.15, 0.60),
    "gpt-4o":      (2.50, 10.00),
    "gpt-4.1":     (2.00, 8.00),
}


def record_usage(cfg: TenantConfig, model: str, usage, ledger) -> float:
    pin, pout = PRICING[model]
    cost = (usage.prompt_tokens * pin + usage.completion_tokens * pout) / 1_000_000
    ledger.insert(
        tenant_id=cfg.tenant_id,
        model=model,
        prompt_tokens=usage.prompt_tokens,
        completion_tokens=usage.completion_tokens,
        cost_usd=round(cost, 6),
        ts=time.time(),
    )
    return cost

Two alerts pay for the whole table. First, compare each tenant's daily cost against its own trailing median; a three-fold jump usually means a runaway agent loop, a leaked API key, or a crypto-mining freeloaders' script. Second, reconcile ledger totals against the provider invoice weekly — drift means you are either eating cost or overcharging, and both become harder to fix the longer they run.

Noisy neighbours and graceful degradation

Load shedding is part of the isolation story. Watch queue depth and p95 latency per tenant, and when the pool saturates, shed by plan tier rather than first-come-first-served: a free tenant should wait before an enterprise tenant. Keep a circuit breaker around each provider so a regional outage parks traffic on a backup endpoint instead of exhausting your retry budget. For siloed tenants, pre-warm a spare deployment on a schedule rather than on the call that a sales demo depends on. Finally, rehearse the failure: replay one tenant's burst in staging and confirm the others' latency stays flat, because isolation you have never tested is a diagram, not a property.

Common Mistakes

Reading tenant_id from the request body or a JWT the client signed themselves

Fix: Resolve the tenant from a server-held API key hash and attach it as trusted request context

Applying only a requests-per-minute limit while ignoring token spend

Fix: Reserve prompt plus max_tokens against a daily budget before generation starts

Writing usage rows with no per-tenant key or no reconciliation

Fix: Append immutable usage records keyed by tenant and reconcile against the provider invoice weekly

Building a separate codebase for enterprise isolation

Fix: Ship pooled with a silo flag so a contract can trigger dedicated provisioning without a rewrite

Best Practices

  • Keep tenant configuration in one immutable object created at the edge and threaded through every stage
  • Store routing tables and pricing as versioned data so plan changes never require a deploy
  • Shed load by plan tier and expose a Retry-After header whenever you return 429
  • Alert on a tenant's cost versus its own trailing median, not just on absolute spend
  • Chaos-test a single tenant's burst in staging and assert the others' p95 latency stays flat

Key Takeaways

  • Tenant identity must be derived from a verifiable credential at the edge and passed downstream as trusted context — never taken from the request body
  • Isolation is a blast-radius-versus-cost dial: pooled with a silo escape hatch beats a second codebase for almost every team
  • Reserve prompt tokens plus max_tokens against both a short-bucket and a daily budget before you generate anything
  • Routing and pricing belong in versioned data tables, so a plan change is a row update instead of a release
  • An append-only per-tenant usage ledger with invoice reconciliation turns token spend into a billable, alertable signal
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement