Database scaling, replication, and sharding
Compare adding capacity to one server, copying data to replicas, and distributing different parts of a dataset across servers.
On this page
Identify what is reaching its limit
Look at query time, CPU, memory and disk usage, and read and write traffic. Adding CPU, memory, or storage to one server is vertical scaling. Using additional servers to share work is horizontal scaling.
-- Find the queries that use the most shared block reads.
-- Requires pg_stat_statements to be enabled.
SELECT calls, total_exec_time, shared_blks_read, query
FROM pg_stat_statements
ORDER BY shared_blks_read DESC
LIMIT 5;
Replication- Copy changes from a primary to other servers. Read replicas can serve read traffic and a suitable standby can support failover. With asynchronous replication, recent writes can take time to appear on a replica.
Table partitioning- Split a logical table into smaller parts, such as one partition per month, so the engine can skip irrelevant partitions for suitable queries. These partitions can live on one server.
Sharding- Distribute different parts of the same dataset across servers. A shard key helps route reads and writes to the right shard. A query spanning several shards may need extra work to gather and combine results.
Apply the choices to inventory
Apply the two mechanisms to different requests. A replica can serve another copy of the data, and a shard can hold just the records for one part of the inventory. If a read-heavy report can tolerate a short delay, examine whether a read replica helps. For a dataset distributed by warehouse ID, a query for one warehouse can target fewer shards, while a cross-warehouse report may have to read many. Check how traffic is distributed so that one busy warehouse does not dominate a shard.
-- The backend can route this report to a read replica if
-- it can tolerate replication lag.
SELECT SUM(quantity) AS total_units
FROM stock_balances
WHERE warehouse_id = 3;
-- In a sharded design, warehouse_id = 3 also tells the
-- shard router which part of the inventory to query.