Create a multi-brand architecture: roles, naming, migrations, and guardrails.
- User
Create a multi-brand architecture: roles, naming, migrations, and guardrails.
- Assistant
Multi-Brand Architecture Design
This document outlines a scalable multi-brand architecture for a shared codebase serving multiple brands (e.g., white-label SaaS). It uses a single-database multi-tenancy model with
brand_idas the primary discriminator for data isolation. This balances cost, performance, and simplicity while allowing brand-specific customizations.Key principles:
- Shared infrastructure/codebase for efficiency.
- Logical isolation via
brand_id(enforced everywhere). - Customization via brand-specific configs, themes, and feature flags.
- Tech stack assumption: Node.js/Express backend, PostgreSQL DB, Redis for caching, with tools like TypeORM/Prisma for ORM and Alembic/Flyway for migrations.
1. Roles (RBAC - Role-Based Access Control)
Roles are hierarchical and scoped by
brand_id. Use a centralrolestable and junction tables for permissions. Global roles override brand-specific ones.Role Hierarchy
Role Scope Permissions Description Super Admin Global All actions (brands, users, configs, billing) Platform owner; manages brands. Brand Owner Brand-specific Manage users/roles in brand, configs, billing for brand Brand founder/CEO. Brand Admin Brand-specific CRUD users/roles, content, integrations (no billing) Day-to-day brand ops. Brand Moderator Brand-specific Read/CRUD limited content/users (no configs) Content approver. Brand User Brand-specific Personal profile, limited actions End-user (e.g., customer). Guest None Read-only public content Anonymous visitor. Implementation
- Tables:
users: id, email, brand_id (nullable for super admins), role_id roles: id, name, brand_id (null for global), permissions (JSON array, e.g., ['users:read', 'configs:write']) user_roles: user_id, role_id (for multi-role support) - Enforcement: Middleware checks
req.user.brand_id === resource.brand_idand permission matrix. - Libraries: CASL (JS) or
casbinfor dynamic policy evaluation.
2. Naming Conventions
Consistent naming ensures clarity and automation (e.g., linters, CI/CD).
Database (PostgreSQL)
- Tables:
{entity}_{brand_id?}or always includebrand_idFK.- Core:
users(withbrand_id),posts(withbrand_id). - Brand-specific:
brand_configs(JSON for themes/flags).
- Core:
- Indexes: Composite on
(brand_id, entity_id)for isolation. - Schemas: Optional
brand_{slug}schema for heavy customization (e.g., e-commerce tables).
Code (Node.js/TypeScript)
- Modules:
src/brands/{brand_slug}/for custom logic; shared insrc/core/. - Endpoints:
/api/v1/{brand_slug}/{resource}(e.g.,/api/v1/acme/users).- Fallback:
{brand_slug}from subdomain (e.g.,acme.example.com).
- Fallback:
- Constants:
BRAND_ACME = 'acme';in enums. - Variables: Prefix brand-scoped:
brandUserId,getBrandConfig(brandId). - Files:
user.service.ts,brand-aware/user.controller.ts.
Infrastructure
- Services/Queues:
{brand_slug}-{service}(e.g.,acme-emails-queuein Redis/Kafka). - Configs:
brands/{slug}.yamlfor per-brand env vars. - Domains:
{brand_slug}.platform.comor custom CNAME.
Category Example Rule API Path /api/v1/acme/posts{brand_slug}required.Table posts (brand_id FK)Always brand_idindex.Env Var BRAND_ACME_API_KEYUpper snake_case, prefixed. 3. Migrations
Use tenant-aware migrations to apply changes safely across brands without downtime. Tool: Node.js with db-migrate or TypeORM migrations.
Strategy
- Shared Schema Migrations: Apply to all brands atomically.
- Brand-Specific: Queue per-brand if needed (rare).
- Process:
- Add
brand_idto new tables by default. - Backfill for existing data.
- Use Row-Level Security (RLS) policies post-migration.
- Add
Migration Template (db-migrate)
// 001_add_brand_posts.js exports.up = async (db) => { await db.runSql(` ALTER TABLE posts ADD COLUMN brand_id UUID REFERENCES brands(id); CREATE INDEX idx_posts_brand_id ON posts(brand_id); -- RLS: CREATE POLICY brand_isolation ON posts USING (brand_id = current_setting('app.current_brand_id')::uuid); `); }; exports.down = async (db) => { /* Rollback */ };Workflow
- Dev: Local DB with sample brands.
- Staging: Migrate all brands in parallel (use
db-migrate multi-tenantplugin). - Prod:
- Blue-green deploy.
- Run migration with
SET app.current_brand_id = ?in transactions. - Rollout: 10% brands → 100%.
- Tools: Liquibase for complex diffs; pg_cron for scheduled backfills.
Handling Brand Onboarding/Offboarding
- Onboard: Seed
brandstable, copy shared data. - Offboard: Soft-delete (
deleted_at), vacuum DB.
4. Guardrails
Prevent cross-brand leaks, abuse, and failures. Enforced at multiple layers.
Security Guardrails
Guardrail Implementation Rationale Data Isolation RLS policies + brand_idchecks in queries/middleware.No cross-brand reads/writes. Auth JWT with brand_idclaim; brand-scoped sessions.Use Auth0/Okta multi-tenant. Rate Limiting Per-brand Redis counters (e.g., 1000 req/min/brand). Prevent one brand DoS. Input Validation Zod/Joi schemas with brand_idinjection protection.SQLi/XSS. Operational Guardrails
Guardrail Implementation Rationale Feature Flags LaunchDarkly/FF4J per-brand (e.g., enable_acme_feature).Gradual rollouts. Audit Logs auditstable:{actor_id, brand_id, action, before/after}.Compliance (GDPR/SOC2). Monitoring Prometheus metrics per-brand (e.g., errors_total{brand="acme"}). Alerts on anomalies.Proactive ops. Circuit Breakers opossumlib: Per-brand service calls.Isolate failures. Data Retention Cron: Purge old data per-brand policy. Cost/privacy. Enforcement Code Snippet (Middleware)
app.use(async (req, res, next) => { const brandId = getBrandIdFromReq(req); // subdomain/header if (!brandId) return res.status(400).json({ error: 'Brand required' }); req.brandId = brandId; // Set RLS context await db.query('SELECT set_config("app.current_brand_id", $1, true)', [brandId]); next(); });Deployment & Scaling
- Infra: Kubernetes namespaces per-brand (heavy users); shared for light.
- Cost Allocation: Tag resources by
brand_id. - Next Steps: Implement PoC with 2 sample brands; test isolation.
This architecture scales to 1000+ brands. Customize based on your stack! Questions?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.