Skip to content
TheChatArchiveThe Chat Archive
Grok 4.1 Fast· xaiHugging Face Frontier Reasoning Traces

Create a multi-brand architecture: roles, naming, migrations, and guardrails.

  1. User

    Create a multi-brand architecture: roles, naming, migrations, and guardrails.

  2. 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_id as 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 central roles table and junction tables for permissions. Global roles override brand-specific ones.

    Role Hierarchy

    RoleScopePermissionsDescription
    Super AdminGlobalAll actions (brands, users, configs, billing)Platform owner; manages brands.
    Brand OwnerBrand-specificManage users/roles in brand, configs, billing for brandBrand founder/CEO.
    Brand AdminBrand-specificCRUD users/roles, content, integrations (no billing)Day-to-day brand ops.
    Brand ModeratorBrand-specificRead/CRUD limited content/users (no configs)Content approver.
    Brand UserBrand-specificPersonal profile, limited actionsEnd-user (e.g., customer).
    GuestNoneRead-only public contentAnonymous 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_id and permission matrix.
    • Libraries: CASL (JS) or casbin for 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 include brand_id FK.
      • Core: users (with brand_id), posts (with brand_id).
      • Brand-specific: brand_configs (JSON for themes/flags).
    • 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 in src/core/.
    • Endpoints: /api/v1/{brand_slug}/{resource} (e.g., /api/v1/acme/users).
      • Fallback: {brand_slug} from subdomain (e.g., acme.example.com).
    • 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-queue in Redis/Kafka).
    • Configs: brands/{slug}.yaml for per-brand env vars.
    • Domains: {brand_slug}.platform.com or custom CNAME.
    CategoryExampleRule
    API Path/api/v1/acme/posts{brand_slug} required.
    Tableposts (brand_id FK)Always brand_id index.
    Env VarBRAND_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

    1. Shared Schema Migrations: Apply to all brands atomically.
    2. Brand-Specific: Queue per-brand if needed (rare).
    3. Process:
      • Add brand_id to new tables by default.
      • Backfill for existing data.
      • Use Row-Level Security (RLS) policies post-migration.

    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

    1. Dev: Local DB with sample brands.
    2. Staging: Migrate all brands in parallel (use db-migrate multi-tenant plugin).
    3. Prod:
      • Blue-green deploy.
      • Run migration with SET app.current_brand_id = ? in transactions.
      • Rollout: 10% brands → 100%.
    4. Tools: Liquibase for complex diffs; pg_cron for scheduled backfills.

    Handling Brand Onboarding/Offboarding

    • Onboard: Seed brands table, 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

    GuardrailImplementationRationale
    Data IsolationRLS policies + brand_id checks in queries/middleware.No cross-brand reads/writes.
    AuthJWT with brand_id claim; brand-scoped sessions.Use Auth0/Okta multi-tenant.
    Rate LimitingPer-brand Redis counters (e.g., 1000 req/min/brand).Prevent one brand DoS.
    Input ValidationZod/Joi schemas with brand_id injection protection.SQLi/XSS.

    Operational Guardrails

    GuardrailImplementationRationale
    Feature FlagsLaunchDarkly/FF4J per-brand (e.g., enable_acme_feature).Gradual rollouts.
    Audit Logsaudits table: {actor_id, brand_id, action, before/after}.Compliance (GDPR/SOC2).
    MonitoringPrometheus metrics per-brand (e.g., errors_total{brand="acme"}). Alerts on anomalies.Proactive ops.
    Circuit Breakersopossum lib: Per-brand service calls.Isolate failures.
    Data RetentionCron: 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?

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.