Video in progress

The write volume is approaching what a single PostgreSQL primary can handle. What options do you consider before sharding?

First I make the writes themselves cheaper: drop unneeded indexes, batch and COPY, HOT updates, smaller rows. Then I split off the load: logs and events to another system, non-synchronous writes through a queue, functional splitting. Sharding comes after these.

📖 Answer

When someone says "there are a lot of writes", you need to know exactly what is running out: CPU, disk IOPS, WAL throughput, or lock contention? The solution is different for each.

Reducing the cost of a write:

  • Indexes. Each extra index adds a write to every INSERT. Unused indexes (idx_scan = 0) are the first candidates. In one project we dropped 6 of 14 indexes and roughly doubled insert throughput.
  • Batching. 500 rows in a single transaction instead of 500 commits (and 500 WAL flushes). In PgJDBC, reWriteBatchedInserts=true.
  • synchronous_commit = off for unimportant writes: no waiting for the flush.
  • HOT updates and fillfactor: the indexes don't change.
  • Row size. Rewriting a big jsonb or text on every update is expensive; split the frequently changing part into a separate table.

Moving the load elsewhere:

  • Telemetry, audit, clickstream: these are often a large share of the writes. Routing them through Kafka → ClickHouse/object storage frees up the OLTP database.
  • Smoothing writes that aren't needed right away through a queue (spreading out the peak load).
  • Functional separation: separate bounded contexts in separate databases.

Infrastructure: faster disks (NVMe, provisioned IOPS), the WAL on a separate disk, a bigger instance. These are "boring" solutions, but they often last a year or two and are much cheaper than sharding.

After each change I measure the result with pg_stat_wal and pg_stat_statements, not by feel.