Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

A service that stores customer orders must handle 10x more writes within two years. One PostgreSQL primary is near its limit. Design a horizontal scaling approach.

I would partition the orders by a key that matches how they are accessed, usually customer id, so each request touches one partition. A routing layer or library maps the key to the right database, cross-partition queries go to a separate read model or search index, and resharding is planned from the start by using many logical shards mapped onto fewer physical databases. Where latency allows, asynchronous processing smooths write spikes. Existing data moves into shards without downtime through a copy, dual-read verification and cutover per shard.

Why this question is asked

A single PostgreSQL primary can go a long way, but there is a ceiling: all writes go to one machine, and when growth is ten times in two years, a bigger machine will not be enough. Partitioning, also called sharding, spreads writes across several databases. It is a big decision, because the shard key shapes the system for years. Interviewers ask this design question to see whether we can choose a key, route requests, handle queries that span shards, plan for resharding and move data safely. In this answer, we will go through each of these in order, ending with the migration the follow-up asks about.

1A Quick Recap: Partitioning Writes

Sharding splits one large dataset into parts, called shards, each stored in its own database. Each shard holds a subset of rows, for example all orders of a range of customers, and handles the writes for them. Ten shards give roughly ten times the write capacity, as long as writes spread evenly and each request needs only one shard.

Those two conditions are what the design is about. A request that needs data from all shards is slow and complex, and a shard that receives far more traffic than others, a hot shard, limits the whole system just as the single primary did.

2Choosing a Key That Matches Access Patterns

We look at how orders are read and written. Almost every operation is per customer: create an order, list my orders, show order 123 of customer 9. So customer id is a natural shard key: all of a customer's orders live in one shard, and each operation touches one database.

We check that the key spreads well. Millions of customers spread evenly when hashed, but a few very large business customers might each place thousands of orders a day; they need attention, for example a dedicated shard. For a multi-tenant business system, tenant id plays the same role. A key like order date would be a bad choice: all new orders go to the newest shard, which becomes the hot shard.

Order ids must still be unique across shards, so we use ids that do not depend on one database's sequence, such as UUIDs or ids that embed the shard number, which also lets us find an order's shard from its id alone.

3Routing and Logical Shards

Requests must reach the right database. A small routing library inside the service, or a routing layer in front of the databases, computes the shard from the key. To make resharding possible later, we route in two steps: the key hashes into one of many logical shards, say 1,024, and a mapping table assigns logical shards to physical databases, at first 4.

Java
int logicalShard(long customerId) {
return Math.floorMod(Long.hashCode(customerId) * 0x9E3779B9, 1024); // spread, 0..1023
}
// Mapping kept in configuration or a small table
// logical 0-255 -> orders-db-1, 256-511 -> orders-db-2, 512-767 -> orders-db-3, 768-1023 -> orders-db-4
DataSource route(long customerId) {
return physicalFor(logicalShard(customerId));
}
// In Spring, an AbstractRoutingDataSource can pick the DataSource per call
// from a key the service sets before the transaction starts.
Step throughTwo-step routing
  1. Order serviceknows the customer id
  2. Routing libraryhash -> logical shard 0..1023
  3. Mapping tablelogical shard -> physical database
  4. Physical databases4 today, 8 or 16 later, without rehashing

4 layers, from the top down. Step through them one at a time.

Notice why the extra step matters. When we need more capacity, we add databases and move whole logical shards to them by changing the mapping, without rehashing every customer. Moving logical shard 300 from db-2 to db-5 touches a known set of rows.

4Queries That Span Shards

Some queries do not fit the key. Customer support searches orders by email or order number, finance needs totals per day across all customers, and operations wants all orders stuck in a state. Running these against every shard and merging results works for rare admin queries, but it is slow and loads every database.

The usual design is a separate read model. Each shard publishes order changes as events, for example with change data capture or an outbox table, and a consumer builds a search index or an analytical store with all orders. Cross-shard queries go there, accepting a delay of seconds.

5Smoothing Spikes With Asynchronous Processing

Not every write must happen during the request. If an order creates follow-up writes, such as loyalty points, analytics records and notification entries, those can be published as events and processed by consumers at a steady rate. The request writes only the order itself, so the shard handles spikes better, and the queue absorbs bursts that would otherwise hit the database all at once. This only works where the business accepts the delay, so we keep the order record itself synchronous.

6Migrating Existing Data Without Downtime

The follow-up asks how to move data from the single database into shards with no downtime. The safe approach goes shard by shard and keeps a way back at each step. We start by making the application write to both places: every change still goes to the old database, which remains the source of truth, and is also applied to the new shard. Then a backfill job copies historical rows into the shards, in batches, with checks that it does not overload the old primary.

Next, we compare: for a share of reads, the service reads from both and logs differences, until the differences are zero for long enough. Then we switch reads for one logical shard range to the new databases, then make the new shard the source of truth for writes, and keep writing to the old database for a while as a fallback. Finally, after a quiet period, we stop the old writes and remove the old data.

Step throughMoving a shard range without downtime
  1. Dual writeold database stays the source of truth
  2. Backfill history in batchesthrottled, resumable
  3. Shadow reads match for a week?
    YesSwitch reads for this rangeNoFix differences, keep comparing
  4. Make the new shard the source of truthold writes kept as fallback
  5. Stop old writes, clean upthen the next range

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

7Follow-up questions

How would you migrate existing data into shards without downtime?

Shard range by range: dual-write new changes to the old database and the new shard, backfill history in throttled batches, compare with shadow reads until there are no differences, switch reads, then switch the source of truth for writes while keeping the old database updated as a fallback, and finally stop the old writes. Change data capture from the old database is an alternative to dual writes in the application, and it avoids missing writes from code paths we forgot.

Why not use PostgreSQL's built-in table partitioning?

Declarative partitioning splits one table into smaller tables inside the same database. It helps with maintenance and with queries that touch recent data, but all partitions still live on one server, so it does not add write capacity. Sharding across servers is what spreads writes.

What happens to transactions that touch two customers?

If both customers may be on different shards, a single database transaction is no longer possible. We avoid such operations where we can, or model them as a saga, a sequence of local transactions with compensating actions, or with an outbox and idempotent consumers.

8Conclusion

In this answer, we designed horizontal write scaling for an orders service. We partition by a key that matches access patterns, such as customer id, route through a library with many logical shards mapped to fewer physical databases so resharding means moving shards rather than rehashing, serve cross-shard queries from a separate read model built from events, and smooth spikes with asynchronous processing. Existing data moves without downtime range by range with dual writes, backfill, shadow reads and a staged cutover.

What to say in the interviewAbout 80 seconds aloud

Open with

Since all writes go to one primary, I would partition the orders across several databases. The key has to match access: almost everything is per customer, so I would shard by customer id, check that large customers do not create hot shards, and use globally unique order ids such as UUIDs or ids that encode the shard.

Then, if they want more

Routing would be a library in the service, two-step: hash the customer id into one of about 1,024 logical shards, and map logical shards to physical databases, four at first. That makes resharding a matter of moving logical shards, not rehashing. In Spring, an AbstractRoutingDataSource can pick the data source per call.

Queries that span shards, like support search or finance totals, go to a separate read model fed by events from an outbox or change data capture. Follow-up writes like loyalty points become asynchronous events to smooth spikes.

For the migration, I would go range by range: dual write with the old database as source of truth, backfill history in throttled batches, compare with shadow reads until they match, switch reads, then switch the source of truth while still writing the old database as a fallback, and finally clean up.

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 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 "A service that stores customer orders must handle 10x more writes within two years. One...": https://scrivio-interview-library.netlify.app/spring-boot/scalability/8aee459085/