Replicas, Partitions, and Shards
choose_read_target for the address just saved
Imagine updating your shipping address, seeing a confirmation, and then opening your account page only to find the old address. You refresh the page, and the new one appears. The change was saved, but for a moment the application made it look as though nothing had happened.
Baodium began receiving complaints like this shortly after its database team introduced read replicas. The replicas were supposed to relieve PostgreSQL of some of the growing read traffic. They were doing that successfully, yet customers occasionally saw older account information immediately after making changes.
The engineers traced one complaint through the database. The address update had committed on the primary. The next request, which retrieved the account page, had gone to a replica that had not yet applied the change. By the time the customer refreshed again, replication had caught up.
The problem came from a reasonable scaling decision. Caching had removed many of Baodium’s repeated catalog reads, as we saw in Chapter 5, but customers still generated requests that could not use an existing cached result. They searched using new filters, opened less popular products, and retrieved information specific to their accounts. Those requests continued reaching PostgreSQL, and connection-acquisition time on the primary had begun increasing.
The team introduced replicas so eligible reads could run elsewhere, leaving more capacity on the primary for writes and operations that needed current state. What they had not fully defined was which reads were eligible.
That distinction takes us into three related parts of database design. We will begin with replicas and the freshness of their data, then examine partitioning for large tables, and finally consider what happens when a single database can no longer handle the writes assigned to it.
Understanding the Primary’s Workload
Before adding more database capacity, the engineers needed to understand what PostgreSQL was spending its time doing.
A database can become slow for several reasons. Queries might be expensive, transactions may occupy connections for too long, or many concurrent operations may be competing for CPU, memory, locks, and storage.
The amount of data is another consideration. A table containing several years of historical records can make index maintenance and archival expensive, even when customer traffic is relatively low.
These problems lead to different designs. More storage does little for connection contention, and adding read replicas does not resolve a write transaction that spends most of its time waiting for a lock.
Figure Figure shows the sources of demand reaching Baodium’s database.
At Baodium, the Catalog team’s query measurements showed that individual reads were still relatively inexpensive. The growing connection-acquisition time came largely from the number of requests competing to use the primary.
The engineers looked at connection occupancy, query duration, transaction duration, database CPU usage, and storage activity. They also separated requests according to the operation each one supported.
This led to an important finding. Browsing queries were consuming a substantial share of the primary’s capacity, even though many of them could tolerate slightly older data. Moving those queries to replicas would reduce contention for the writes and required reads that had to reach the primary.
The decision made sense for the measured workload. Other database problems would need different responses.
Choosing Storage From the Operations It Supports
It is worth considering how this decision fits into the rest of Baodium’s data architecture.
Checkout changes related order, payment, and inventory records while enforcing business rules. A transactional database is useful here because the application needs atomic updates, constraints, and reliable record relationships.
Catalog search has different requirements. Customers search by keywords, filter on product attributes, and expect relevant results from a large collection. A dedicated search index can serve those queries efficiently, while Catalog Service continues to own the authoritative product records.
Product images present another access pattern. Their bytes are relatively large, and a published image can often be treated as immutable. Object storage, combined with stable content-specific URLs, is a natural fit.
Configuration data differs again. Once a configuration revision has been published, its contents can be immutable and cached by revision number, while the pointer to the active revision requires a freshness policy.
We encountered these choices in Chapters 3 and 5. They matter here because introducing another database copy is useful only when its guarantees match the operation that will read it.
A search index might still contain a product that was recently withdrawn from sale. That may be acceptable for discovery, provided checkout checks current sale eligibility before accepting an order. Similarly, a replica can serve an older description without necessarily causing harm. It cannot decide whether a payment or inventory reservation is valid based on an outdated copy.
The application needs to know which service owns each decision and which copies are suitable for the reads that lead up to it.
Replicas, Partitions, and Shards Address Different Problems
The engineers considered three techniques as Baodium’s database requirements grew.
These techniques can be combined. A shard may contain partitioned tables and have its own read replicas. There is no requirement to introduce them in a particular sequence.
For Baodium’s immediate read problem, replicas provided additional capacity without dividing write ownership. Partitioning later addressed expensive historical-data maintenance. Sharding became relevant when the write rate and isolation requirements of merchant orders began approaching the limits of one primary.
How PostgreSQL Replicas Receive Changes
In the setup Baodium used, one PostgreSQL primary accepted application writes, while two replicas served eligible read requests.
Figure Figure shows the arrangement.
PostgreSQL records database changes in a write-ahead log, usually called WAL. The log supports crash recovery and provides the changes that physical replicas apply to their own copies of the database.
When a transaction commits on the primary, the corresponding WAL records become part of the primary’s log. A standby receives those records and replays them to update its local database state.
There are several points in that process worth distinguishing.
First, the primary generates WAL records. Next, the standby receives the relevant records and writes them according to its replication configuration. Finally, the standby replays the changes so that new queries can observe them.
A replica can therefore have received a transaction’s WAL without having applied it yet.
This is the distinction that mattered during Baodium’s address-change incident. The primary had committed the new address, but the replica selected for the account page had not replayed the commit when the read began.
With asynchronous replication, the primary can acknowledge a committed transaction before a standby has received or replayed its WAL.1
Replicas also consume resources while receiving and replaying changes. Queries running on a standby compete with WAL replay for CPU, memory, and storage access. A reporting query may interact with replay and cleanup activity in ways that require additional PostgreSQL configuration.
Adding a replica therefore creates another place to execute reads, but its actual capacity must be measured under both the read workload and the replication activity it will receive.
What Each Read Must Guarantee
Before routing a read to a replica, we need to know what the caller expects to observe.
Consider three requests.
A customer opens a product description that was last edited yesterday. Seeing a copy that is a second behind the primary is unlikely to change the customer’s decision.
Another customer updates a shipping address and immediately opens the account page. If the page displays the previous address, the customer may conclude that the update was lost.
A third customer attempts to reserve the final available unit of a product. That operation must make its decision against the inventory state owned by Inventory Service.
The three requests have different requirements, although all of them may ultimately involve reading a database record.
Figure Figure illustrates the interval in which a replica can return the earlier version of a record.
Baodium classified its read paths according to what an older result could affect.
The routing decision belongs to the service operation. A global rule that sends every SELECT to a replica cannot distinguish a browsing lookup from a read needed inside a transaction.
That is especially dangerous when a handler reads some state before updating it. If the read comes from a lagging replica and the write goes to the primary, the application may make its decision using information that was already outdated.
Authoritative Reads and Transactions
Sending an inventory query to the primary does not automatically prevent overselling.
Imagine two customers trying to reserve the last pair of shoes. Both requests could read an available quantity of one before either one updates the row.
If the application treats the read and the update as independent operations, both customers may receive a successful reservation.
Chapter 3 introduced the conditional update used to prevent this race. The same mechanism applies here.
UPDATE inventory
SET available = available - 1
WHERE product_id = $1
AND available > 0
RETURNING product_id;The statement changes the quantity only when stock is still available. If no row is returned, the reservation did not succeed.
The transaction must also record the reservation’s operation identity, so that a repeated checkout request does not reserve another unit.
Routing determines which database owns the current state. The transaction and its constraints determine whether the requested change is permitted.
This is why checkout continues calling Inventory Service rather than reading around it through whichever replica appears fastest.
Read-Your-Writes
The address-change incident involved a guarantee known as read-your-writes.
After a client successfully changes a value, that client’s later reads should reflect the change.
The simplest implementation may be to return the committed value as part of the write response. If the customer saves a shipping address, the API can return the address that was recorded, allowing the page to display it immediately.
That solves the first display, but what happens when the customer refreshes the page?
The refresh may reach a different application instance and a replica that has not replayed the commit. The application needs another way to preserve the guarantee.
One option is to route sensitive reads to the primary for a period after the customer writes.
That can be a useful practical solution when replication lag is usually short. However, a fixed delay cannot guarantee freshness if the replica falls further behind than the chosen interval.
A more precise approach ties the read to the write’s replication position.
In PostgreSQL, the primary can report its current WAL position through pg_current_wal_lsn(), while a standby reports its replay progress through pg_last_wal_replay_lsn().
After the write commits, the application can obtain a WAL position that is known to cover that commit. The read router then selects a replica only after it has replayed through the required position.
The position needs to come from the same primary history and must be captured after the transaction commits. A position obtained before commit does not establish that the commit itself has been replayed.
The read must also begin a new snapshot after the replay condition is satisfied. A transaction using an earlier snapshot may continue seeing the earlier data.
Failover introduces another consideration. PostgreSQL WAL positions belong to a timeline and database history. A router cannot blindly compare positions from unrelated timelines after a primary changes.
The routing token and validation procedure need to account for the source timeline and what the new primary has retained.
These details make position-based routing useful for systems with substantial read-your-writes traffic. For a relatively small number of sensitive account reads, using the primary is often simpler and easier to test.
Choosing Replicas and Handling Lag
Baodium’s router could now distinguish browsing reads from those that required more recent state.
For an eligible read, the router considered replicas that were reachable and met the operation’s freshness policy. It also needed to know when the eligibility information had been collected.
Suppose a replica reported low lag three minutes ago. That measurement does not establish that the replica is current now. It might have lost its replication connection shortly after the sample.
The routing observations therefore included the replica’s replay progress, connection health, and sample time. A background observer collected this information so customer requests did not each create another monitoring query.
What Replication Lag Means
Database dashboards often display a single value called replication lag. It is worth checking exactly how that value is calculated.
WAL positions can tell us how many bytes separate the primary’s current position from a standby’s received or replayed position. That difference measures log progress, although it does not tell us how many seconds the standby will need to catch up.
Time-based estimates have their own limitations.
PostgreSQL provides pg_last_xact_replay_timestamp(), which reports the timestamp of the last transaction replayed on the standby.
Subtracting it from the current time can be misleading when the primary is idle. If no new transactions have committed, the standby may be completely caught up while the apparent time difference continues increasing.
A heartbeat written periodically to the primary can provide another estimate. Each replica reads the heartbeat after replay, and the observer measures its delay. The estimate depends on the heartbeat interval, collection frequency, and clock behavior.
The team monitored WAL progress and time-based lag with those limitations in mind.
A low average or a recent heartbeat still cannot prove that one particular customer write is visible. A strict read-your-writes request uses the evidence associated with that write or a route to the authoritative database.
Protecting the Primary During Replica Failure
What happens when both read replicas become unavailable?
The simplest fallback is to send their traffic to the primary. Unfortunately, that may overwhelm the database the replicas were introduced to protect.
Suppose the replicas normally handle 80 percent of the eligible browsing traffic, while the primary handles 20 percent.
If all replica reads suddenly fall back to the primary, the primary receives the entire workload instead of its usual one-fifth share.
For that class of read, its offered request rate increases by a factor of five.
Those additional queries compete with payment state changes, inventory operations, reconciliation, and other requests that require the primary.
Baodium therefore gave primary fallback its own admission allocation. When that allocation was exhausted, the route returned its approved reduced or unavailable result instead of admitting an unbounded number of queries.
The routing procedure can be expressed without embedding database details in each application handler.
def choose_read_target(policy, observations, request):
if policy.requires_primary:
return primary_required.admit(
deadline=request.deadline
)
candidates = observations.eligible_replicas(
policy=policy,
maximum_sample_age=policy.sample_age_limit,
)
target = replica_admission.try_choose(
candidates,
deadline=request.deadline,
)
if target is not None:
return target
if policy.allow_primary_fallback:
target = primary_fallback.try_admit(
deadline=request.deadline,
)
if target is not None:
return target
raise ReadTemporarilyUnavailable()The methods are illustrative. The admission controls account for the query until its local database operation has finished and its resources have been released.
The replica observer must also verify any WAL position required by a read-your-writes request before declaring a replica eligible.
If a route permits an older result, that allowance belongs in the route’s contract. The router cannot silently relax the freshness requirement because its preferred replica is unavailable.
A route requiring authoritative state has a separate primary allocation and failure policy. Otherwise, a large volume of optional browsing fallback could consume the connections needed by checkout.
Replica Failover and Confirmed Writes
Read replicas also offer a potential recovery path when the primary fails.
The replica selected to become the new primary must be able to accept writes without creating an inconsistent history.
With asynchronous replication, a standby may be missing transactions that the old primary already acknowledged. If it is promoted before those records arrive, the new primary may begin accepting writes from an earlier database state.
Replay lag alone does not settle the durability question. A standby may already have received and durably stored WAL that it has not yet replayed. Recovery can replay that WAL before exposing the new primary.
The failover decision needs evidence about which committed records are available on the candidate and which acknowledged writes might be missing.
Synchronous Replication and Commit Acknowledgment
PostgreSQL supports synchronous replication, in which a transaction can wait for selected standby acknowledgments before reporting success.
The guarantee depends on the configuration.
When synchronous standbys are configured, the usual synchronous_commit=on mode waits for the required standby acknowledgment that the commit WAL has been flushed to durable storage.
With remote_apply, the transaction waits until the selected synchronous standby has replayed the commit, making it visible to new query snapshots.
Those are different promises. Receiving and durably storing WAL protects against certain loss scenarios, while replay determines when standby queries can observe the change.
The synchronous-standby configuration also determines which standbys must acknowledge a commit and how many acknowledgments are required. Without configured synchronous standbys, changing the setting alone does not establish a remote durability guarantee.
There is a latency cost. Waiting for another server adds network and standby processing to the commit path.
The team also needs a policy for standby failure. If the required synchronous standby becomes unavailable, writes may wait until the required acknowledgment can be obtained. Reducing the acknowledgment requirement changes the durability promise and needs an explicit operational decision.
Preventing Two Primaries From Accepting Writes
Promotion creates another risk. The former primary may recover after the replacement has started accepting writes.
If both can commit new transactions, the system now has two competing database histories.
This is called split brain.
The failover procedure must prevent the former primary from accepting writes before or as the replacement takes authority. That protection is called fencing.
Updating the application’s database endpoint is insufficient when old connections can still reach the previous primary.
Depending on the deployment, fencing may require stopping the old instance, revoking its write access, isolating it, or enforcing ownership through the database management system.
The key requirement is that the previous writer cannot resume accepting writes after the replacement becomes authoritative.
The ownership versions introduced in Chapter 3 serve a similar purpose for application workers. Later in this chapter, we will use them when moving records between shards.
Backups and Point-in-Time Recovery
Replication provides additional copies of current database state. Those copies generally apply the same changes as the primary, including changes made by mistake.
Suppose an archival job deletes the wrong month’s orders and commits successfully.
The replicas will ordinarily replay that deletion. Promoting one of them does not restore the deleted records.
PostgreSQL supports point-in-time recovery through a base backup and the WAL required to replay changes up to a selected recovery point.2
The operator can restore an isolated database to a point before the accidental deletion.
That gives the team access to the earlier records, but it creates another decision.
If new orders were accepted after the deletion, replacing production wholesale with the older backup would also remove those later orders.
The team may instead recover the missing records from the restored copy and reconcile them with the operations completed afterward.
The recovery plan needs a recovery-point objective (RPO), describing the acceptable amount of data loss, and a recovery-time objective (RTO), describing how long the service can take to become usable again.
A meaningful restore test starts a separate database from the backup and archived WAL, confirms the expected records exist, and runs representative application queries.
The team measures how long the restoration and required reconciliation take. These tests can reveal missing WAL segments, unusable backups, or application versions that cannot operate against the restored schema.
Replicas and backups therefore serve related but different recovery needs. Baodium needed both.
Partitioning a Growing Orders Table
The replica changes addressed read traffic. Another database problem appeared in the orders table, where six years of historical data had accumulated.
Baodium introduced a retention policy requiring orders older than 24 months to be removed from the active system under the approved archival process.
The existing maintenance job deleted expired rows in batches. It often ran through most of the night, generated substantial WAL, and left indexes requiring additional maintenance.
Adding read replicas would not make that deletion cheaper. The work was happening on the primary and had to be recorded in its transaction log.
The team considered dividing the orders table into monthly partitions.
Table partitioning allows an application to query a logical table whose rows are stored in separate physical tables. A partition key determines which physical table contains each row.
For orders, the creation date was a natural candidate because the retention policy removed whole periods of historical data.
Partitioning could also help monthly reporting queries. It introduced a complication for requests that retrieved an order only by its ID.
Choosing the Partition Key From Actual Queries
The team examined three representative operations.
-- Remove orders past the retention boundary
DELETE FROM orders
WHERE created_at < '2024-07-01 00:00:00+00';
-- Report on one calendar month
SELECT state, count(*), sum(amount_minor)
FROM orders
WHERE created_at >= '2026-06-01 00:00:00+00'
AND created_at < '2026-07-01 00:00:00+00'
GROUP BY state;
-- Retrieve an order by its public identifier
SELECT *
FROM orders
WHERE order_id = $1;The first operation removes old rows. The second reads one month’s records. The third has no date predicate at all.
A partition key that works well for the first two may do little for the third.
Table Table compares the candidates.
The engineers chose monthly range partitioning on created_at.
That allowed PostgreSQL to skip partitions outside a query’s date range, a behavior called partition pruning.
It also allowed the retention procedure to detach an entire expired month instead of deleting millions of rows individually.
The choice did not make order-ID lookups faster. Those queries would need another piece of the design.
Creating Monthly Partitions
PostgreSQL supports declarative range partitioning.
CREATE TABLE orders (
order_id uuid NOT NULL,
user_id uuid NOT NULL,
created_at timestamptz NOT NULL,
state text NOT NULL,
amount_minor bigint NOT NULL,
PRIMARY KEY (order_id, created_at)
) PARTITION BY RANGE (created_at);
CREATE TABLE orders_2026_01
PARTITION OF orders
FOR VALUES FROM ('2026-01-01 00:00:00+00')
TO ('2026-02-01 00:00:00+00');The first boundary is inclusive, and the second is exclusive. The next month begins exactly where the earlier partition ends.
The timestamps include explicit UTC offsets so the boundaries do not depend on a session’s local time zone.
The database team created future partitions ahead of time. Without an appropriate partition or deliberate default partition, an insert for a new date range fails.
A scheduled maintenance process created partitions three months ahead and alerted when fewer than two future partitions were available. Tools such as pg_partman can help automate this lifecycle.
The Uniqueness Problem
The primary key in the example contains both order_id and created_at.
There is a reason for that extra column.
In PostgreSQL, a unique constraint or primary key on a partitioned table must include every partition-key column. The individual partition indexes cannot independently enforce uniqueness across different physical partitions.
The constraint in our example therefore guarantees uniqueness of the pair (order_id, created_at).
It does not prevent the same order_id from appearing under two different creation timestamps.
If Baodium promises that an order ID identifies exactly one order across all months, the application needs another enforcement mechanism.
One option is a small, nonpartitioned directory that owns the globally unique order ID and records the order’s creation time.
CREATE TABLE order_directory (
order_id uuid PRIMARY KEY,
created_at timestamptz NOT NULL
);
CREATE INDEX order_directory_by_created_at
ON order_directory (created_at);Creating an order now inserts the directory entry and the partitioned order row in the same local database transaction.
If either insert fails, both are rolled back.
When the application later retrieves an order by ID, it first looks up the creation timestamp in the directory and uses that value to target the appropriate partition.
The directory adds an indexed write for every order and requires its own retention policy. Those costs belong in the database estimate.
For a system with relatively few point lookups, it may be cheaper to probe the monthly partitions instead. Baodium measured the frequency and latency of those lookups before introducing the directory.
The important consequence is that choosing a partition key affects constraints and access paths as well as maintenance.
Removing Expired Partitions
Once the table was partitioned by month, the retention job could detach an expired partition instead of deleting every row.
PostgreSQL supports DETACH PARTITION and, subject to its documented restrictions, DETACH PARTITION ... CONCURRENTLY.
After detachment, the old partition can be archived and eventually dropped according to the retention policy.
This avoids the repeated row-level deletes and associated maintenance of the original job.
The team still had to coordinate the operation with backups, dependent references, active queries, and the order directory.
Partitioning improved retention and date-range query behavior. All the partitions still lived under one database’s write capacity.
When that capacity became the limiting factor for another workload, Baodium had to consider a different architecture.
Sharding Merchant-Order Writes
The next scaling problem came from merchant orders.
Each completed customer checkout produced a merchant order for each merchant represented in the cart.
Merchants used those records to accept orders, update fulfillment, issue refunds, and settle payouts.
Those operations updated related records, including line items, fulfillment state, and the merchant’s payout ledger.
Initially, all merchant orders lived on one PostgreSQL primary.
At peak, the system processed approximately 3,000 merchant-order writes per second. The primary had sustained about 4,000 writes per second in workload tests after the team improved indexes and batching.
The measured headroom was becoming uncomfortable. Some of the largest merchants also ran bulk refunds and settlement jobs that consumed locks and I/O needed by smaller merchants.
Read replicas could serve reporting queries, but they could not perform the writes owned by the primary.
The database team began considering sharding, in which different databases own different subsets of records.
The difficult decision was which subset each database should own.
Choosing a Shard Key
Suppose a merchant requests a refund for one order.
The application needs the order, the related payment information, the merchant’s ledger, and the current refund policy.
If those records are on one shard, the local database can enforce the applicable constraints and commit its part of the change atomically.
If they are divided across several shards, the application must coordinate the update across databases.
The same issue arises during settlement. A merchant’s payout may depend on many orders and ledger entries. Baodium wanted that accounting operation to be local to one database where possible.
The team compared three candidate keys.
Sharding by merchant-order ID would distribute individual orders relatively evenly. However, a settlement operation would need records from many shards.
Sharding by merchant ID kept each merchant’s orders and ledger together. That allowed merchant-scoped transactions and portal queries to use one database.
The cost was uneven demand. A merchant generating much more traffic than the others could dominate the shard that owned its records.
A third approach could split a merchant across several sub-buckets. That would distribute its writes, but settlement would need to coordinate several partitions or databases.
Baodium chose merchant_id because local settlement was an important correctness requirement.
The team accepted uneven merchant sizes as a capacity risk that needed measurement.
We will see shortly how significant that risk became.
Operations That Cross Merchant Boundaries
The merchant shard owned its local order and payout records.
Some workflows still crossed merchant boundaries.
A customer checkout containing products from several merchants could produce merchant orders on different shards. The overall checkout workflow therefore needed durable coordination, using the operation records and saga principles from Chapter 3.
An administrative report spanning all merchants also needed data from several shards.
Global uniqueness could create another shared dependency. For example, if a tracking number had to be unique across all merchant orders, no individual shard could enforce that constraint for the whole system.
Those operations needed explicit designs. Sharding made merchant ownership more local, while the application took responsibility for the workflows outside that boundary.
Routing a Merchant to Its Shard
Once the shard key was chosen, every service handling a merchant order needed to locate the owning database.
An obvious first implementation is to hash the merchant ID and take the remainder after division by the number of shards.
That works until the number of shards changes.
With eight shards, the calculation uses a divisor of eight. Adding a ninth changes the assignment for many merchants, which means their records must be moved before the new rule can be used safely.
The team separated the stable assignment of merchants to logical buckets from the physical databases that owned those buckets.
Figure Figure shows the routing path.
Baodium used 1,024 virtual buckets. A stable hash mapped each merchant to one bucket, and an ownership directory mapped each bucket to a database.
Moving a bucket between databases then required updating its ownership record after migrating the associated data.
The code below illustrates the initial assignment.
import hashlib
BUCKET_COUNT = 1024
def bucket_for(merchant_id):
value = canonicalize_merchant_id(merchant_id)
digest = hashlib.sha256(
value.encode("utf-8")
).digest()
return int.from_bytes(digest[:8], "big") % BUCKET_COUNT
def locate_merchant(merchant_id, directory):
override = directory.merchant_override(merchant_id)
if override is not None:
return override
bucket = bucket_for(merchant_id)
return directory.bucket_owner(bucket)The canonical form of the merchant ID and the bucket count are part of the persisted routing contract.
Changing either one would require a planned migration, since the change could assign existing merchants to different buckets.
Python’s built-in hash() is not suitable for this persistent mapping when applied to strings under its usual randomized hashing behavior. Different processes can produce different results for the same string.
The ownership directory also records an epoch, or ownership version.
When a bucket moves, the directory advances the epoch. Routers cache ownership entries, but the receiving database validates the route’s epoch before accepting a write.
This is important because directory changes do not reach every application instance at exactly the same time.
A router holding an old entry must not continue writing to a database that has lost authority.
The directory also supports a merchant-level override, used when one large merchant needs its own shard. That override takes precedence over the normal bucket mapping.
The owning database must enforce the override’s transfer state as well. Otherwise, a router using an old bucket entry could bypass the new merchant assignment.
Uneven Traffic Across Shards
The initial capacity estimate looked encouraging.
Baodium planned eight shards, each tested at approximately 900 merchant-order writes per second.
In a perfectly balanced workload, the combined tested rate would be
writes per second.
That was much higher than the current peak of 3,000.
The production merchant distribution changed the calculation.
Baodium’s largest merchant generated about 18 percent of the merchant-order writes.
At 3,000 writes per second, that merchant contributed
writes per second.
Suppose the remaining 2,460 writes were distributed evenly across the eight shards. That contributes about 308 writes per second to each shard.
The shard containing the largest merchant would then receive approximately 848 writes per second, against its tested limit of 900.
The fleet average would be only 375 writes per second per shard.
A dashboard showing that average would make the system look comfortable, while the busiest shard had room for only about six percent more traffic under the same distribution.
The team began measuring write rates, transaction duration, connection occupancy, lock waits, and storage activity for each shard.
Those measurements showed which merchant workloads needed special attention.
Handling a Large Merchant
The engineers considered moving unrelated buckets away from the hot shard. That would reduce the background traffic, but the large merchant’s 540 writes per second would still reach one database.
Another option was to give that merchant a dedicated shard.
The ownership directory already supported merchant overrides, so the routing model could accommodate that change without altering the hash assigned to every other merchant.
At its current write rate, the merchant would fit comfortably within the dedicated database’s tested capacity.
Settlement would also remain local.
The third option was to split the merchant across several buckets. That offered more write distribution, but it would require a different settlement procedure and more complex queries for the merchant portal.
Baodium chose the dedicated shard.
The team also established a review trigger for a merchant whose own workload approached one database’s tested limit. At that point, simply moving the merchant would no longer provide enough headroom.
The decision illustrates why capacity planning must include the distribution of demand, particularly when tenants or customers have very different workload sizes.
Queries That Need Several Shards
Sharding by merchant made individual merchant operations simpler to route. It also complicated a page used by Baodium’s support team.
Operators wanted to view the 100 most recent merchant orders across the whole marketplace.
Those orders were now spread across eight databases.
A query containing one merchant ID could go directly to its owning shard. The support query had no merchant filter, so it needed information from several shards.
The service could send a bounded query to each shard and merge the results. This is called scatter-gather.
Each shard returns its 100 most recent orders under the same ordering rule. The application then combines the candidates and selects the newest 100 overall.
The ordering needs a tie-breaker, such as creation time followed by order ID, so results are deterministic when several orders share a timestamp.
Pagination requires more care.
A cursor may need to preserve the global ordering boundary and the per-shard progress. Separate shard queries also do not share one transaction snapshot, so concurrent writes can change which records appear between pages.
For an exploratory support view, the application may accept an eventually consistent result under documented pagination behavior.
A financial reconciliation total has stricter requirements. It cannot claim completeness if one shard is unavailable or the queries do not represent an appropriate consistent cut of the data.
Bounding Fan-Out
Scatter-gather introduces additional concurrency.
One support-page request may start eight shard queries. If many operators open the page at the same time, the combined demand can become significant.
Baodium used a shared bounded executor, per-shard admission controls, and an overall request deadline.
Those are the same protections we introduced for service calls in Chapter 4.
Abandoning a future after a timeout does not necessarily stop a running database query.
The application therefore used database-side statement timeouts or explicit cancellation, alongside local resource accounting.
The result also identified missing shards whenever a partial response was permitted.
The support page ran only a few times a minute, so bounded fan-out was acceptable.
Another workflow made that approach far too expensive.
Tracking Numbers and a Global Directory
Carrier updates arrived with a tracking number, but they did not always include the merchant ID.
Without another lookup mechanism, the handler would have to ask every shard whether it owned the tracking number.
At a peak of 300 tracking updates per second across eight shards, that approach would generate
shard lookup queries per second.
Most would return no matching record.
The team introduced a tracking-number directory that mapped each tracking number to its merchant and owning order.
The directory also enforced the required global uniqueness of tracking numbers.
That uniqueness rule needed to be applied before a shipment was finalized.
If two merchant shards independently committed the same tracking number and only later attempted directory insertion, one insert would fail after the conflicting shipment had already been accepted.
The revised workflow reserved the tracking number in the directory under a unique constraint, then completed the merchant shipment operation through a durable workflow.
An interrupted workflow could leave a reserved directory entry without a completed shipment. Reconciliation would either finish the shipment or release the reservation according to the business policy.
A tracking update arriving before directory activation also needed a pending or retryable outcome rather than immediate fan-out.
Baodium shipped about 40 orders per second at the measured peak.
The directory therefore received roughly 40 reservation writes and 300 tracking lookups per second, or about 340 directory operations.
Each accepted tracking update still required its normal owning-shard write. That work would occur under either design.
The directory replaced 2,400 fan-out lookups with a much smaller number of indexed operations.
It added another dependency and a recovery process, but the traffic reduction and global uniqueness requirement justified that cost.
Moving a Merchant Between Shards
Baodium now had a dedicated shard for its largest merchant, but the merchant’s records were still on the original database.
The team needed to transfer those records while the merchant continued receiving orders and updating fulfillment.
Copying the existing data was only part of the job.
New writes would continue arriving while the copy ran. The destination needed those changes before taking ownership.
There also had to be a point after which the old database could no longer accept writes for that merchant.
Otherwise, a router using an outdated directory entry could write to the original shard after the destination had started serving the merchant.
A Controlled Ownership Transfer
The engineers divided the migration into five stages.
Copy the existing records.
The source remained the writer while the destination received an initial snapshot of the merchant’s records. The team recorded the source change position associated with that snapshot.
Catch up with new writes.
Changes committed after the snapshot were captured and applied to the destination. The applier continued until the remaining difference was small enough for a brief write interruption.
Fence the source.
The source marked the merchant as transferring and rejected new writes under its ownership guard. Transactions that had already been admitted were allowed to finish or were resolved under the migration policy.
Apply and verify the final changes.
The team recorded the final source change position, applied all changes through that point, and compared the records required by the transfer. Counts and checksums were useful evidence, alongside checks of critical balances and relationships.
Transfer write authority.
The destination received the new ownership epoch. The directory was updated to route the merchant to the destination, and only the new owner was permitted to accept writes.
The merchant had approximately 140 million rows to transfer.
At the tested copy rate, the initial snapshot took about 93 minutes.
The change applier processed updates faster than the merchant generated them, reducing the remaining difference over approximately eleven minutes.
Only the final fencing, catch-up, and ownership change required the short period in which new merchant writes could not proceed.
The exact pause had to be measured and compared with the merchant’s availability requirement.
Enforcing the Ownership Epoch
Updating a shared routing directory does not immediately change what every application instance believes.
Some routers will still have cached routes to the old database. Others may already have open connections to it.
The source database must therefore enforce its loss of authority.
Baodium maintained a merchant ownership guard on the shard that received the write.
Every write transaction checked that guard before modifying the merchant’s records.
def write_merchant_order(db, route, change):
with db.transaction():
guard = db.lock_merchant_guard(
change.merchant_id
)
if guard.state != "ACTIVE":
raise StaleRoute(change.merchant_id)
if guard.epoch != route.epoch:
raise StaleRoute(change.merchant_id)
db.apply(change)The repository methods are illustrative.
The guard is locked in the same transaction as the merchant write, so the transfer procedure can wait for admitted writes to finish before revoking authority.
When the merchant moves, the source retains a fenced guard or tombstone. An old bucket route therefore cannot bypass the merchant-level transfer merely because the original bucket still belongs to the source database.
The destination has its own guard under the new epoch.
A router that receives StaleRoute refreshes the ownership directory and retries using the original business-operation identity.
The idempotency rules from Chapter 3 are important here. A retry after a routing change must not apply the same order transition twice.
Failure During Migration
The migration tests interrupted each stage deliberately.
A failure during the initial copy could be recovered by restarting or resuming the copy under its recorded snapshot and change position.
A failure during catch-up required the applier to resume from a durable checkpoint without losing or duplicating business effects.
Once the source had been fenced, the application needed a clear procedure for either completing the transfer or safely restoring the original ownership before any new writes.
After the destination accepted writes, simply pointing routes back to the source would be unsafe.
The source would lack changes committed on the destination. Returning ownership would require another controlled transfer or a recovery process that accounted for those writes.
For every interrupted stage, the team checked that only one database had write authority and that the business-operation records could still be recovered.
Matching row counts alone would not establish either property.
Testing Replicas, Partitions, and Shards
The engineers had introduced several new storage mechanisms, and each required a different kind of failure test.
For replicas, the most useful test recreated the customer’s original address complaint.
The team paused replay on a standby after committing an address change and then requested the account page.
The response had to include the committed address through the read-your-writes path, even while the replica was behind.
Other tests used expired monitoring samples, unavailable replicas, and bounded primary fallback.
The team also tested long-running standby queries. PostgreSQL settings such as max_standby_streaming_delay and hot_standby_feedback affect the interaction between standby queries, replay conflicts, and cleanup on the primary.
Those settings needed evaluation under realistic query duration and replication activity.
For partitioning, the engineers checked query plans to verify pruning and tested inserts at new month boundaries.
They tested order-ID uniqueness separately from query performance because the composite partitioned primary key did not enforce uniqueness of order_id alone.
For sharding, the load test used the actual distribution of merchant sizes.
An evenly distributed synthetic workload would have made every shard look healthy and hidden the large merchant that dominated one database.
The tests also covered unavailable shards, incomplete cross-shard queries, outdated routing entries, and interrupted ownership transfers.
The production dashboard followed the same distinctions.
Replica measurements included WAL progress, observation age, read-routing class, and primary fallback.
Partitioning measurements included storage, query plans, maintenance duration, and missing future partitions.
Shard measurements included the write rate and transaction cost of each database, with particular attention to large merchants and admission rejections.
These measurements gave the on-call engineer enough evidence to identify whether a problem came from replica freshness, insufficient source capacity, or incorrect data ownership.
Regional Metadata Write Authority
The same decisions apply to a document service used by customers in North America and Europe.
Users fetch a document by ID, list documents belonging to a tenant, rename files, and share documents with colleagues.
The file bytes can live in object storage. Metadata such as titles, owners, and permissions needs authenticated updates and suitable indexes.
Fetching a document by ID benefits from a direct key lookup.
Listing a tenant’s documents needs an index beginning with the tenant identifier and supporting the API’s ordering and pagination.
Sharing a document may update access records and an audit trail in one local transaction.
An object uploaded successfully to storage does not prove its metadata record committed. The service needs a durable completion procedure and cleanup for orphaned uploads, similar to the workflow in Chapter 2.
A first regional design might use one transactional metadata authority, read replicas for eligible regional reads, and object storage for the document contents.
The document owner who has just renamed a file needs read-your-writes. A public listing may tolerate some replication delay.
Now suppose the company wants both regions to accept writes independently.
With asynchronous replication, a write acknowledged in one region may not reach the other before a failure.
If both regions change the same permission record, the system needs conflict handling that preserves its security rules.
A revoked permission must not reappear because an older replica became the writer.
One practical initial design assigns each tenant a single write-owning region.
When that region is unavailable, the application can refuse writes until ownership is confirmed or transferred under the approved recovery procedure.
An ownership epoch protects the transfer from an old region resuming writes.
Read placement, data residency, and recovery requirements still need to be evaluated for the actual customers and jurisdictions.
Chapter 14 uses the same ownership principle when Baodium prepares for regional checkout failure.
Design Exercise: Team Messaging Storage
Consider a team messaging application with 50,000 workspaces.
Users read their channels much more often than they send messages. A few large workspaces account for a substantial share of the writes.
The product also has an important user expectation. After posting a message, the sender must see it on the next refresh.
Where should the messages live, which reads should use replicas, and when would sharding be worth introducing?
Starting With the Main Query
The most frequent read retrieves recent messages for a channel within a workspace.
A relational database can support that access pattern with an index beginning with the workspace and channel, followed by a message ordering key.
For example, the application could index
and use cursor-based pagination to read a bounded number of messages.
The initial design does not need one physical partition per workspace.
Fifty thousand individual PostgreSQL partitions would create substantial schema and maintenance overhead.
Time-based partitions might become useful for retention, depending on how messages are archived and queried.
A fixed number of hash partitions could also distribute workspace data within one database, if measurements showed that physical layout was becoming a constraint.
The first design should be tested against the actual query and retention workload before either mechanism is added.
Preserving the Sender’s Recent Message
Channel history can often be read from a replica.
However, the sender who has just posted a message needs to see the committed message on the next request.
The application can return the committed message from the write operation and later route the sender’s reads to the primary or an eligible replica that has replayed the write.
The same read-your-writes principle applies to edited or deleted messages when the product promises immediate visibility to the acting user.
The application also needs stable message identities, so retrying a send after a timeout does not create two copies of the message.
That part of the design comes from Chapter 3.
Choosing the Shard Boundary
Suppose the write rate eventually exceeds one primary’s tested capacity.
Sharding by workspace keeps most channel operations local. It also allows workspace-level access-control checks and many administrative queries to use one database.
The risk is uneven demand.
A very large workspace may generate more messages than thousands of smaller ones combined.
Sharding by channel spreads a large workspace across databases, but listing a user’s unread channels or calculating workspace-wide state becomes more complicated.
Baodium’s merchant-order decision offers a useful starting point.
The team could shard by workspace, measure the largest tenants, and move an unusually busy workspace to a dedicated shard.
If that single workspace outgrew one database, splitting it by channel would become a specific design change with known cross-shard consequences.
The failure tests would include a lagging replica, an unavailable shard, and a workspace transfer interrupted while messages were being sent.
For each case, the application needs to establish where new messages may be written and what a reader can retrieve after the write is acknowledged.
Summary
Baodium introduced read replicas to reduce the demand on its PostgreSQL primary. The replicas served many browsing queries successfully, but the address-change incident showed why read routing needed a clearer contract.
The engineers began classifying reads according to the state each operation required. Product metadata could use an eligible replica under its freshness policy. An account page immediately after a save needed read-your-writes. Inventory reservations continued through their authoritative transaction path.
Other database problems required different changes.
Monthly partitioning made old-order retention more efficient, but it also affected uniqueness and lookup paths. Sharding distributed merchant-order writes, while requiring the application to identify each record’s owner and coordinate operations that crossed merchants.
The most difficult part of sharding appeared when ownership changed. A destination could accept new writes only after the source had been fenced and the relevant data had been transferred and verified.
We now have several places where the same customer action can be observed: the application, the primary database, its replicas, a message or tracking directory, and sometimes another shard.
During an incident, engineers need evidence that connects those observations to the request the customer actually made.
Chapter 8 examines how instrumentation, traces, metrics, and logs provide that evidence across a distributed request path.
PostgreSQL describes asynchronous and synchronous standby behavior in Hot Standby and Log-Shipping Standby Servers.↩︎
See PostgreSQL’s Continuous Archiving and Point-in-Time Recovery documentation.↩︎
After this chapter
⌘/Ctrl K to search
The rest of the book
You have been reading Practical System Design. Chapters 1 through 7 are here in full. If you are enjoying the book, the rest of it is the full edition.
The full edition continues from the next chapter through the last chapter, the epilogue, and the appendices. Buy it on Amazon.