AiCredits
Tenant Isolation

Multi-Tenant API Keys: Isolating Usage Per Customer Safely

Build multi-tenant API keys that isolate every customer safely: hashed tenant keys, per-tenant token budgets, rate caps, and metered DeepSeek calls.

Published 2026-11-28 Updated 2026-11-28 9 min

The shortcut that ends in an incident

Most teams start by holding one provider key in the backend and letting every customer hit the same endpoint. That works until a customer's key leaks, one tenant burns the month's budget in an hour, or support can't tell which account made 40,000 calls overnight.

The fix isn't a bigger rate limit. It's a tenant layer: your own key format, your own usage ledger, your own limits, with a single upstream credential that never leaves your server.

Rule one: tenants never touch your AiCredits key

Your AiCredits key is an account credential, not a product credential. It pays for everything, so if it appears in a browser bundle, a mobile binary, a support ticket, or a stack trace, the blast radius is your entire balance.

Tenants get keys you minted yourself, prefixed sk_tenant_ and stored as SHA-256 hashes. The upstream key lives in an environment variable or secret manager and is referenced only by the process that calls https://api.aicreditsapi.com/v1.

Mint, hash, and revoke tenant keys

# tenants.py — key issuance and lookup (Python 3.10+)
import hashlib, secrets, sqlite3, time

DB = "tenants.db"

SCHEMA = """
CREATE TABLE IF NOT EXISTS tenants (
    tenant_id            TEXT PRIMARY KEY,
    name                 TEXT NOT NULL,
    plan                 TEXT NOT NULL DEFAULT 'standard',
    key_hash             TEXT NOT NULL UNIQUE,
    key_prefix           TEXT NOT NULL,
    monthly_token_budget INTEGER NOT NULL,
    tokens_used          INTEGER NOT NULL DEFAULT 0,
    created_at           INTEGER NOT NULL,
    revoked_at           INTEGER
);
CREATE TABLE IF NOT EXISTS usage_events (
    id                INTEGER PRIMARY KEY AUTOINCREMENT,
    tenant_id         TEXT NOT NULL,
    model             TEXT NOT NULL,
    prompt_tokens     INTEGER NOT NULL,
    completion_tokens INTEGER NOT NULL,
    request_id        TEXT NOT NULL,
    created_at        INTEGER NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_usage_request
    ON usage_events (tenant_id, request_id);
"""

def init_db() -> None:
    con = sqlite3.connect(DB)
    con.executescript(SCHEMA)
    con.commit()
    con.close()

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

def issue_key(tenant_id, name, monthly_token_budget, plan="standard"):
    raw_key = "sk_tenant_" + secrets.token_urlsafe(32)
    con = sqlite3.connect(DB)
    con.execute(
        "INSERT INTO tenants (tenant_id, name, plan, key_hash, key_prefix,"
        " monthly_token_budget, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
        (tenant_id, name, plan, _hash(raw_key), raw_key[:16],
         monthly_token_budget, int(time.time())),
    )
    con.commit()
    con.close()
    return raw_key  # hand to the customer once; never store or log it

def resolve_tenant(raw_key):
    con = sqlite3.connect(DB)
    con.row_factory = sqlite3.Row
    row = con.execute(
        "SELECT * FROM tenants WHERE key_hash = ? AND revoked_at IS NULL",
        (_hash(raw_key),),
    ).fetchone()
    con.close()
    return row

def revoke_key(tenant_id) -> None:
    con = sqlite3.connect(DB)
    con.execute("UPDATE tenants SET revoked_at = ? WHERE tenant_id = ?",
                (int(time.time()), tenant_id))
    con.commit()
    con.close()
  • Return the raw key exactly once. There is no "show key again" button worth the risk; offer rotation instead.

  • Keep the first 16 characters in plaintext as key_prefix so support can identify a key from a screenshot without ever seeing the secret.

  • Look keys up by hash index. Comparing raw keys in application code invites timing side channels and accidental logging.

  • Give every tenant a revoked_at column and a rotation path: issue new, overlap for a short window, revoke old.

  • Scope keys by purpose (chat, embeddings, admin) if one customer can run several integrations.

Meter at the response, not at the request

You cannot know token cost before the call. Read response.usage after each completion and write an append-only usage event; treat any tokens_used column as a cache you can rebuild from events.

Check the budget before dispatch so you fail fast, and record the actual charge after so two concurrent requests can't silently blow past the ceiling. If you need hard guarantees, reserve an estimate inside a transaction, then reconcile to actual usage.

# app.py — one metered, budget-checked endpoint
import os, sqlite3, time
import openai
from fastapi import FastAPI, Header, HTTPException
from tenants import DB, resolve_tenant

app = FastAPI()
client = openai.OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
    timeout=60.0,
)

def charge(tenant_id: str, request_id: str, usage) -> None:
    con = sqlite3.connect(DB)
    cur = con.execute(
        "INSERT OR IGNORE INTO usage_events (tenant_id, model, prompt_tokens,"
        " completion_tokens, request_id, created_at) VALUES (?, ?, ?, ?, ?, ?)",
        (tenant_id, "deepseek-v4-flash", usage.prompt_tokens,
         usage.completion_tokens, request_id, int(time.time())),
    )
    if cur.rowcount:  # idempotent: a retried request_id is not billed twice
        con.execute(
            "UPDATE tenants SET tokens_used = tokens_used + ? WHERE tenant_id = ?",
            (usage.total_tokens, tenant_id),
        )
    con.commit()
    con.close()

@app.post("/v1/chat")
def chat(body: dict, authorization: str = Header(...)):
    tenant = resolve_tenant(authorization.removeprefix("Bearer ").strip())
    if tenant is None:
        raise HTTPException(status_code=401, detail="invalid or revoked key")
    if tenant["tokens_used"] >= tenant["monthly_token_budget"]:
        raise HTTPException(status_code=429, detail="token budget exhausted")
    messages = body.get("messages")
    if not messages:
        raise HTTPException(status_code=400, detail="messages required")

    completion = client.chat.completions.create(
        model="deepseek-v4-flash",
        messages=messages,
        max_tokens=min(int(body.get("max_tokens", 512)), 1024),  # your cap, not theirs
        user=tenant["tenant_id"],  # tags upstream abuse reports to one tenant
    )
    charge(tenant["tenant_id"], completion.id, completion.usage)
    return {
        "id": completion.id,
        "content": completion.choices[0].message.content,
        "tokens_used": completion.usage.total_tokens,
    }

Rate-limit per tenant, not globally

A global rate limit means your loudest customer sets the ceiling for everyone else. Per-tenant buckets keep one integration from starving the rest.

# limits.py — token bucket per tenant
import time

class Bucket:
    def __init__(self, rate: float, burst: int):
        self.rate, self.burst = rate, burst
        self.tokens, self.updated = float(burst), time.monotonic()

    def allow(self) -> bool:
        now = time.monotonic()
        self.tokens = min(self.burst, self.tokens + (now - self.updated) * self.rate)
        self.updated = now
        if self.tokens >= 1:
            self.tokens -= 1
            return True
        return False

_buckets: dict[str, Bucket] = {}

def check_rate(tenant_id: str, rate: float = 2.0, burst: int = 5) -> bool:
    return _buckets.setdefault(tenant_id, Bucket(rate, burst)).allow()

This in-process bucket is fine for a single worker. With multiple workers or replicas, move the counter to Redis and decrement atomically, otherwise each process grants the full burst and your real limit is burst × workers.

Cap in-flight concurrency per tenant as well — a semaphore around the upstream call stops one customer from queueing hundreds of parallel completions behind your shared connection pool.

Streaming breaks naive metering

# streaming.py — meter the final chunk
import os
import openai
from billing import charge  # the charge() function from the example above

client = openai.OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

def stream_reply(tenant_id: str, messages: list):
    stream = client.chat.completions.create(
        model="deepseek-v4-flash",
        messages=messages,
        stream=True,
        stream_options={"include_usage": True},
    )
    for chunk in stream:
        if chunk.usage:  # final chunk carries the totals
            charge(tenant_id, chunk.id, chunk.usage)
        if chunk.choices and chunk.choices[0].delta.content:
            yield chunk.choices[0].delta.content

If the client disconnects mid-stream you still paid for what was generated. Log the disconnect as an unmetered request against that tenant and rate-limit repeated disconnects, otherwise a reconnect loop becomes free compute on your balance.

Never let the client choose the model

If the request body contains a model field, some tenant will eventually send the most expensive name they can guess. Resolve the model server-side from their plan and ignore whatever the client sent.

# model_tiering.py
TIER_MODELS = {
    "standard": "deepseek-v4-flash",
    "premium": "deepseek-v4-pro",
}

def model_for(tenant) -> str:
    return TIER_MODELS.get(tenant["plan"], "deepseek-v4-flash")

deepseek-v4-flash is the sensible default for interactive tenant traffic; deepseek-v4-pro costs more and belongs to tiers that pay for the extra capability. Pair the mapping with a hard max_tokens ceiling so a single request can't consume a meaningful slice of a tenant's monthly budget.

Isolation checklist

LayerWhat you isolateIf you skip it
CredentialOne key per tenant, SHA-256 at rest, prefix shown in UIOne leak burns every customer at once
BudgetAppend-only usage ledger per tenantA single tenant can eat your margin for the month
ThroughputRequests/sec and in-flight calls per tenantYour loudest customer sets latency for everyone
ModelPlan → model mapping resolved server-sideTenants self-upgrade to the pro model on your bill
AuditRequest id, tenant id, key prefix, timestampNo trail when abuse or a billing dispute appears
Revocationrevoked_at flag with an overlap window on rotationA compromised key stays live until you redeploy

The most expensive multi-tenant bug is the call path you forgot to meter. Count every route that reaches the provider, including retries, batch jobs, and internal admin tools.

Where AiCredits fits

Your tenant layer needs exactly one upstream credential per environment — dev, staging, production — so a leaked staging key can't touch production traffic. AiCredits issues keys that work internationally with a card or PayPal, no Chinese phone number or bank account required, which matters when your own customers are global and onboarding shouldn't gate your launch.

On cost: flash is the cheaper default, pro costs more, and cache hits and off-peak traffic cost less than cold peak calls. Check aicreditsapi.com/deepseek-prices for current rates, then size each tenant's budget from your own ledger rather than a guess.

FAQ

Should each customer get their own AiCredits key?

Usually no. One upstream key per environment plus a tenant ledger is simpler to monitor and rotate. Split upstream keys when you need hard blast-radius separation or separate accounting entities — for example, keeping a staging key that can never reach production.

Can I store tenant keys encrypted instead of hashed?

Only if you must show the key back to the customer, which you shouldn't. Encryption adds a key-management problem and a decryption path an attacker can target; a hash makes lookup one-way and leaks nothing useful.

How do I avoid double-charging on retries?

Send a client-supplied idempotency key, store the upstream request id with the usage event, and add a UNIQUE index on (tenant_id, request_id). The INSERT OR IGNORE pattern above then makes retries free.

Does this pattern work with OpenAI or OpenRouter?

Yes. Only the base_url and model name change; the tenant layer lives entirely on your side, which is exactly why it's worth building once and reusing.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer 🔒Security Scan

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×