Scrivio Interview library
DesignAdvanced6 min read · updated 12 November 2026

Your multi-tenant SaaS has one huge tenant with 60 percent of rows and thousands of tiny tenants. Queries with WHERE tenant_id = ? have unstable performance. What design options do you consider?

With one tenant holding 60 percent of rows and thousands holding a few each, no single plan for WHERE tenant_id = ? is right for both: the big tenant wants scans built for volume, the small ones want quick index lookups. In the short term we force custom plans, add composite indexes that lead with tenant_id and add statistics; structurally we partition by tenant with the big one in its own partition, or move very large tenants to their own database or shard, and route their different workload separately. The choice weighs the operational cost of more databases against noisy-neighbour risk and any contractual isolation.

Why this question is asked

Multi-tenant SaaS products almost always end up with a long tail of small customers and a few giants, and the database feels that skew long before the product team does. Unstable performance on tenant-filtered queries is the usual first symptom. Interviewers ask this design question to see whether we can separate a quick mitigation from a structural fix, and whether we weigh operations and contracts, not just query plans. In this answer, we will see why skew breaks a single plan, go through the short-term fixes, then the structural options, and finish with how to choose.

1Why Skew Makes One Plan Wrong

The planner chooses a plan from its estimate of how many rows a condition matches. For tenant_id = 17, one of the small tenants, that might be 300 rows out of 500 million, so an index scan is perfect. For tenant_id = 1, the giant, it is 300 million rows, and reading them through an index row by row would be far slower than a sequential scan or a bitmap scan.

PostgreSQL's statistics do record the giant as a most common value, so a plan built for the actual value is usually sensible. The instability comes from plans that do not see the value. A prepared statement can switch to a generic plan, which assumes an average tenant, and that average is wrong for everyone: too big for the small tenants and much too small for the giant. Join plans built from that average are often the worst part, with nested loops that explode on the large tenant.

Same query, different tenants
TenantRowsGood planRisk with a shared plan
tenant 1 (giant)300 million (60%)parallel or bitmap scan, hash joinnested loop over millions
typical tenanta few thousandindex scan, nested loopfull scan of a huge table
tiny tenanta few hundredindex scansame as typical
A plan based on an average tenant fits nobody.

So the symptom is not just slow, but unpredictable: the same endpoint is fast for one customer and slow for another, or fast in the morning and slow after the connection pool has warmed up.

2Short-Term Fixes

The cheapest fix is to make sure each execution is planned for its real tenant. Setting plan_cache_mode = force_custom_plan for the application role stops PostgreSQL from switching to a generic plan, at the price of planning every query, usually well under a millisecond.

Next come indexes that lead with tenant_id. A composite index such as (tenant_id, created_at) lets every tenant-scoped query, including the giant's, read a narrow, ordered slice instead of scanning: the giant's 'last 50 orders' becomes 50 index entries rather than a sort over 300 million rows. Statistics help the estimates stay honest, a higher statistics target on tenant_id and extended statistics when tenant_id is correlated with other filtered columns such as status.

SQL
ALTER ROLE saas_app SET plan_cache_mode = force_custom_plan;
CREATE INDEX CONCURRENTLY orders_tenant_created_idx ON orders (tenant_id, created_at DESC);
ALTER TABLE orders ALTER COLUMN tenant_id SET STATISTICS 1000;
CREATE STATISTICS orders_tenant_status (mcv) ON tenant_id, status FROM orders;
ANALYZE orders;

These steps are reversible and can ship in days. They do not change the fact that the giant shares a table, vacuum cycles, caches and I/O with everyone else, which is what the structural options address.

3Structural Option: Partition by Tenant

Partitioning splits one logical table into several physical tables, called partitions, and the planner skips partitions that cannot match, which is called partition pruning. If the giant gets its own partition, it gets its own statistics, its own indexes and its own vacuum schedule, and queries for small tenants never touch its 300 million rows. The rest can be spread with hash partitioning so each partition stays a manageable size.

SQL
CREATE TABLE orders (tenant_id bigint NOT NULL, id bigint NOT NULL, created_at timestamptz NOT NULL,
PRIMARY KEY (tenant_id, id))
PARTITION BY LIST (tenant_id);
CREATE TABLE orders_t1 PARTITION OF orders FOR VALUES IN (1); -- the giant on its own
CREATE TABLE orders_rest PARTITION OF orders DEFAULT PARTITION BY HASH (tenant_id);
CREATE TABLE orders_rest_0 PARTITION OF orders_rest FOR VALUES WITH (MODULUS 8, REMAINDER 0);
-- ... remainders 1 to 7

Notice that the primary key must include the partition key, tenant_id, because unique constraints on a partitioned table must contain it. That is natural in a multi-tenant schema where every query filters by tenant anyway. The migration itself is real work on a large table, usually done by building the new partitioned table and moving data in batches or with logical replication.

4Structural Option: A Dedicated Database or Shard

For the largest tenants, the strongest isolation is their own database, or their own shard in a sharded setup such as Citus. The giant then has its own hardware, its own maintenance windows and its own capacity planning, and its heavy reports can never slow down the small tenants. The application needs a routing layer that maps a tenant to a data source, which Spring supports with AbstractRoutingDataSource.

Workload differences can be handled in the same layer. If the giant runs large exports and analytics, those can go to a read replica or a separate query path designed for volume, such as pre-aggregated tables, while its interactive traffic keeps the normal path.

5Choosing Between the Options

Each structural step adds operational cost. Partitioning keeps one database but adds partition management and a migration. A dedicated database per large tenant means more backups, upgrades, monitoring and schema migrations to roll out, and tooling that can run a migration across many databases reliably. The benefit is protection from the noisy neighbour, the large tenant whose load hurts everyone else, and sometimes it is not optional: some enterprise contracts require data isolation or a specific region.

So I would start with the short-term fixes, measure whether instability disappears, and decide structurally with numbers: the giant's share of database time, how fast it grows, and what its contract demands. A common outcome is partitioning when one or two tenants stand out, and a dedicated database when a tenant is large enough, or contractually required, to justify its own operations.

6Follow-up questions

Does partitioning alone fix generic plans?

It helps, because with runtime partition pruning the executor skips partitions that cannot match even in a generic plan, and the giant's partition has its own statistics. But a generic plan inside the shared partitions can still be built for an average tenant, so force_custom_plan or good indexes remain useful.

Why not give every tenant its own schema or database?

With thousands of tenants, schema-per-tenant or database-per-tenant multiplies catalog size, connections and migration effort enormously. It suits a few large tenants, not a long tail of small ones, which is why the hybrid split is common.

How do you detect a growing giant before it hurts?

Track rows and database time per tenant, for example from a nightly count per tenant and pg_stat_statements broken down by tenant through query tags or application metrics. Set a threshold, such as a tenant passing 10 percent of rows, that triggers a design review.

7Conclusion

In this answer, we saw that strong data skew between tenants makes any single plan wrong for either the giant or the small tenants, especially when prepared statements fall back to generic plans. Short-term fixes are forced custom plans, composite indexes leading with tenant_id and better statistics. Structural options are partitioning with the giant in its own partition, or a dedicated database or shard with routing, and the choice weighs the operational cost of more databases against noisy-neighbour risk and contractual isolation.

What to say in the interviewAbout 90 seconds aloud

Open with

The root problem is data skew: one tenant has 60 percent of rows and thousands have a handful, so the best plan for tenant_id = ? depends completely on the value.

Then, if they want more

For a tiny tenant I want an index scan; for the giant I want a scan built for volume. Plans that do not see the value, mainly generic plans from prepared statements, assume an average tenant and are wrong for everyone, which is why performance is unstable.

Short term, I would set plan_cache_mode to force_custom_plan for the application role, add composite indexes that lead with tenant_id and include the sort column, like tenant_id and created_at, and raise statistics or add extended statistics where tenant_id correlates with status.

Structurally, I would consider list partitioning by tenant with the giant in its own partition and the rest in a hash-partitioned default, which gives it separate statistics, indexes and vacuum.

For tenants that are very large or need contractual isolation, I would move them to a dedicated database or shard with a routing data source, and send their exports to a replica. The trade-off is operational: more databases mean more upgrades, backups and migrations, against the noisy-neighbour risk.

I would start with the cheap fixes, measure, and decide on the structure with data on each tenant's share and growth.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Your multi-tenant SaaS has one huge tenant with 60 percent of rows and thousands of tiny...": https://scrivio-interview-library.netlify.app/databases/query-optimization/377fc61859/