Course contentsShow
← Databases & SQL
Lesson 695 of 1,9536. Query Performance and IndexingFree lesson

Multi-tenant Indexing Strategies

Optimize indexes for workloads requiring strict data isolation between multiple tenants.

In this lesson, you will learn how to design indexes that maintain strict data isolation between tenants while keeping your query performance lightning-fast.

The Tenant Isolation Challenge

In a multi-tenant database, your tables often contain data for hundreds or thousands of different clients. A common mistake is creating indexes on columns (like created_at or status) without considering the tenant_id. If your queries always filter by tenant_id to ensure data isolation, an index that doesn't start with that ID forces the database to scan through rows belonging to other tenants before finding yours.

The Prefix Strategy

To optimize for multi-tenancy, your indexes should almost always follow the Tenant-Prefix Pattern. By placing tenant_id as the leading column in your composite indexes, you effectively partition the index tree by tenant. This allows the database engine to jump straight to the segment of the index belonging to the specific tenant, ignoring all other data entirely.

Consider a system tracking orders. Instead of indexing by order_date alone, use a composite index:

-- Poor performance: The DB may scan across all tenants first
CREATE INDEX idx_orders_date ON orders(order_date);

-- Optimized: The DB engine navigates directly to the tenant's subtree
CREATE INDEX idx_tenant_orders ON orders(tenant_id, order_date);

Why This Matters

When you use a tenant_id prefix, the database uses "Index Partition Trimming" logic. Because the tenant_id is the first column, the index is naturally grouped by tenant. This not only improves speed but also ensures that your query execution plan is perfectly scoped to the tenant requesting the data.

Even if your queries include other filters, as long as tenant_id is the leading edge of your composite index, you prevent "noisy neighbor" syndrome where one tenant’s large data set slows down the index lookups for everyone else. Always include the isolation key as the leftmost column in your indexing strategy to ensure both security and efficiency.

Key Takeaway: Always include tenant_id as the first column in your composite indexes to enforce strict data isolation and force the database to ignore irrelevant tenant data during index traversal.