Subscribe

Sharding and partitioning: what to do when one database is not enough

Before you shard, partition. I split a 1.8 million row Postgres 18 table by month, hit the default partition trap, dropped a month with 18 kB of WAL instead of 28 MB, then built a logical shard map in Go that moves 25% of customers instead of 75%.

Sharding and partitioning: what to do when one database is not enough

"We need to shard" is said far more often than it is needed. Splitting data across several databases is a big, mostly one-way change, and there are cheaper steps before it. In this blog we will go through those steps in order, spend most of the time on the one that helps the most for the least work (Postgres declarative partitioning), and then look at real sharding with a small shard router in Go.

This is an advanced post. You should know SQL, indexes and a bit of Go. I used Postgres 18.7 (postgres:18-alpine in Docker) and Go 1.27.3. All the SQL and Go is in a code folder and I ran every piece of it.

Same format as the rest of this series: requirements, estimates, diagram, deep dive, trade-offs.

Requirements

Take an app with an events table (clicks, views, orders) and an orders table.

  • Events come in all day and are kept for 90 days, then deleted.
  • Most queries ask for one customer's recent events, or one time range.
  • Orders are kept forever and always read per customer.
  • The database must keep up as traffic grows for the next few years.

Estimates

Say 200 events a second on average. That's about 17 million rows a day and 1.5 billion over 90 days. At around 150 bytes a row plus indexes, call it 300 GB. (How to do this kind of sum is in system design basics.)

Postgres on one decent machine handles 300 GB fine. See, the size is not really the problem. Two other things are. Deleting 17 million rows every day with DELETE is heavy, and vacuum on a huge table takes hours. And indexes that no longer fit in memory make every insert slower. Both of those are solved by partitioning, without a second database.

The ladder

I think of it as a ladder. Climb one step only when the one below runs out.

  5. shard across databases      many primaries, app routes by key
  4. partition tables            one database, many smaller tables
  3. read replicas               reads off the primary
  2. bigger instance + indexes   EXPLAIN, better indexes, more RAM
  1. one Postgres                where almost everyone starts

Steps 2 and 3 have their own posts: Postgres index design, finding slow queries with pg_stat_statements, and consistency and read replicas. Connection limits are another reason people think they need more databases, and PgBouncer usually fixes that one.

Vertical partitioning, by the way, is moving columns or whole tables apart (for example the big payload column into its own table, or the events table into its own database). Horizontal partitioning splits rows. The rest of this post is about rows.

Range partitioning by month

The parent table holds no data. Each month is its own table, and Postgres routes inserts and queries to the right one.

CREATE TABLE events (
    id          bigint GENERATED ALWAYS AS IDENTITY,
    customer_id bigint      NOT NULL,
    kind        text        NOT NULL,
    created_at  timestamptz NOT NULL,
    payload     jsonb       NOT NULL DEFAULT '{}',
    PRIMARY KEY (id, created_at)          -- must include the partition key
) PARTITION BY RANGE (created_at);

CREATE TABLE events_2026_09 PARTITION OF events FOR VALUES FROM ('2026-09-01') TO ('2026-10-01');
CREATE TABLE events_2026_10 PARTITION OF events FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');
CREATE TABLE events_2026_11 PARTITION OF events FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
CREATE TABLE events_default PARTITION OF events DEFAULT;

CREATE INDEX ON events (customer_id, created_at);

That primary key comment is there because Postgres insists. I tried a plain id primary key on partitioned table first:

ERROR:  unique constraint on partitioned table must include all partitioning columns
DETAIL:  PRIMARY KEY constraint on table "bad_events" lacks column "created_at" which is part of the partition key.

Each partition has its own index, and Postgres can't check uniqueness across them. So id alone is no longer guaranteed unique by the database. With an identity column it is unique in practice, but it's worth knowing that a unique email or order number can't be enforced on a partitioned table unless it includes the partition key.

Then I loaded 1.8 million rows spread over three months.

INSERT INTO events (customer_id, kind, created_at)
SELECT (random() * 9999)::int + 1,
       (ARRAY['view','click','order'])[1 + (g % 3)],
       timestamptz '2026-09-01' + (g * interval '1 second' * 4.4)
FROM generate_series(1, 1800000) g;
   partition    | count
----------------+--------
 events_2026_09 | 589090
 events_2026_10 | 608728
 events_2026_11 | 589091
 events_default |  13091

Three months, I thought. Except 1.8 million times 4.4 seconds is about 92 days, so the last 13,091 rows were in December and went to the default partition. My mistake, and a useful one, because the next step failed:

CREATE TABLE events_2026_12 PARTITION OF events FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');
ERROR:  updated partition constraint for default partition "events_default" would be violated by some row

Once rows sit in the default partition, you can't add a partition that would own them. You have to move them out by hand: detach the default, create the month, copy the rows across, delete them from the old default and attach it again. The script is in the code folder. My first version of it copied the rows without the id column, so every moved row got a new id. Easy to miss, OVERRIDING SYSTEM VALUE with id in the column list keeps them.

The lesson I took: create partitions ahead of time. A daily job that makes next month's partition (or the pg_partman extension) means the default partition stays empty, and honestly I would skip the default partition and let an insert with no partition fail loudly.

Partition pruning

A query on a time range only touches the partitions that can match.

EXPLAIN (COSTS OFF)
SELECT count(*) FROM events WHERE created_at >= '2026-10-05' AND created_at < '2026-10-12';
 Finalize Aggregate
   ->  Gather
         Workers Planned: 2
         ->  Partial Aggregate
               ->  Parallel Seq Scan on events_2026_10 events

Only October. The catch is the other direction. A query by customer alone, with no time filter, has to visit every partition:

 Aggregate
   ->  Append
         ->  Bitmap Heap Scan on events_2026_09 events_1
         ->  Bitmap Heap Scan on events_2026_10 events_2
         ->  Bitmap Heap Scan on events_2026_11 events_3
         ->  Bitmap Heap Scan on events_default events_4

Four partitions is fine. Thirty-six monthly partitions is 36 index lookups per query. So the partition key should be something nearly every query filters on. For events that's time, and the app should always send a date range, even a wide one. (The EXPLAIN post covers reading these plans.)

Retention: drop, don't delete

This is where partitioning actually pays for itself. I compared deleting September against dropping its partition, and measured the WAL each one wrote.

SELECT pg_current_wal_lsn() AS before \gset
BEGIN;
DELETE FROM events WHERE created_at < '2026-10-01';
ROLLBACK;
SELECT pg_size_pretty(pg_current_wal_lsn() - :'before') AS wal_for_delete;
DELETE 589090
Time: 117.566 ms
 wal_for_delete
----------------
 28 MB

28 MB of WAL for 589,090 rows. All of that goes to every replica and into every backup. A committed delete also leaves dead rows for vacuum to clean up. At the 17 million rows a day from the estimates, multiply accordingly.

Dropping the partition:

ALTER TABLE events DETACH PARTITION events_2026_09 CONCURRENTLY;
DROP TABLE events_2026_09;
 wal_for_drop
--------------
 18 kB

18 kB. One thing caught me here. My first try at DETACH ... CONCURRENTLY failed with this:

ERROR:  cannot detach partitions concurrently when a default partition exists

One more reason to not have a default partition. Without CONCURRENTLY the detach takes a strong lock on the parent and blocks queries for a moment, which on a busy table is exactly what you don't want.

Hash partitioning and the hot key

Orders are read per customer, so they get split by customer with hash partitioning. This is the same idea as a shard key, only inside one database.

CREATE TABLE orders (
    customer_id bigint NOT NULL,
    order_id    bigint NOT NULL,
    total_paise bigint NOT NULL,
    PRIMARY KEY (customer_id, order_id)
) PARTITION BY HASH (customer_id);

CREATE TABLE orders_p0 PARTITION OF orders FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE orders_p1 PARTITION OF orders FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE orders_p2 PARTITION OF orders FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE orders_p3 PARTITION OF orders FOR VALUES WITH (MODULUS 4, REMAINDER 3);

I loaded 240,000 orders over 10,000 customers, then 160,000 more for a single big customer.

 partition | count  | pct
-----------+--------+------
 orders_p0 |  59736 | 14.9
 orders_p1 | 220648 | 55.2
 orders_p2 |  60720 | 15.2
 orders_p3 |  58896 | 14.7

Hashing spreads keys evenly, it does not spread load evenly. One customer with 40% of the rows makes one partition hold 55% of everything. On a single database that's a mild annoyance. Across separate shard databases it means one machine is twice as busy as the others and you can't fix it by adding machines. If you know you have customers like that, give them their own shard, or pick a key with more spread (customer plus month, for example).

Real sharding: a logical shard map in Go

When one primary can't take the writes any more, the data goes to several databases and the app picks the database for each request. The naive way is hash(customer_id) % number_of_databases. It works until you add a database. I measured what happens going from 3 to 4 databases with a million customers:

hash % N, 3 -> 4 databases:  75.0% of customers move
logical shards + map:        25.0% of customers move (256 of 1024 logical shards)

Three quarters of the data moving between databases is basically a migration project. The usual fix is a fixed number of logical shards (1,024 here), much more than you'll ever have databases. The hash picks the logical shard and that never changes. A small map says which database owns each logical shard.

const LogicalShards = 1024

func Logical(customerID int64) int {
    return int(Hash(customerID) % LogicalShards)
}

type Map struct {
    DBs   []string           // DSNs, index = physical shard
    Owner [LogicalShards]int // logical shard -> index in DBs
}

func (m *Map) DSN(customerID int64) string {
    return m.DBs[m.Owner[Logical(customerID)]]
}

Adding a database means picking 256 logical shards, copying their rows to the new database, then flipping their entries in the map. Only the customers in those shards move, and only to the new database. The test checks exactly that:

shard_test.go:24: customers moved: 25.0%

The full AddDB is in the code folder. In production the map lives in a small table or config file that every app instance loads, and the copy for each logical shard follows the usual pattern: copy, catch up, briefly block writes for that shard, flip, unblock.

Trade-offs

Partitioning keeps one database, so you keep transactions, joins and foreign keys between unpartitioned tables. You lose global unique constraints that don't include the partition key, and every query without the key get slower as partitions add up.

Sharding costs a lot more. Queries across customers ("top 10 products this week") have to ask every shard and merge the results, so reporting usually moves to a separate warehouse. Transactions across two shards are gone, unless you build sagas or use something like the outbox pattern to make the steps reliable. Every migration runs N times. Backups and restores are per shard (pgBackRest on each). If you already went with schema per tenant like in the multi-tenant posts, the tenant is a natural shard key, which makes this a lot easier.

There are also tools that do the routing for you, Citus on Postgres being the well known one. I'd still learn the moving parts with something small like the code above first, so the tool's choices make sense.

My guess is that for most apps, monthly partitions plus a job that drops old ones is as far up the ladder as they ever need to go.