C.W.K.
Stream
Lesson 05 of 05 · published

Multi-Tenant Isolation

~20 min · ops, multi-tenant, security

Level 0Scout
0 XP0/41 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Three patterns, three risk profiles

1. Collection-per-tenant

Each tenant gets their own Chroma collection or pgvector table. Strongest isolation; can become operationally heavy with thousands of tenants.

2. Shared collection + tenant_id metadata

One big collection, every chunk has metadata.tenant_id, every query includes where={tenant_id}. Cheap, scales to millions of tenants, but a missing filter leaks across tenants. Test rigorously.

3. Schema-per-tenant (pgvector)

Use Postgres schemas to namespace tenants. Single connection pool, but cleaner isolation than the metadata pattern. Use search_path to scope queries automatically.

The contract that prevents leaks

Wrap retrieval in a function that requires a tenant_id parameter. No code path can call the retriever without one. The compiler enforces what code review will eventually miss.

Code

Tenant-required retrieval contract (Python type hints)·python
from typing import NewType

TenantId = NewType('TenantId', str)

def retrieve(question: str, tenant_id: TenantId, k: int = 5):
    return collection.query(
        query_embeddings=[embed(question)],
        n_results=k,
        where={'tenant_id': {'$eq': tenant_id}},
    )
pgvector schema-per-tenant·sql
CREATE SCHEMA acme;
CREATE TABLE acme.chunks (LIKE public.chunks INCLUDING ALL);

-- Per-request:
SET search_path = acme, public;
SELECT id, text FROM chunks ORDER BY embedding <=> $1 LIMIT 5;

External links

Exercise

Pick the multi-tenant pattern that fits your scale (1 — collection-per, 2 — metadata, 3 — schema-per). Implement it. Write the cross-tenant leakage test. Run it. If it passes, your isolation works.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.