agentleFS
camilooscargbaptistacamilooscargbaptista/cto-toolkit/multi-tenancy/SKILL.md

multi-tenancy

Skill9 starsChanged 8 months agoMITView on GitHub

Multi-tenant architecture patterns: row-level, schema-level, database-level isolation and tenant routing

6 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use accessibility and api-design.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • MicrosoftSkill

    accessibility

    Consolidated accessibility skill entrypoint for WCAG 2.2, ARIA Authoring Practices, cognitive accessibility, Section 508, EN 301 549, design intent verification, and the Accessibility Planner workflow.

    Also in 3 projects that use this

  • MicrosoftSkill

    api-design

    Guide for designing and documenting RESTful APIs. Use when asked to design an API, create endpoints, or document an API.

    Also in 3 projects that use this

The file

Files
SKILL.md

Multi-Tenancy Patterns

When to Use

  • Building SaaS that serves multiple organizations/clients
  • Designing data isolation between tenants (companies, stations, fleets)
  • Choosing the right isolation level for your compliance needs

Isolation Models

1. Row-Level (Shared Everything)

┌──────────────────────────────┐
│         Single Database       │
│  ┌────────────────────────┐  │
│  │     users table         │  │
│  │  tenant_id │ name       │  │
│  │  ──────────┼──────────  │  │
│  │  company_a │ Alice      │  │
│  │  company_b │ Bob        │  │
│  └────────────────────────┘  │
└──────────────────────────────┘

Pros: Simple, cheap, easy to maintain
Cons: Risk of data leakage, shared resources
Best for: Small/medium SaaS, cost-sensitive

Implementation — TypeORM Global Scope:

// Middleware injects tenant
@Injectable()
export class TenantMiddleware implements NestMiddleware {
  use(req: AuthRequest, res: Response, next: NextFunction) {
    req.tenantId = req.user?.companyId;
    next();
  }
}

// Repository automatically filters by tenant
@Injectable()
export class TenantAwareRepository<T> {
  constructor(private repo: Repository<T>) {}

  findAll(tenantId: string): Promise<T[]> {
    return this.repo.find({ where: { tenant_id: tenantId } as any });
  }

  // CRITICAL: NEVER allow findAll without tenantId
}

// Global subscriber (safety net)
@EventSubscriber()
export class TenantSubscriber implements EntitySubscriberInterface {
  afterLoad(entity: any) {
    // Verify tenant match on every load (paranoia mode)
  }
  
  beforeInsert(event: InsertEvent<any>) {
    // Auto-inject tenant_id
    if (event.entity && !event.entity.tenant_id) {
      event.entity.tenant_id = getCurrentTenantId();
    }
  }
}

2. Schema-Level (Shared Database, Separate Schemas)

┌──────────────────────────────┐
│         Single Database       │
│  ┌──────────┐ ┌──────────┐  │
│  │ schema_a  │ │ schema_b  │  │
│  │  users    │ │  users    │  │
│  │  orders   │ │  orders   │  │
│  └──────────┘ └──────────┘  │
└──────────────────────────────┘

Pros: Good isolation, shared infra cost
Cons: Schema migration complexity, connection pooling
Best for: Medium SaaS, regulated industries

3. Database-Level (Full Isolation)

┌──────────┐  ┌──────────┐  ┌──────────┐
│  DB_A     │  │  DB_B     │  │  DB_C     │
│  users    │  │  users    │  │  users    │
│  orders   │  │  orders   │  │  orders   │
└──────────┘  └──────────┘  └──────────┘

Pros: Maximum isolation, per-tenant backup/restore
Cons: Expensive, complex management
Best for: Enterprise, healthcare, financial

Tenant Routing

// Router that selects connection based on tenant
@Injectable()
export class TenantConnectionManager {
  private connections = new Map<string, Connection>();

  async getConnection(tenantId: string): Promise<Connection> {
    if (this.connections.has(tenantId)) {
      return this.connections.get(tenantId);
    }

    const config = await this.configService.getTenantDbConfig(tenantId);
    const connection = await createConnection({
      name: tenantId,
      ...config,
    });

    this.connections.set(tenantId, connection);
    return connection;
  }
}

Data Isolation Checklist

  • Every query filters by tenant_id (row-level)
  • No global admin endpoints return cross-tenant data without authorization
  • Indexes include tenant_id as first column
  • Foreign keys respect tenant boundaries
  • Bulk operations scoped to single tenant
  • Logging includes tenant context
  • Testing includes cross-tenant access attempts
  • Backup/restore can be done per-tenant

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.