Agent skill

SaaS Multi Tenant

by davila7 in davila7/claude-code-templates

Design and implement multi-tenant SaaS architectures with row-level security, tenant-scoped queries, shared-schema isolation, and safe cross-tenant admin patterns in PostgreSQL and TypeScript.

MITAuto-check passedBackend & APIs

Install SaaS Multi Tenant

skills CLI
$ npx skills add davila7/claude-code-templates --skill saas-multi-tenant -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install davila7/claude-code-templates saas-multi-tenant --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/davila7/claude-code-templates.git skills-src && mkdir -p .claude/skills && cp -r skills-src/cli-tool/components/skills/development/saas-multi-tenant .claude/skills/saas-multi-tenant && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
saas-multi-tenant
GitHub stars
33k
Used in
3 other repos
Token cost
~3.1k tokens
SKILL.md length
1,374 words
Files
1
Skills in repo
479
Repo updated
First seen
Licence
MIT

At a glance

Design and implement multi-tenant SaaS architectures with row-level security, tenant-scoped queries, shared-schema isolation, and safe cross-tenant admin patterns in PostgreSQL and TypeScript.

  • Works in 8 steps: Determine the tenancy model. Ask the… → Add tenant_id to every tenant-scoped… → Set up PostgreSQL Row-Level Security… → …
  • Tasks that involve Multi-tenancy
  • SKILL.md covers When to Use This Skill, Core Workflow, Examples and Never Do This, plus 2 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

SaaS Multi Tenant is an agent skill from davila7/claude-code-templates. Design and implement multi-tenant SaaS architectures with row-level security, tenant-scoped queries, shared-schema isolation, and safe cross-tenant admin patterns in PostgreSQL and TypeScript.

Its SKILL.md is about 3.1k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Backend & APIs, covering Multi-tenancy. It works with PostgreSQL and TypeScript. The repository describes itself as: CLI tool for configuring and monitoring Claude Code. The licence is MIT.

When your agent uses it

  • Tasks that involve Multi-tenancy

Example prompts

  • “/saas-multi-tenant”

Workflow steps

8 steps, taken from the first numbered list in SKILL.md.

  1. Determine the tenancy model. Ask the user about their scale expectations and isolation requirements. For most SaaS apps under 1000…
  2. Add tenant_id to every tenant-scoped table. The column must be NOT NULL, type UUID or TEXT, and included in every composite index. Never…
  3. Set up PostgreSQL Row-Level Security (RLS). Create a policy on each tenant-scoped table that filters rows by…
  4. Build tenant-aware middleware. At the start of every request, extract the tenant_id from the authenticated session or JWT claims. Set it…
  5. Scope all ORM queries by tenant. If using Prisma, apply a global middleware that injects where: { tenantId } into every findMany…
  6. Handle tenant-aware migrations. Every new table migration must include tenant_id as a column. Write a linting rule or CI check that…
  7. Build cross-tenant admin routes separately. Admin endpoints that aggregate data across tenants must bypass RLS explicitly using SET LOCAL…
  8. Implement tenant provisioning. When a new customer signs up, create their tenant record, seed default data (roles, settings, onboarding…

What it can do on your machine

Read from SKILL.md and the folder at commit c0ca7da. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript and sql).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

SaaS Multi Tenant loads about 3.1k tokens when it runs. Until then it costs about 53 tokens; SKILL.md has 1,374 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~53
When it runs · the whole SKILL.md, loaded when a task matches
~3.1k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from davila7/claude-code-templates at commit c0ca7da, republished under its MIT licence (© davila7). 1,374 words, ~3,147 tokens.

Download SKILL.mdSave it as .claude/skills/saas-multi-tenant/SKILL.md (or your agent's skills folder).
name
saas-multi-tenant
description
Design and implement multi-tenant SaaS architectures with row-level security, tenant-scoped queries, shared-schema isolation, and safe cross-tenant admin patterns in PostgreSQL and TypeScript.
risk
safe
source
community
date_added
2026-03-28
tags
multi-tenancy, saas, row-level-security, postgresql, tenant-isolation
tools
claude, cursor, gemini

SaaS Multi-Tenant Architecture

When to Use This Skill

  • The user is building a SaaS application where multiple customers share the same database
  • The user asks about tenant isolation, row-level security, or data leakage prevention
  • The user needs to scope every database query to a specific tenant without manual WHERE clauses
  • The user asks about shared-schema vs schema-per-tenant vs database-per-tenant tradeoffs
  • The user is implementing admin endpoints that must access data across tenants
  • The user needs to add tenant_id columns to an existing single-tenant application
  • The user asks about PostgreSQL RLS policies for tenant isolation
  • The user is building tenant-aware middleware in Express, Fastify, or Next.js API routes

Do NOT use this skill when:

  • The user is building a single-user application with no shared infrastructure
  • The user asks about authentication only without tenant scoping (use an auth skill instead)
  • The user needs general database schema design without multi-tenancy requirements

Core Workflow

  1. Determine the tenancy model. Ask the user about their scale expectations and isolation requirements. For most SaaS apps under 1000 tenants, shared-schema with a tenant_id column on every table is the correct default. Schema-per-tenant adds operational overhead (migrations run N times). Database-per-tenant is only justified when tenants have regulatory data residency requirements.

  2. Add tenant_id to every tenant-scoped table. The column must be NOT NULL, type UUID or TEXT, and included in every composite index. Never allow a tenant-scoped table to exist without this column — a missing tenant_id is a data leak waiting to happen.

  3. Set up PostgreSQL Row-Level Security (RLS). Create a policy on each tenant-scoped table that filters rows by current_setting('app.current_tenant_id'). This acts as a database-level safety net — even if application code forgets a WHERE clause, RLS blocks cross-tenant reads.

  4. Build tenant-aware middleware. At the start of every request, extract the tenant_id from the authenticated session or JWT claims. Set it on the database connection using SET LOCAL app.current_tenant_id = '...' inside a transaction. Every subsequent query in that request inherits the tenant scope automatically.

  5. Scope all ORM queries by tenant. If using Prisma, apply a global middleware that injects where: { tenantId } into every findMany, findFirst, update, and delete call. If using Drizzle, create a base query builder that includes the tenant filter. Never rely on developers remembering to add the filter manually.

  6. Handle tenant-aware migrations. Every new table migration must include tenant_id as a column. Write a linting rule or CI check that rejects any migration creating a table without tenant_id unless the table is explicitly marked as global (e.g., plans, feature_flags).

  7. Build cross-tenant admin routes separately. Admin endpoints that aggregate data across tenants must bypass RLS explicitly using SET LOCAL role = 'admin_bypass' or a dedicated database role. These routes must be protected by a separate admin authentication flow — never reuse tenant user sessions for admin access.

  8. Implement tenant provisioning. When a new customer signs up, create their tenant record, seed default data (roles, settings, onboarding state), and assign the founding user. Wrap this in a database transaction so partial provisioning never leaves orphan records.

Examples

Example 1: PostgreSQL RLS Policy for Tenant Isolation
sql
-- Enable RLS on the table
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
ALTER TABLE projects FORCE ROW LEVEL SECURITY;

-- Policy: users can only see rows where tenant_id matches the session variable
CREATE POLICY tenant_isolation ON projects
  USING (tenant_id = current_setting('app.current_tenant_id')::uuid);

-- Policy for INSERT: new rows must match the current tenant
CREATE POLICY tenant_insert ON projects
  FOR INSERT
  WITH CHECK (tenant_id = current_setting('app.current_tenant_id')::uuid);
Example 2: Express Middleware That Sets Tenant Context per Request
typescript
import { Pool } from "pg";

const pool = new Pool({ connectionString: process.env.DATABASE_URL });

async function tenantMiddleware(req, res, next) {
  const tenantId = req.auth?.tenantId; // extracted from JWT during auth
  if (!tenantId) return res.status(403).json({ error: "No tenant context" });

  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    // Use set_config — SET LOCAL does not accept bind placeholders ($1)
    await client.query("SELECT set_config('app.current_tenant_id', $1, true)", [tenantId]);
    req.db = client;
    req.tenantId = tenantId;

    // Cleanup on response finish — guarantees release even if handler skips next()
    res.on("finish", async () => {
      try { await client.query("COMMIT"); } catch { await client.query("ROLLBACK"); }
      client.release();
    });

    next();
  } catch (err) {
    await client.query("ROLLBACK").catch(() => {});
    client.release();
    next(err);
  }
}
Example 3: Prisma Middleware for Automatic Tenant Scoping
typescript
import { PrismaClient } from "@prisma/client";

// Tables that do NOT have tenant_id (global tables)
const GLOBAL_TABLES = new Set(["Plan", "FeatureFlag", "SystemConfig"]);

function createTenantPrisma(tenantId: string): PrismaClient {
  const prisma = new PrismaClient();

  prisma.$use(async (params, next) => {
    if (GLOBAL_TABLES.has(params.model ?? "")) return next(params);

    // Initialize args.where — Prisma passes undefined args for calls like findMany()
    params.args = params.args ?? {};
    params.args.where = params.args.where ?? {};

    // Inject tenant filter on reads (skip findUnique — it only accepts unique-field selectors)
    if (["findMany", "findFirst", "count", "aggregate"].includes(params.action)) {
      params.args.where = { ...params.args.where, tenantId };
    }

    // Inject tenant_id on creates
    if (["create", "createMany"].includes(params.action)) {
      params.args.data = params.args.data ?? {};
      if (params.action === "createMany") {
        params.args.data = params.args.data.map((d: any) => ({ ...d, tenantId }));
      } else {
        params.args.data = { ...params.args.data, tenantId };
      }
    }

    // Scope updates and deletes
    if (["update", "updateMany", "delete", "deleteMany"].includes(params.action)) {
      params.args.where = { ...params.args.where, tenantId };
    }

    return next(params);
  });

  return prisma;
}

Never Do This

  1. Never query a tenant-scoped table without a tenant_id filter. Even if your ORM middleware handles it, raw SQL queries bypass middleware entirely. Every raw query must include WHERE tenant_id = $1 or rely on RLS. A single unscoped SELECT * FROM invoices leaks every customer's billing data.

  2. Never store tenant_id only in the application session without enforcing it at the database level. Application-layer filtering is a suggestion. RLS is enforcement. If a bug in your middleware skips the tenant filter, only RLS prevents the data leak. Run both layers.

  3. Never use auto-incrementing integer IDs for tenant-scoped resources. Sequential IDs (invoice #1042) let attackers enumerate other tenants' resources by incrementing the ID. Use UUIDs for all tenant-scoped primary keys. Reserve integer IDs for internal-only tables.

  4. Never let tenant users access admin aggregation endpoints. A route like GET /admin/metrics that queries across all tenants must never be reachable with a regular tenant JWT. Use a separate authentication mechanism (API key, admin role claim with a different issuer) for cross-tenant routes.

  5. Never run migrations with RLS enabled on the migration connection. The migration user needs to create tables, add columns, and modify policies. If RLS is active on the migration connection, ALTER TABLE commands may silently fail or affect only the "current tenant's" view. Use a dedicated superuser or bypassrls role for migrations.

  6. Never share connection pools across tenants when using SET LOCAL. If you use SET LOCAL app.current_tenant_id inside a transaction, that setting is scoped to the transaction. But if a previous request's transaction was not properly committed or rolled back, the connection returns to the pool with stale tenant context. Always RESET app.current_tenant_id in the cleanup path.

Show full SKILL.md (561 more words)Show less

Edge Cases

  1. Tenant deletion and data retention. When a tenant cancels their subscription, you cannot simply DELETE FROM tenants WHERE id = $1. Foreign key cascades may time out on large datasets. Instead, soft-delete the tenant (set deleted_at), revoke all user sessions, then run a background job that deletes tenant data in batches over hours or days.

  2. Tenant data export for GDPR/compliance. When a tenant requests a full data export, you need to query every tenant-scoped table for that tenant_id and package it. Build a registry of all tenant-scoped tables (parse your migration files or maintain a manifest) so the export job doesn't miss tables added after the export feature was built.

  3. Shared resources between tenants. Some features require shared state — e.g., a marketplace where Tenant A's products are visible to Tenant B's users. These tables need a different RLS policy: read access is public (no tenant filter), but write access is still scoped to the owning tenant. Model these as owner_tenant_id instead of tenant_id.

  4. Tenant-aware background jobs. When a cron job or queue worker processes tasks, there is no HTTP request to extract tenant_id from. The job payload must include tenant_id, and the worker must set the database session variable before processing. Never run background jobs without tenant context — they will either fail on RLS or bypass it entirely.

  5. Connection pool exhaustion with schema-per-tenant. If you use one PostgreSQL schema per tenant and each schema requires its own connection pool, 500 tenants means 500 pools. This exhausts max_connections fast. Use a connection pooler like PgBouncer in transaction mode, or switch to shared-schema before hitting this wall.

Best Practices

  1. Create a tenants table as the single source of truth. Every tenant_id foreign key in every table points back to tenants.id. Include columns for name, slug (for subdomain routing), plan_id, created_at, and deleted_at. This table is the root of your entire data model.

  2. Index tenant_id as the first column in every composite index. PostgreSQL uses leftmost prefix matching for composite indexes. An index on (tenant_id, created_at) serves both "all items for tenant X" and "items for tenant X sorted by date." An index on (created_at, tenant_id) only helps date-range queries across all tenants.

  3. Use subdomains or path prefixes for tenant routing. acme.yourapp.com or yourapp.com/org/acme — both work. Map the subdomain or path to a tenant_id lookup at the edge (middleware or reverse proxy). This lookup should be cached (Redis or in-memory with 60s TTL) since it runs on every single request.

  4. Separate tenant-scoped tables from global tables explicitly. Maintain a list (code constant or database table) of which tables are global (no tenant_id) and which are tenant-scoped. Use this list in your ORM middleware, your migration linter, and your data export job. If a table isn't in either list, the CI check should fail.

  5. Test with at least 3 tenants in your seed data. A single tenant in development hides every multi-tenancy bug. Two tenants hides bugs where the first tenant's data leaks to the second but not vice versa. Three tenants catches ordering and filtering bugs that only appear with multiple peers.

  6. Rate-limit and quota per tenant, not globally. A global rate limit of 1000 requests/minute means one noisy tenant can exhaust the quota for everyone. Implement per-tenant rate limiting using a Redis key pattern like ratelimit:{tenant_id}:{endpoint} with a sliding window counter.

© davila7, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in cli-tool/components/skills/development/saas-multi-tenant of davila7/claude-code-templates.

Open the folder on GitHubat commit c0ca7da

Used in 3 other repositories

We found 12 copies of this SKILL.md (exact, near-identical or edited) in other folders, from 3 other GitHub owners. This page covers the copy in davila7/claude-code-templates, which our catalogue first saw on October 7, 2026.

Compare with similar skills

SaaS Multi Tenant next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

SaaS Multi Tenant compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
SaaS Multi Tenant this skilldavila7/claude-code-templates33k3 repos~3.1kAutomated safety check: PassMIT
Stash Encryptioncipherstash/stack157—~18kAutomated safety check: NotesMIT
cmux Backend Rulesmanaflow-ai/cmux28k1 repos~682Automated safety check: PassCustom licence
Stack Previewvicoa-ai/vicoa504—~1.8kAutomated safety check: NotesAGPL-3.0
Backend Dev Guidelineslitefuse/litefuse1011 repos~5.8kAutomated safety check: PassCustom licence
Backend AI Guidelablup/backend.ai-webui1331 repos~1.8kAutomated safety check: PassLGPL-3.0

Similar skills

  • Stash Encryption

    cipherstash/stack

    Implement field-level encryption with @cipherstash/stack using the EQL v3 typed schema.

    157 GitHub stars~18k tokensUpdated today
    Backend & APIsAuto-check: notes
  • cmux Backend Rules

    manaflow-ai/cmux

    Sets the backend TypeScript and Cloud VM rules for cmux: Effect-based services, thin route handlers, Postgres as source of truth, migrations and provider secrets.

    28k GitHub starsUsed in 1 repo~682 tokens
    Backend & APIsAuto-check passed
  • Stack Preview

    vicoa-ai/vicoa

    Run the whole Vicoa stack (Postgres, backend, realtime server, web dashboard) from the current checkout and publish it at one public tunnel URL, so a branch can be reviewed from another machine or…

    504 GitHub stars~1.8k tokensUpdated today
    Backend & APIsAuto-check: notes
  • Backend Dev Guidelines

    litefuse/litefuse

    Comprehensive backend development guide for Litefuse's Next.js 14/tRPC/Express/TypeScript monorepo.

    101 GitHub starsUsed in 1 repo~5.8k tokens
    Backend & APIsAuto-check passed
  • Backend AI Guide

    lablup/backend.ai-webui

    Expert guide for Backend.AI distributed computing platform. An agent skill from lablup/backend.ai-webui.

    133 GitHub starsUsed in 1 repo~1.8k tokens
    Backend & APIsAuto-check passed
  • Stash Zerokms

    cipherstash/stack

    The ZeroKMS key model — keysets, clients, client keys, and the grant/revoke lifecycle.

    157 GitHub stars~4.4k tokensUpdated today
    Backend & APIsAuto-check passed

More from davila7/claude-code-templates

All 479 skills in this repo
  • Perplexity Web Search

    davila7/claude-code-templates

    Runs web-grounded searches through Perplexity's Sonar models over OpenRouter for current events, recent literature and cited facts beyond the model's training cutoff.

    33k GitHub starsUsed in 11 repos~3.5k tokens
    Auto-check: notes
  • Neuropixels Data Analysis

    davila7/claude-code-templates

    Analyzes Neuropixels recordings from SpikeGLX or Open Ephys through preprocessing, drift correction, Kilosort4 spike sorting, quality metrics and curation.

    33k GitHub starsUsed in 9 repos~2.8k tokens
    Auto-check passed
  • Scientific Venue Templates

    davila7/claude-code-templates

    Supplies LaTeX templates and formatting rules for journals, conferences, posters, and grant proposals, then can check a draft against them.

    33k GitHub starsUsed in 9 repos~5.1k tokens
    Auto-check: notes
  • Brand Voice Content Creator

    davila7/claude-code-templates

    Analyzes a brand's existing writing to lock in a consistent voice, then builds SEO blog posts and platform-specific social content around it.

    33k GitHub starsUsed in 3 repos~1.9k tokens
    Auto-check passed
  • CAPA Officer

    davila7/claude-code-templates

    Guides corrective and preventive action (CAPA) work in a quality management system, from initiation and root cause analysis through effectiveness verification.

    33k GitHub starsUsed in 1 repo~2k tokens
    Auto-check passed
  • Fda Consultant Specialist

    davila7/claude-code-templates

    Senior FDA consultant and specialist for medical device companies including HIPAA compliance and requirement management.

    33k GitHub starsUsed in 1 repo~2.7k tokens
    Auto-check passed

Categories

Questions about SaaS Multi Tenant

What does SaaS Multi Tenant do?

Design and implement multi-tenant SaaS architectures with row-level security, tenant-scoped queries, shared-schema isolation, and safe cross-tenant admin patterns in PostgreSQL and TypeScript. SaaS Multi Tenant is an agent skill from davila7/claude-code-templates. Design and implement multi-tenant SaaS architectures with row-level security, tenant-scoped queries, shared-schema isolation, and safe cross-tenant admin patterns in PostgreSQL and TypeScript.

When should I use SaaS Multi Tenant?

SaaS Multi Tenant fits situations like: tasks that involve Multi-tenancy.

How do I install SaaS Multi Tenant in Claude Code?

Run `npx skills add davila7/claude-code-templates --skill saas-multi-tenant -a claude-code`. Or copy the skill folder (cli-tool/components/skills/development/saas-multi-tenant in davila7/claude-code-templates) into .claude/skills/saas-multi-tenant in your project. Claude Code loads it when a task matches its description.

How do I install SaaS Multi Tenant in Codex?

Run `npx skills add davila7/claude-code-templates --skill saas-multi-tenant -a codex`. Or copy the skill folder (cli-tool/components/skills/development/saas-multi-tenant in davila7/claude-code-templates) into .agents/skills/saas-multi-tenant in your project. Codex loads it when a task matches its description.

Can I use SaaS Multi Tenant in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add davila7/claude-code-templates --skill saas-multi-tenant -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/saas-multi-tenant, .gemini/skills/saas-multi-tenant, .github/skills/saas-multi-tenant and .opencode/skills/saas-multi-tenant in your project.

What does SaaS Multi Tenant need to run?

SKILL.md names no scripts, command-line tools or credentials: SaaS Multi Tenant is instructions for the agent only.

Does SaaS Multi Tenant access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is SaaS Multi Tenant safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does SaaS Multi Tenant use?

SaaS Multi Tenant is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does SaaS Multi Tenant use?

About 3.1k tokens (SKILL.md is roughly 13k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to SaaS Multi Tenant?

Skills that share tags, products or a category with SaaS Multi Tenant: Stash Encryption (cipherstash/stack, 157 stars), cmux Backend Rules (manaflow-ai/cmux, 28k stars), Stack Preview (vicoa-ai/vicoa, 504 stars) and Backend Dev Guidelines (litefuse/litefuse, 101 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains SaaS Multi Tenant?

davila7 (a GitHub user) maintains it in davila7/claude-code-templates, which has 32,512 GitHub stars. The repository holds 479 skills in this directory. The repository was last updated on October 10, 2026.

Source: davila7/claude-code-templates on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.