Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

An orders table for a multi-tenant SaaS has grown to 4 billion rows and write throughput is near the limit of one PostgreSQL primary. You are asked to shard it. How do you choose the shard key, and what problems must the Java services handle afterwards?

For a multi-tenant SaaS orders table, tenant_id is usually the best shard key, because almost every query and transaction is scoped to one tenant and it spreads load across shards, but very large tenants can create hot shards, so the mapping must allow moving or splitting them. Afterwards the services must handle queries without the shard key as scatter-gather or through a separate read model, live without cross-shard transactions, generate globally unique ids such as UUIDv7, and route through a directory or hashing scheme that supports resharding.

Why this question is asked

Sharding is one of the few database changes that changes the programming model of every service touching the data. Before it, the database gives us joins, transactions and unique ids for free across all rows; after it, those guarantees hold only within one shard. Interviewers ask this question to see whether we pick the key from the access patterns and whether we know the problems that follow us into the Java code for years. In this answer, we will recap what sharding means, choose a shard key, and then go through scatter-gather queries, transactions, ids and resharding.

1A Quick Recap of Sharding

Sharding splits one logical table across several independent databases, called shards. Each shard holds a subset of the rows and is its own PostgreSQL primary, so write capacity grows with the number of shards. The shard key is the column whose value decides which shard a row lives on. Everything else depends on that choice, because a query that includes the shard key can go to one shard, while a query that does not must ask every shard.

2Choosing the Shard Key

A good shard key has two properties. It matches the main access pattern, so most queries and transactions touch one shard, and it spreads load evenly. For a multi-tenant SaaS product, tenant_id usually wins on both counts. Users work inside their own tenant, so nearly every query already filters by tenant, and joins between a tenant's orders, order lines and customers stay on one shard if those tables are sharded by the same key.

The risk is skew. If one tenant produces 20 percent of all orders, its shard is far busier than the others and may hit the same limit we were escaping. So we look at the size distribution before deciding. Options include placing the largest tenants on their own shards, or using a compound key such as tenant_id plus a hash of the order id for those tenants, accepting that their queries may span a few shards.

Candidate shard keys for orders
KeySingle-shard queriesLoad spreadMain risk
tenant_idalmost allgood, uneven tenantsvery large tenants create hot shards
order_id hashonly lookups by idexcellentevery tenant query is scatter-gather
customer_idper-customer viewsgoodtenant reports span all shards
created_at rangerecent orderspoorall new writes hit one shard
tenant_id matches the access pattern; skew is handled separately.

3Queries Without the Shard Key

Some queries do not include the tenant: an internal support search for an order number, a global revenue report, a lookup by payment reference from a webhook. Without the shard key, the router has to send the query to every shard and merge the results, which is called scatter-gather. Its latency is the slowest shard's latency, and its load is multiplied by the number of shards, so with 32 shards one such query costs 32 queries.

We keep these rare. Lookups by another identifier get a small global index table, such as payment reference to tenant_id, so the router can find the shard first. Cross-tenant reports read from a separate read model, for example a warehouse fed by change data capture, instead of the shards.

Java
// the router needs the tenant to pick a shard
Order find(long tenantId, UUID orderId) {
return shardFor(tenantId).orders().findById(orderId); // one shard
}
Order findByPaymentRef(String ref) {
long tenantId = paymentIndex.tenantFor(ref); // small global lookup
return shardFor(tenantId).orders().findByPaymentRef(ref); // still one shard
}

4No More Cross-Shard Transactions

A transaction in PostgreSQL covers one database, so it cannot atomically change rows on two shards. With tenant_id as the key, most operations naturally stay inside one tenant, which is a strong argument for it. Operations that must span shards, such as moving credit between two tenants, need a different design: a saga, a sequence of local transactions with compensating actions if a later step fails, usually driven by events through an outbox. Two-phase commit across shards exists but is slow and fragile, so it is rarely the answer.

In the Java code this means the transaction boundary must be visible. A @Transactional method should only touch one shard, and a test or a guard in the routing layer can fail fast when a transaction tries to use a second shard.

5Globally Unique Ids

A single PostgreSQL sequence no longer works, because each shard has its own. We need ids that are unique without coordination. UUIDv7 is a good default: it is 128 bits, generated in the application, and starts with a millisecond timestamp, so new ids are roughly ordered and B-tree indexes stay compact, unlike random UUIDv4. A Snowflake-style 64-bit id, made of a timestamp, a worker number and a counter, is smaller but needs worker numbers to be assigned. Either way, ids are generated before the insert, which also helps idempotent retries.

6Planning for Resharding From the Start

The number of shards will change, and big tenants will need to move. If the shard is computed as hash(tenant_id) % 8, adding a ninth shard moves almost every tenant. So the mapping should be indirect. A directory, a table that maps each tenant to a shard, lets us move one tenant at a time and give a big tenant its own shard. Consistent hashing with many virtual buckets is the other common approach: tenants map to one of, say, 4096 buckets, buckets map to shards, and moving a bucket moves only its tenants.

Step throughRouting a request after sharding
  1. Request has tenant_id?
    YesLook up shard in the directoryNoFind tenant via a global index
  2. Tenant being moved?
    YesFollow the migration stateNoUse its shard
  3. Run the query on one shardtransaction stays within that shard

3 steps in order. Play them, or step through them one at a time.

The routing layer, whether a Spring library in each service or a proxy, reads that directory and caches it, so services never compute shards themselves.

7Follow-up questions

How would you move one large tenant to its own shard with no downtime?

Create the new shard, copy the tenant's existing rows in the background, and keep them in sync with change data capture filtered to that tenant. When the copy has caught up, verify row counts and checksums, then briefly block that tenant's writes (a few seconds), wait for the last changes to apply, switch the directory entry to the new shard and unblock. Reads can switch before writes, and the old rows are kept until the move is confirmed, so we can switch back.

Would you shard before trying anything else?

Usually not. Partitioning the table within one PostgreSQL instance, archiving old orders, moving reads to replicas and tuning write paths can buy years. Sharding is right when write throughput or data size on one primary is truly the limit, as in this scenario.

Should every table be sharded by tenant_id?

The tables that are queried together with orders should be, so their joins stay local. Small global reference tables, such as currencies, can be copied to every shard instead.

8Conclusion

In this answer, we saw that the shard key should follow the main access pattern and spread load, which makes tenant_id the usual choice for SaaS, with special handling for very large tenants. After sharding, queries without the key become scatter-gather and should be rare or served by a read model, transactions must stay within one shard or become sagas, ids must be globally unique such as UUIDv7, and a directory or bucketed mapping makes resharding and tenant moves possible.

What to say in the interviewAbout 80 seconds aloud

Open with

I would choose the shard key from the access patterns, and for a multi-tenant SaaS that is usually tenant_id. Almost every query and transaction is scoped to one tenant, so with orders, order lines and related tables all sharded by tenant, joins and transactions stay on one shard, and tenants spread load well.

Then, if they want more

The risk is skew, so I would look at tenant sizes first and plan to put the largest tenants on their own shards. Then I would prepare the services for four problems.

Queries without the tenant become scatter-gather across every shard, so I would keep them rare, add small global index tables for lookups like payment reference to tenant, and move cross-tenant reporting to a separate read model fed by CDC. There are no cross-shard transactions, so each transactional method must stay in one shard, and the rare cross-tenant operations become sagas.

A single sequence no longer works, so ids come from the application, UUIDv7 or a Snowflake-style generator. And I would plan resharding from day one: a directory mapping tenants to shards, or hashing into many buckets, so we can move one tenant or bucket at a time instead of rehashing everything.

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 "An orders table for a multi-tenant SaaS has grown to 4 billion rows and write throughput...": https://scrivio-interview-library.netlify.app/databases/database-scaling/222f3294d7/