Multi-Tenant PXBaas Platform

Updated at:

PXBaas Multi-Tenant Edition leverages the distributed capabilities of PolarDB-X to deliver a middle-ground architecture that combines shared infrastructure with physical database isolation per tenant. Through a three-layer mechanism of Kong gateway tenant routing, application-layer RLS injection, and database-layer CCL rate limiting, it supports hundreds of tenants on a single deployment while maintaining strict security isolation and fair resource allocation.

Why multi-tenancy

When a SaaS platform provisions backend services for each tenant, it faces a fundamental cost-versus-security tradeoff:

  • Dedicated deployment is too expensive: 100 tenants = 100 independent systems, with monthly infrastructure costs exceeding CNY 5,000. Small tenants have less than 5% resource utilization, leaving the majority of compute capacity idle.

  • Shared single-database is too risky: When all tenants share one database, a slow query from one tenant degrades performance for everyone; a misconfigured RLS policy can expose the entire dataset; and per-tenant throttling is not possible.

  • A middle ground is needed: Share infrastructure to reduce costs, yet isolate databases physically for security. This is exactly the design goal of PXBaas Multi-Tenant Edition.

Architecture

The multi-tenant edition uses a layered architecture with clearly defined responsibilities at each layer:multi-tenant-architecture

  • Client layer: supabase-js / mini-program SDK / curl, or any HTTP client. Requests carry a JWT token (Authorization header) and a tenant identifier (X-Tenant-Id header).

  • Gateway layer (Kong): The single entry point for all requests (port 8000). Handles JWT verification, tenant status checks, cross-tenant consistency validation, and per-tenant QPS token-bucket rate limiting before routing valid requests to backend services.

  • Application service layer: Auth, MysqlREST, Storage, Realtime, and Edge Functions are deployed as shared services. Each component routes to the correct tenant context using the tenant_id claim internally.

  • Data layer (PolarDB-X): Platform management data resides in the _platform database. Each tenant's business data resides in an isolated tenant_xxx database, providing physical separation.

Key design decisions

  • Platform-level keys + per-tenant keys: The platform owns a global anon_key and service_role_key for administrative operations. Each tenant receives a 32-byte random jwt_secret at creation time, used exclusively for signing and verifying that tenant's JWTs.

  • Physical database isolation: Every tenant has its own database tenant_{tenant_id}. The application layer switches context with USE tenant_{tenant_id} before executing operations.

  • Shared service deployment: Auth, MysqlREST, Storage, Realtime, and Edge Functions are deployed as shared services. Requests are routed to the correct tenant database based on the tenant_id claim in the JWT.

Four-layer isolation for security

The multi-tenant edition enforces four progressive layers of isolation to guarantee that tenant data can never be accessed across boundaries:security-isolation

Layer 1: Network isolation

  • The MySQL port is accessible only from the internal network and is not exposed to the public internet.

  • The Kong Admin API is restricted to internal network or VPN access. Direct public access is prohibited.

  • The Studio management console requires Basic Auth to prevent unauthorized access.

Layer 2: Kong gateway isolation

  • Per-tenant secret verification: Each tenant uses an independent jwt_secret. Kong extracts the X-Tenant-Id from the request header, then verifies the JWT signature with that tenant's secret. Requests with mismatched secrets are rejected immediately.

  • X-Tenant-Id consistency check: Kong validates that the X-Tenant-Id in the request header matches the tenant_id claim in the JWT payload, preventing tenant identity spoofing.

  • Tenant status check: Kong queries the tenant status (active/suspended/deleted). Requests from non-active tenants receive an immediate 403 response.

Layer 3: Application isolation

  • Database switching: MysqlREST executes USE tenant_{tenant_id} before processing each request, ensuring all SQL operations are scoped to the tenant's database.

  • RLS injection: Even within a tenant's database, row-level security policies are injected to filter data rows based on the user identity in the JWT.

  • Forced tenant_id filter: All queries are appended with a mandatory WHERE tenant_id = ? clause as a defense-in-depth measure. Even if the USE statement fails, no data from other tenants can be leaked.

Layer 4: Database physical isolation

  • Independent databases: Each tenant owns an isolated tenant_{tenant_id} database that is physically separated from all other tenants.

  • REVOKE of dangerous privileges: Tenant database users have CREATE USER, GRANT, and DROP DATABASE privileges revoked. Even in the event of SQL injection, privilege escalation is not possible.

Four-layer progressive throttling

To prevent any single tenant from exhausting shared resources, the multi-tenant edition implements four progressive layers of throttling:rate-limiting

Layer 1: Kong gateway QPS limiting

  • Default limit of 100 QPS per tenant, based on the Token Bucket algorithm.

  • Requests exceeding the limit receive HTTP 429 Too Many Requests.

  • The threshold can be adjusted per tenant through the Admin API.

Layer 2: PolarDB-X CCL (database)

The native CCL (Concurrency Control Language) feature of PolarDB-X enforces per-tenant QPS limits and slow query protection at the database layer.

-- Set the QPS limit for tenant tenant_001 to 200
CREATE CCL_RULE tenant_001_qps
  ON `tenant_001`.*
  TO 'app_user'@'%'
  FOR SELECT, INSERT, UPDATE, DELETE
  WITH MAX_CONCURRENCY = 200;

-- Automatically kill slow queries that exceed 5 seconds
CREATE CCL_RULE tenant_001_slow
  ON `tenant_001`.*
  TO 'app_user'@'%'
  FOR SELECT
  WITH MAX_CONCURRENCY = 10, WAIT_TIMEOUT = 5000;
  • Per-tenant QPS limits prevent any single tenant from exhausting database connections.

  • Slow queries are automatically killed after a 5-second timeout, returning 503 Service Unavailable.

Layer 3: MysqlREST connection pool

  • Each tenant has an independent connection pool with a default of 5 database connections.

  • Idle connections are automatically reclaimed after 30 minutes to reduce resource consumption.

  • Queries are subject to a 5-second timeout. Queries exceeding this limit are terminated and an error is returned.

Layer 4: Resource quota limits

The platform maintains per-tenant resource quotas in the _platform database's tenant_quotas table:

Quota

Default

Description

Storage

1 GB

Combined database and file storage

Edge Functions

20

Maximum number of deployable serverless functions

WebSocket connections

100

Concurrent Realtime WebSocket connections

Database connections

5

MysqlREST connection pool size

Login rate

60/min

Auth service login/signup request limit

All quotas can be adjusted in real time through the Admin API. Kong polls for quota changes every 60 seconds and applies updates automatically:

# Adjust the QPS quota for tenant_001 to 500
curl -X PUT http://<supabase_host>:<supabase_port>/api/admin/tenants/tenant_001/quotas \
  -H "Authorization: Bearer <service_role_key>" \
  -H "Content-Type: application/json" \
  -d '{
    "kong_qps_limit": 500,
    "storage_limit_gb": 5120
  }'

Cost advantages and elastic scaling

Cost comparison

Dimension

Dedicated (100 tenants)

Multi-tenant shared

Savings

Compute

100 instances x 0.5C = 50C

1 instance x 4C = 4C

~90%

Monthly cost (est.)

CNY 5,000+

CNY 500+

~10x reduction

Operations complexity

100 systems managed independently

1 unified system

-

Elastic scaling

  • Online scaling: PolarDB-X supports adding CN (compute nodes) and DN (data nodes) online. The scaling operation is fully transparent to clients and requires no downtime.

  • Locality resource groups: Dedicate specific DN nodes to VIP tenants using the Locality feature of PolarDB-X. Tenant data is pinned to designated node groups, providing physical-level resource guarantees.

  • Read-write splitting: Read-only replicas absorb read traffic while writes go to the primary node. Load is balanced automatically.

  • Online DDL: Schema changes execute online without locking tables or disrupting active requests.

Use cases

Scenario

Description

Multi-tenant benefits

Vibe Coding platform

AI-assisted programming platform where each user or project has an isolated backend environment

Sub-second tenant provisioning, usage-based billing, and CCL rules to prevent AI-generated inefficient queries from impacting the platform

Online Education SaaS

Each training institution has isolated student, course, and order data

Physical database isolation meets education industry compliance requirements; elastic scaling handles enrollment peaks

E-commerce SaaS

Multi-merchant platform where each merchant manages products, orders, and customers independently

Complete data isolation between merchants, auto-scaling during promotions, and dedicated resources for VIP merchants

Enterprise Collaboration

Each enterprise or team has isolated document, messaging, and task spaces

Realtime enables collaborative editing; WebSocket quotas guarantee real-time communication quality

IoT Platform

Device data from each enterprise customer is stored and analyzed independently

Distributed architecture handles massive device data volumes; CCL prevents large analytical queries from interfering with each other

Low-code/No-code Platform

Each app creator has an independent database and API endpoint

REST APIs auto-map to database tables; Edge Functions enable custom logic extensions

Comparison with original Supabase

Dimension

Original Supabase

PXBaas Multi-Tenant Edition

Database engine

PostgreSQL (single-node)

PolarDB-X (MySQL-compatible distributed)

Multi-tenant support

Separate instance per project; cost scales linearly with tenants

Built-in multi-tenant management with shared deployment + physical DB isolation; cost scales sub-linearly

Horizontal scaling

Requires manual sharding or third-party solutions

Native distributed architecture; online CN/DN node addition with transparent horizontal partitioning

Resource guarantees

Depends on PostgreSQL configuration; no per-tenant resource isolation

Locality resource groups + CCL rate limiting; VIP tenants can be assigned dedicated DN nodes

Database-level rate limiting

No built-in mechanism; requires application-layer implementation

Native CCL rate limiting + automatic slow query kill; database-layer fairness enforcement

Cost model

Per-instance billing; 100 tenants = 100x the cost

Shared billing; 100 tenants share 1 infrastructure set at approximately 1/10 the cost of dedicated deployment