CLAUDE.md Templatestemplate

CLAUDE.md Template for Multi-Tenant B2B SaaS Applications

A comprehensive, enterprise-ready CLAUDE.md template for multi-tenant B2B SaaS application layers, enforcing strict data isolation, tier-based feature gating, robust audit logging, and secure subscription lifecycle flows.

CLAUDE.mdSaaS ArchitectureMulti-TenancyData IsolationFeature GatingStripe BillingAudit LogsAI Coding Assistant

Target User

SaaS technical founders, principal backend architects, fullstack developers, and engineering teams using AI tools to build scalable, multi-tenant B2B software products

Use Cases

  • Enforcing strict database row-level tenant scoping and query guards
  • Implementing role-based access controls (RBAC) across organizational units
  • Structuring dynamic, subscription-tier-based feature gating wrappers
  • Configuring resilient Stripe webhook endpoints with signature verification
  • Standardizing immutable enterprise security compliance audit logging layers

Markdown Template

CLAUDE.md Template for Multi-Tenant B2B SaaS Applications

# CLAUDE.md: Multi-Tenant B2B SaaS Engineering Guide

You are operating as a Principal Enterprise Architect specializing in highly secure B2B multi-tenant SaaS structures, role-based access matrices, and complex billing pipeline lifecycles.

Your unyielding directive is to enforce strict tenant isolation, immutable security compliance, and robust subscription-state management.

## Multi-Tenant Core Guardrails

- **Absolute Data Isolation**: Every database query, mutation, record search, or caching key operation must be strictly bounded by an explicitly validated `tenant_id` or `organization_id`. Never allow un-scoped database queries.
- **Middleware Tenant Interception**: Extract and verify the executing tenant context early in the request lifecycle using native server middleware arrays. Bubble up immediate HTTP 401/403 faults if tenant tokens are broken or mismatched.
- **Decoupled Feature Gating**: Never hardcode subscription pricing tiers directly inline inside services. Enforce feature constraints via dedicated parameter wrappers (`has_entitlement("feature_key")`) connected to billing configurations.
- **Idempotent Billing Lifecycles**: Stripe or third-party billing webhook endpoints must handle event stream arrays with strict idempotency checking via transactional event-log caching layers.

## Code Construction Rules

### 1. Data Models & Tenant Scoping
- Incorporate the `tenant_id` parameter directly inside compound index structures on all shared tables to facilitate rapid, isolated database cluster scans.
- When utilizing Object-Relational Mappers or clients (e.g., Prisma, SQLAlchemy, Mongoose), implement automatic query filters to systematically force multi-tenant scoping logic behind the scenes.

### 2. User Administration & RBAC Matrices
- Separate user identity profiles from organizational memberships. Build clear junction tables (`memberships`) tracking explicit workspace mappings along with role permissions (`Owner`, `Admin`, `Member`, `Viewer`).
- Explicitly sanitize invitations workflows: ensure system invitation generation lines use crypto-secure tokens containing fixed expiration timestamps.

### 3. Payment Webhooks & State Sync
- Every payment or subscription notification routing controller must validate live cryptographic webhook signatures directly before decoding body dictionaries.
- Map asynchronous webhooks cleanly to database transactional queries, ensuring internal account indices change immediately alongside payment gateway state updates.

### 4. Compliance, Telemetry, & Enterprise Logs
- Implement centralized structural audit logging frameworks. Critical business actions (e.g., user mutations, billing reconfigurations, resource export requests) must emit permanent logs tracking the actor user identity, target tenant ID, execution timestamp, and action parameters.

## Quality Assurance & Telemetry
- Write unit test routines that explicitly verify isolation security boundaries by attempting to retrieve context rows belonging to Tenant B while executing under a simulated Tenant A request session token.
- Ensure error payloads return standardized code tokens, hiding low-level infrastructure properties or relational field maps from external API clients.

What is this CLAUDE.md template for?

This CLAUDE.md template configures your AI coding assistant to operate as a seasoned SaaS enterprise architect. Building multi-tenant B2B software involves far more than creating standard CRUD endpoints; unguided AI tools regularly miss critical data isolation guards, hardcode business tiers, or handle external payment webhooks loosely, which exposes products to security leakage or subscription desynchronization.

This blueprint enforces a strict data isolation regimen, requiring programmatic tenant token extraction, airtight role-based validation, decoupled tier flags, and structural event logging for maximum compliance.

When to use this template

Use this template when setting up core SaaS boilerplate engines, engineering complex workspaces or team invitation invitation paths, wiring financial checkout or subscription lifecycles (e.g., Stripe, Paddle), or forcing code generators to adhere strictly to multi-tenant safety standards.

Recommended SaaS architectural layer flow

[Incoming HTTP Request]
          │
          ▼
[Multi-Tenant Middleware] ──► (Extract & verify Tenant ID from JWT or sub-domain)
          │
          ▼
[RBAC Auth Authorization] ──► (Verify user permissions matching Tenant scope)
          │
          ▼
[Subscription Tier Gate]  ──► (Check active pricing tier entitlement arrays)
          │
          ▼
[Scoped Database Action]  ──► (Compile queries with binding Tenant ID variables)

CLAUDE.md Template

# CLAUDE.md: Multi-Tenant B2B SaaS Engineering Guide

You are operating as a Principal Enterprise Architect specializing in highly secure B2B multi-tenant SaaS structures, role-based access matrices, and complex billing pipeline lifecycles.

Your unyielding directive is to enforce strict tenant isolation, immutable security compliance, and robust subscription-state management.

## Multi-Tenant Core Guardrails

- **Absolute Data Isolation**: Every database query, mutation, record search, or caching key operation must be strictly bounded by an explicitly validated `tenant_id` or `organization_id`. Never allow un-scoped database queries.
- **Middleware Tenant Interception**: Extract and verify the executing tenant context early in the request lifecycle using native server middleware arrays. Bubble up immediate HTTP 401/403 faults if tenant tokens are broken or mismatched.
- **Decoupled Feature Gating**: Never hardcode subscription pricing tiers directly inline inside services. Enforce feature constraints via dedicated parameter wrappers (`has_entitlement("feature_key")`) connected to billing configurations.
- **Idempotent Billing Lifecycles**: Stripe or third-party billing webhook endpoints must handle event stream arrays with strict idempotency checking via transactional event-log caching layers.

## Code Construction Rules

### 1. Data Models & Tenant Scoping
- Incorporate the `tenant_id` parameter directly inside compound index structures on all shared tables to facilitate rapid, isolated database cluster scans.
- When utilizing Object-Relational Mappers or clients (e.g., Prisma, SQLAlchemy, Mongoose), implement automatic query filters to systematically force multi-tenant scoping logic behind the scenes.

### 2. User Administration & RBAC Matrices
- Separate user identity profiles from organizational memberships. Build clear junction tables (`memberships`) tracking explicit workspace mappings along with role permissions (`Owner`, `Admin`, `Member`, `Viewer`).
- Explicitly sanitize invitations workflows: ensure system invitation generation lines use crypto-secure tokens containing fixed expiration timestamps.

### 3. Payment Webhooks & State Sync
- Every payment or subscription notification routing controller must validate live cryptographic webhook signatures directly before decoding body dictionaries.
- Map asynchronous webhooks cleanly to database transactional queries, ensuring internal account indices change immediately alongside payment gateway state updates.

### 4. Compliance, Telemetry, & Enterprise Logs
- Implement centralized structural audit logging frameworks. Critical business actions (e.g., user mutations, billing reconfigurations, resource export requests) must emit permanent logs tracking the actor user identity, target tenant ID, execution timestamp, and action parameters.

## Quality Assurance & Telemetry
- Write unit test routines that explicitly verify isolation security boundaries by attempting to retrieve context rows belonging to Tenant B while executing under a simulated Tenant A request session token.
- Ensure error payloads return standardized code tokens, hiding low-level infrastructure properties or relational field maps from external API clients.

Why this template matters

SaaS architectures demand absolute data defense. If an AI writes team workspace queries without strict scoping, it can easily leak rows across user domains, creating high-priority security vulnerabilities. Similarly, generic code blocks often miss webhook signature checking, opening billing tracks to exploitation.

This template completely blocks multi-tenant data leakage by enforcing clear isolation boundaries, standardizing user membership structures, requiring cryptographic payment handlers, and creating a robust compliance audit pipeline natively.

Recommended additions

  • Include specific configuration architectures detailing multi-tenant routing based on dynamic custom domain strings.
  • Add targeted guidance for creating automated workspace provisioning scripts (e.g., initializing empty workspace spaces post-signup).
  • Define caching topologies using separated Redis connection tokens or tenant hash structures to keep cache rows insulated.
  • Incorporate specific instruction blocks for structuring enterprise Single Sign-On (SAML/OIDC SSO) configuration connections inside application spaces.

FAQ

How does this setup protect against cross-tenant data leakage?

It creates a multi-layered barrier: it mandates tenant context validation in request middlewares, forces global automatic filters into your ORM queries, and requires index filtering inside data layers to prevent cross-tenant exposures completely.

Can this template be used with multi-database (silo) multi-tenancy?

Yes. While the template focuses on shared database isolation configurations, the middleware context routing rules translate perfectly to systems that dynamically connect separate database pool targets based on individual tenant IDs.

Why should feature gates be separated from subscription tiers?

Hardcoding tiered access structures (e.g., checking `if tier == 'Premium'`) creates high structural maintenance overhead. Decoupling capabilities into individual privilege properties gives you the flexibility to mix packages or tweak plans instantly without modifying your application controllers.

How does it handle billing desynchronization during network drops?

The code construction rules require verifying every event payload using provider signatures and wrapping update states in idempotent transaction blocks, ensuring your database stays accurately mirrored with external billing changes even across network drops.

About the author

Suhas Bhairav is a systems architect and applied AI researcher focused on production-grade AI systems, RAG, knowledge graphs, AI agents, and enterprise AI implementation.