backend-multi-tenancy
Use when the user asks about multi-tenancy, SaaS where each customer must only see their own data, tenant isolation, row-level security, schema or database…
от j4flmao★ 47 звёзд на GitHub
Установить backend-multi-tenancy в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Backend Multi-Tenancy
Purpose
Implement tenant isolation in a SaaS application using row-level, schema-per-tenant, or DB-per-tenant strategies with automated provisioning and safe migrations. The core challenge is guaranteeing that no tenant can access another tenant's data while balancing operational complexity, cost, and compliance requirements.
Architecture/Decision Trees
Isolation Strategy Decision Tree
Is regulatory compliance required (GDPR/SOC 2/HIPAA)?
|-- YES --> Do tenants require full data separation?
| |-- YES --> DB-per-tenant (highest isolation)
| |-- NO --> Schema-per-tenant
|-- NO --> Expected tenant count?
|-- < 100, B2B --> Schema-per-tenant
|-- >= 100, B2C --> Row-level (shared database)
|-- Mixed (B2B+B2C) --> Hybrid: row-level for B2C, schema for B2B
Hybrid Strategy Matrix
| Tier | Isolation | Database | Provisioning | Backup |
|---|---|---|---|---|
| Free | Row-level | Shared | Auto (self) | Global |
| Pro | Schema | Shared | Auto (self) | Global |
| Enterprise | DB | Dedicated | Manual | Per-tenant |
Agent Protocol
Trigger
Exact user phrases: "multi-tenancy", "SaaS", "tenant isolation", "row-level security", "DB per tenant", "schema per tenant", "tenant provisioning", "tenant migration", "multi-tenant database", "tenant context".
Input Context
- Number of tenants (current and projected).
- Regulatory requirements (GDPR, SOC 2, HIPAA).
- Database technology and hosting model.
- Existing authentication/user system.
- Pricing tiers and tenant size distribution.
- Team operational capacity for managing per-tenant infrastructure.
Output Artifact
Tenant isolation configuration or implementation plan. No file unless requested.
Response Format
Strategy: {Row-level|Schema-per-tenant|DB-per-tenant}
Isolation Level: {shared|semi-isolated|fully-isolated}
Provisioning: {automated|manual}
Migration: {shared schema|per-tenant}
Completion Criteria
- Isolation strategy chosen based on requirements.
- Tenant context propagated through all layers.
- All queries scoped to current tenant.
- Tenant provisioning automated.
- Migrations run safely across all tenants.
- Cross-tenant access audit logging configured.
- Backup strategy accounts for per-tenant restore requirements.
Max Response Length
4 lines per isolation strategy. 20 lines for full plan.
Workflow
Step 1: Choose Isolation Strategy
| Strategy | Isolation | Complexity | Cost | Best For |
|---|---|---|---|---|
| Row-level | Lowest | Low | Low | B2C, many small tenants |
| Schema-per-tenant | Medium | Medium | Medium | B2B, medium tenants |
| DB-per-tenant | Highest | High | High | Enterprise, regulated |
Step 2: Implement Tenant Context
// Middleware extracts tenant from auth token
async function tenantMiddleware(req, res, next) {
const token = decodeJWT(req.headers.authorization);
req.tenantId = token.tenant_id;
// Validate tenant is active and not suspended
const tenant = await tenantCache.get(req.tenantId);
if (!tenant || tenant.status !== 'active') {
return res.status(403).json({ error: 'tenant_inactive' });
}
// Set in async local storage for ORM access
asyncLocalStorage.run({ tenantId: req.tenantId, tenant }, next);
}
Step 3: Scope All Queries (Row-Level)
// Prisma example: global middleware appends tenant filter
prisma.$use(async (params, next) => {
const tenantId = asyncLocalStorage.getStore()?.tenantId;
if (tenantId && params.model && !params.args.where?.tenantId) {
params.args.where = { ...params.args.where, tenantId };
}
return next(params);
});
Step 4: Automate Tenant Provisioning
-- For schema-per-tenant
CREATE SCHEMA IF NOT EXISTS tenant_{id};
-- Apply migrations to tenant schema
SELECT migrate_tenant('tenant_{id}');
-- Seed default data for new tenant
INSERT INTO tenant_{id}.settings (key, value) VALUES ('theme', 'default');
Step 5: Handle Data Isolation at Rest
- Row-level:
WHERE tenant_id = ?on every query. - Schema-per-tenant: search_path or schema-qualified tables.
- DB-per-tenant: connection string per tenant in a registry.
Step 6: Migrate Safely
# For shared schema: add nullable column, backfill, then NOT NULL
# For per-tenant: iterate tenants, migrate one by one
# Use a migration orchestration table to track per-tenant progress
// Per-tenant migration runner
async function migrateTenants(migrationName: string, migrationFn: (schema: string) => Promise<void>) {
const tenants = await tenantRepository.listActive();
// Use batch processing with concurrency limit
const BATCH_SIZE = 10;
for (let i = 0; i < tenants.length; i += BATCH_SIZE) {
const batch = tenants.slice(i, i + BATCH_SIZE);
await Promise.all(
batch.map(async (tena
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- references/data-partitioning.md
- references/isolation-strategies.md
- references/merged-enterprise-multi-tenant.md
- references/multi-tenancy-data-isolation.md
- references/multi-tenancy-monitoring.md
- references/multi-tenancy-tenant-lifecycle.md
- references/multi-tenancy-testing.md
- references/multi-tenant-advanced.md
- references/multi-tenant-architecture.md
- references/multi-tenant-fundamentals.md
- references/tenant-isolation.md
- references/tenant-lifecycle.md
- references/tenant-provisioning-2.md
- references/tenant-provisioning.md
- references/tenant-routing.md
FAQ
Что делает скилл backend-multi-tenancy?
Use when the user asks about multi-tenancy, SaaS where each customer must only see their own data, tenant isolation, row-level security, schema or database per tenant, tenant context or tenant provisioning. Produces an isolation model with enforcement code. Not for Supabase RLS specifics (use supabase).
Как установить скилл backend-multi-tenancy?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл backend-multi-tenancy запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
AnthropicCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
discernment-nudge
AnthropicAfter you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
data-consolidate
AnthropicJoins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
inspection-to-capa
AnthropicRuns the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…