Scrivio Interview library
ScenarioAdvanced8 min read · updated 13 November 2026

A B2B platform shards by tenant through a directory, with one tenant never spanning shards. The largest enterprise tenant now fills 3.5 TB of a 4 TB volume on its dedicated shard, grows by about 150 GB a month and drives 70 percent of that shard's CPU at peak.

The directory cannot split a single tenant. What do you do in the next two months and in the long term, and how do you choose a second-level sharding key for this tenant?

In the next two months we buy time: scale the shard up, archive cold data past its retention, and move reporting reads to a replica, which together give us many months of headroom. In the long term we make the shard key hierarchical, (tenant_id, sub_key), so small tenants still live on one shard while this tenant can span several, choosing sub_key from the tenant's access patterns (an entity such as store or account that most queries filter on and that keeps transactions local, never a timestamp), and migrating one sub-range at a time with change capture and a fenced cutover.

Why this question is asked

Tenant-per-shard designs are simple and give each customer isolation, until one customer grows faster than any single machine. This scenario has a hard clock: 500 GB of headroom at 150 GB a month is about three months, and CPU is already at 70 percent. Interviewers ask it at senior level because it needs two plans at once, a quick one that is safe and a structural one that is right, plus a careful choice of the new key. In this answer, we will do the arithmetic, buy time safely, design a hierarchical key, choose the sub-key from real queries, deal with the queries that now span shards, and plan the migration.

1A Quick Recap and the Arithmetic

In directory sharding, a table maps each tenant to the shard that holds all of its data. Keeping a tenant on one shard is what makes the design pleasant: every query and transaction for a tenant is local, joins work, and foreign keys hold. The rule that a tenant never spans shards is also the problem, because this tenant's shard can only grow as far as one machine.

The numbers: 3.5 TB used of 4 TB leaves 0.5 TB. At 150 GB a month, that is a little over three months, and the volume should never run close to full because PostgreSQL needs room for vacuum, index rebuilds and WAL spikes, so the real deadline is closer to two months. CPU at 70 percent at peak means there is also little room for growth in load.

2The Next Two Months: Buying Time Safely

The short-term plan uses only low-risk, well-understood operations. First, scale up: cloud volumes can usually be enlarged online, for example from 4 TB to 8 TB, and the instance can move to a larger class during a short maintenance window or by failing over to a larger replica. That alone moves the disk deadline out by more than two years at the current rate.

Second, archive cold data. Enterprise tenants often keep years of closed orders, audit events or old documents that are rarely read. Data past its retention period can be deleted; older data that must be kept can move to a partitioned archive table on cheaper storage, or to object storage such as S3 in Parquet files queried through the warehouse. If 30 percent of the data is closed records older than two years, that frees about 1 TB.

Third, offload reads. Reporting and export queries are often the most expensive part of the CPU. Sending them to a read replica, or better to the warehouse, can take a large share of the 70 percent off the primary. Each of these steps is reversible and buys months, which we then use to do the long-term change properly.

Short-term options for the large tenant's shard
ActionEffectRisk
Grow volume 4 TB -> 8 TBdisk deadline moves out by about two yearslow, usually online
Larger instancemore CPU and memory headroomshort failover
Archive closed records older than 2 yearsfrees perhaps 1 TBneeds retention rules agreed
Reports to replica or warehouseremoves heavy reads from the primaryreplica lag for reports
Buy time with reversible steps, then use it for the structural fix.

3The Long Term: A Hierarchical Shard Key

Scaling up has a ceiling and a price, so the real fix is to let a tenant span shards when it must, without changing anything for the thousands of small tenants. We extend the key to two levels, (tenant_id, sub_key). For a normal tenant, the directory still has one row: tenant to shard. For a large tenant, the directory maps the tenant plus a range or bucket of sub_key to a shard, for example tenant 77 with buckets 0 to 255 of hash(store_id) on shard 12, buckets 256 to 511 on shard 13, and so on.

SQL
-- directory with an optional second level
CREATE TABLE tenant_shard (
tenant_id bigint NOT NULL,
bucket_from int NOT NULL DEFAULT 0, -- 0..1023 of hash(sub_key)
bucket_to int NOT NULL DEFAULT 1023,
shard int NOT NULL,
epoch bigint NOT NULL,
PRIMARY KEY (tenant_id, bucket_from)
);
-- small tenant: one row (42, 0, 1023, shard 5)
-- large tenant: several rows (77, 0, 255, shard 12), (77, 256, 511, shard 13), ...

Routing code first looks up the tenant; if there is one row covering all buckets, it is done, exactly as before. Only for a split tenant does it compute the sub_key bucket and pick the matching row. Hashing the sub_key into buckets, rather than using raw ranges of it, keeps the spread even even if store ids were assigned in order.

4Choosing the Sub-Key From Access Patterns

The sub-key decides which queries stay on one shard, so we choose it from the tenant's real workload, not from the schema. We look at the slow query log and pg_stat_statements for this tenant and ask: which column do most queries and transactions filter on, besides tenant_id? For a retailer it might be store_id: orders, stock and staff all belong to one store, and a checkout transaction touches one store. For a services company it might be account_id or project_id.

A good sub-key has three properties. Most queries filter on it, so they stay on one shard. Transactions stay within one value of it, so we do not need distributed transactions. And it has many values with no single giant one, so data spreads; one store with half of all orders would just recreate the problem one level down. A timestamp is the classic wrong choice: all new writes would go to the newest range, making one shard hot while the others hold only history.

5Queries That Now Span Shards

Some queries will still cover the whole tenant: a company-wide sales report, a search across all stores, an export. On the split tenant these become scatter-gather queries, sent to every sub-shard and merged in the application, which is slower and more complex. We find them early by tagging queries in the logs with whether they filter on store_id. Many of them belong in a read model or the warehouse anyway: change data capture with Debezium into Kafka, then into a reporting store, gives tenant-wide views without touching the shards. The few that must stay online get explicit scatter-gather code with timeouts and pagination.

6Migrating One Sub-Range at a Time

We move the tenant in pieces. For each bucket range, we bulk copy its rows to the new shard, stream ongoing changes with logical replication or change data capture until the target is caught up, then do a fenced cutover: block writes for that range on the source, wait for in-flight transactions, apply the final changes up to the recorded source position, switch the directory with a new epoch, and unblock. We verify with row counts and checksums per chunk before deleting the source copy. Moving 64 buckets at a time, each cutover pauses writes for that slice for a second or two. Because this is the platform's largest customer, we agree the plan, the maintenance windows and the rollback criteria with them in advance, and we run the whole procedure on a copy of their data first.

7Follow-up questions

How would you spot the next tenant heading for this limit a year earlier?

Track size, growth rate and CPU per tenant, not only per shard, and project each tenant's time to reach a threshold, such as 50 percent of the largest volume we are comfortable running. A weekly report of tenants whose projected date is within 12 to 18 months, plus an alert when a tenant's share of its shard's CPU passes a threshold, gives enough warning to plan a split as routine work instead of an emergency.

Why not move this tenant to Citus or another distributed SQL database?

That is a valid long-term option, and Citus in particular supports distributing tables by a column. But it is a platform change with its own migration, operations and testing, and it still requires choosing a distribution key with the same care. The hierarchical directory reuses what the team already runs; the decision depends on how many tenants will need it.

What happens to foreign keys and unique constraints across sub-shards?

Constraints that span sub-shards can no longer be enforced by the database. Constraints within one store still hold. For global uniqueness, such as an invoice number across the tenant, we use an id generator or a small central table, and we accept that cross-store references are checked by the application.

8Conclusion

In this answer, we bought time for the oversized tenant with reversible steps: a larger volume and instance, archiving cold data and moving reports to a replica or warehouse. For the long term we made the shard key hierarchical, (tenant_id, sub_key), so small tenants stay on one shard and large ones span several, chose the sub-key from real queries so transactions stay local and writes spread, never a timestamp, moved tenant-wide reports to a read model, and migrated one bucket range at a time with change capture, a fenced cutover and verification, agreed with the customer.

What to say in the interviewAbout 90 seconds aloud

Open with

The clock is short: half a terabyte of headroom at 150 gigabytes a month is about three months, and really two because the volume must never run full.

Then, if they want more

So for the next two months I buy time with reversible steps: grow the volume and the instance, archive closed records past their retention to cheaper storage, and move reporting and exports to a replica or the warehouse, which also takes load off the 70 percent CPU.

Long term, a single tenant has to be able to span shards, so I make the key hierarchical, tenant_id plus a sub_key. Small tenants keep one directory row; the big tenant gets rows per bucket of hash(sub_key), each pointing to a shard.

I pick the sub_key from the tenant's real queries: something like store or account id that most queries filter on and that keeps a transaction on one value, with many values and no giant one. Never a timestamp, because the newest range would take every write.

Tenant-wide queries become scatter-gather, so I find them early and serve most of them from a read model fed by change data capture. Then I migrate one bucket range at a time: copy, stream changes, fenced cutover with a new epoch, checksum verification, and I agree the plan and windows with the customer.

About this answer

Last updated
13 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 official documentation for the version you use. 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 "The directory cannot split a single tenant. What do you do in the next two months and in...": https://scrivio-interview-library.netlify.app/architecture/partitioning-and-replication/1feddc8786/