Quick revision
The short answer
Shard by tenant_id with a directory: small tenants are packed onto shared shards and the few large tenants get dedicated shards, so placement can change per tenant. In Java we resolve the tenant from the request (a token claim or the host name), look up its shard, bind it to the request and select the DataSource with Spring's AbstractRoutingDataSource. Global data lives in a separate shared database, and operations such as migrations, monitoring and tenant moves are planned per shard from the start.
What to remember
In this answer, we designed sharding for 50,000 tenants with a directory keyed by tenant_id, packing small tenants onto shared shards and giving large ones dedicated shards. In Spring, a filter resolves the tenant from the token or host, looks up its shard and binds it, and AbstractRoutingDataSource picks the right pool; the binding must hold for the whole transaction and be set explicitly in background jobs. Global data lives in its own database or is replicated to shards, and migrations, monitoring and tenant moves are planned per shard.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Shard by tenant_id with a directory: small tenants are packed onto shared shards and the few large tenants get dedicated shards, so placement can change per tenant. In Java we resolve the tenant from the request (a token claim or the host name), look up its shard, bind it to the request and select the DataSource with Spring's AbstractRoutingDataSource. Global data lives in a separate shared database, and operations such as migrations, monitoring and tenant moves are planned per shard from the start.
Why this question is asked
Multi-tenant SaaS is the most natural case for sharding, because almost every query already belongs to one tenant. The difficulty is in the details: tenants differ in size by orders of magnitude, the routing must never send a query to the wrong tenant's data, and the operational work multiplies with each shard. Interviewers ask this to see whether we can design both the data placement and the Spring code, and whether we think about the day-two operations. In this answer, we will choose the sharding strategy, follow a request through the routing code, look at the pitfalls of tenant context, place the global data, and plan the operations.
1Choosing the Strategy: Directory Sharding by Tenant
The shard key is tenant_id, because nearly every query is scoped to one tenant and all of a tenant's rows should live together, so joins and transactions stay on one shard. The question is how to map tenants to shards. Hashing would spread 50,000 tenants evenly by count, but not by load: one enterprise tenant may be larger than 10,000 small ones together, and a hash cannot give it its own shard.
So we use a directory, a small table that maps each tenant_id to a shard_id. New small tenants are assigned to the shared shard with the most room. Large tenants are placed on dedicated shards. If a tenant grows, we move it, which changes one directory row after the data is copied. For example, we might start with 8 shared shards holding about 6,000 tenants each and 3 dedicated shards for the three largest customers.
| tenant_id | shard_id | Notes |
|---|---|---|
| 17 | shared-03 | small tenant, packed with about 6,000 others |
| 18 | shared-01 | small tenant |
| 900 | dedicated-01 | largest customer, own database server |
| 4211 | shared-03 -> shared-07 | being moved: writes frozen for a few seconds |
2Routing a Request in Spring
Each request goes through three steps. First, we resolve the tenant: from a claim in the JWT, such as tenant_id, or from the host name, such as acme.example.com. Second, we look up the shard in the cached directory. Third, we bind that shard to the current request so the data layer can use it. Spring gives us AbstractRoutingDataSource for the last step: it is a DataSource that, each time a connection is requested, calls determineCurrentLookupKey() and delegates to the target DataSource registered under that key.
Notice the IllegalStateException when no tenant is bound. A routing DataSource with a default target that silently serves unbound requests is how one tenant's data ends up in another tenant's shard. Failing loudly is safer. Also notice the finally block: servlet threads, and virtual threads too, run one request after another, so a value left in the ThreadLocal would leak into the next request. The JPA EntityManagerFactory sits on top of the routing DataSource, so repositories do not change at all. Each shard database also stores tenant_id on every row and every query filters by it, so even a routing mistake cannot show one tenant another tenant's rows on a shared shard.
3Keeping the Tenant Bound for the Whole Transaction
The routing DataSource decides when a connection is first requested, and in a Spring transaction that happens when the transaction begins. From then on, the transaction keeps the same connection. So the tenant must be bound before the transaction starts and must not change inside it; switching tenants halfway through a @Transactional method would keep using the first shard's connection. A good rule is one tenant per transaction, enforced by a check.
Background work is where this breaks most often. A @Scheduled job, a Kafka listener or an @Async method runs on a thread that never passed through the filter, so TenantContext is empty. Each of those must set the tenant explicitly: the Kafka message carries tenant_id in a header, and the listener binds it in a try and finally before calling the service. For @Async, a TaskDecorator can copy the context to the worker thread. A job that processes all tenants loops over the directory and binds each tenant in turn, with one transaction per tenant.
4Where Global Data Lives
Some data belongs to no tenant: subscription plans, feature flags, currencies, the tenant directory itself. We keep it in a separate small global database with its own DataSource, used by its own repositories, and we never join it to tenant data in SQL. If tenant queries need some of it in joins, such as a reference table of countries, we replicate it to every shard as read-only copies, refreshed when it changes. This keeps every tenant query on a single shard.
5Planning the Operations
Every operational task now happens per shard. Schema migrations run against each shard: Flyway or Liquibase is invoked once per shard DataSource, in a controlled rollout so that a broken migration stops after the first shard, and the application must tolerate shards being on two schema versions for a short time. Monitoring is per shard, with dashboards for CPU, connections, latency and replication lag broken down by shard, plus per-tenant metrics so we spot a tenant that is outgrowing a shared shard. And we need a tool to move a tenant: copy its rows to the target shard while capturing changes, verify, freeze writes for that tenant for a few seconds, switch the directory row, and unfreeze. That tool should be built before it is needed, because the first big customer will need it at the worst moment.
8 messages in order. Play them, or step through them one at a time.
6Follow-up questions
How do you stop connection pool counts exploding with many shards?
Each application instance holding a HikariCP pool of 20 connections to each of 11 shards means 220 connections per instance, and 50 instances mean 11,000 connections, far more than PostgreSQL handles well. We keep per-shard pools small, such as 3 to 5 connections, because each instance only sends a share of traffic to each shard, and we put PgBouncer in transaction mode in front of each shard so many client connections share a few hundred server connections. With many more shards, we can route requests to service instances by shard, so each instance only connects to a subset.
What happens if the directory cache is stale during a tenant move?
The move process freezes writes for that tenant before switching, and the old shard records that it no longer owns the tenant. A service with a stale cache that writes to the old shard gets a clear error, refreshes the directory and retries. Without such a guard, writes could land on the abandoned copy and be lost.
Why not use one schema per tenant instead?
With 50,000 tenants, schema per tenant means 50,000 copies of every table, which strains the catalog, migrations and connection handling. It can work for a few hundred large tenants, but for many small ones a shared table with a tenant_id column is far simpler.
7Conclusion
In this answer, we designed sharding for 50,000 tenants with a directory keyed by tenant_id, packing small tenants onto shared shards and giving large ones dedicated shards. In Spring, a filter resolves the tenant from the token or host, looks up its shard and binds it, and AbstractRoutingDataSource picks the right pool; the binding must hold for the whole transaction and be set explicitly in background jobs. Global data lives in its own database or is replicated to shards, and migrations, monitoring and tenant moves are planned per shard.
Open with
I would shard by tenant_id using a directory rather than a hash, because tenant sizes are very uneven. A directory table maps each tenant to a shard, so small tenants get packed onto shared shards and the few very large ones get dedicated shards, and moving a tenant later is a copy plus one row change.
Then, if they want more
In the Java code, a servlet filter resolves the tenant from the JWT claim or the host name, looks up the shard in a locally cached directory, and stores it in a request-scoped context. An AbstractRoutingDataSource returns that shard as its lookup key, so it picks the right HikariCP pool, and JPA and the repositories do not change.
It throws if no tenant is bound instead of using a default, and the filter clears the context in finally. The tenant has to be bound before the transaction starts, because the connection is chosen then, so I enforce one tenant per transaction.
Kafka listeners, scheduled jobs and async tasks don't pass through the filter, so they set the tenant explicitly from a message header or by looping over the directory. Global data like plans and feature flags lives in a separate database with its own DataSource, or is replicated to every shard if it is needed in joins.
Every row still carries tenant_id as a second safety net. Operationally, migrations roll out shard by shard, monitoring is per shard and per tenant, and we build a tenant move tool early. For connection counts I keep pools small and put PgBouncer in front of each shard.
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.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
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 "A Spring Boot SaaS application on one PostgreSQL database must scale to 50,000 tenants...": https://scrivio-interview-library.netlify.app/databases/partitioning-and-sharding/40238b98a0/