Concepts Multitenancy - osama1998H/Moca GitHub Wiki

Multitenancy

Schema-per-tenant isolation, SiteContext, per-site connection pools, and tenant resolution.

Schema-Per-Tenant Model

Each Moca site (tenant) gets its own PostgreSQL schema within a shared database cluster. This provides strong data isolation without the overhead of separate database instances.

PostgreSQL Cluster
├── Schema: site_alpha     (Site Alpha's tables)
├── Schema: site_beta      (Site Beta's tables)
└── Schema: site_gamma     (Site Gamma's tables)

Connection Isolation

  • Each site has its own pgxpool.Pool
  • AfterConnect callback sets search_path to the site's schema
  • Separate pools isolate prepared statement caches between tenants
  • Pool registry manages lifecycle (create, get, evict idle)

Site Resolution

Three strategies for determining which site a request belongs to:

Strategy Example Config
Subdomain alpha.moca.local Default
Header X-Moca-Site: alpha API clients
Path /site/alpha/api/... Shared domain

SiteContext

Every request carries a SiteContext containing:

  • Site name
  • Database pool (pre-configured with correct schema)
  • Redis key prefix
  • User context
  • Configuration overrides

Redis & Search Isolation

  • Redis: Keys prefixed with site name (e.g., alpha:cache:MetaType:User)
  • Meilisearch: Indexes named {site}_{doctype} (e.g., alpha_Customer)

Site Management

moca site create mysite          # Create new site (schema + seed core doctypes)
moca site list                   # List all sites
moca site drop mysite            # Drop site schema
moca site use mysite             # Set default site for CLI

Related