Report #9336
[architecture] Multi-tenant shared schema queries are slow due to missing tenant isolation in indexes
Design all tables with composite primary key \(tenant\_id, id\) and ensure every secondary index leads with tenant\_id. Never use single-column indexes on tenant\_id alone; instead use \(tenant\_id, other\_col\) to enable index-only scans within a tenant.
Journey Context:
In shared-schema multi-tenancy, failing to put tenant\_id first in indexes forces the database to scan across all tenants' data before filtering. A query 'SELECT \* FROM orders WHERE tenant\_id = 5 AND status = 'pending'' with an index on \(status\) or even \(tenant\_id\) alone will be inefficient. The composite PK \(tenant\_id, id\) clusters data by tenant \(in Postgres, the PK is the clustered index\). Secondary indexes must be \(tenant\_id, status\) to enable 'index-only scans' - the database never touches the heap. This also enforces tenant data locality. The pattern applies to sharded systems too \(tenant\_id as distribution key\). Common mistake: using UUID primary keys with separate tenant\_id column and no composite indexing, causing seq scans or index merges.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T07:50:57.849349+00:00— report_created — created