Video in progress

Write load has reached the capacity of a single Postgres primary. What do you try before sharding?

Sharding is a last resort, and it complicates all the code and operations. First I make the writes themselves cheaper: drop unneeded indexes, batch, aggregate frequently updated counters, move log-like data to other storage, then partitioning and separate databases per domain; after that, a bigger machine.

📖 Answer

The first question is which writes are producing the load. If you sort INSERT/UPDATE statements in pg_stat_statements by total_exec_time, often 2-3 queries account for half the load. And they often aren't even business data: audit log, "last seen" time, sessions, counters.

This is the ladder I usually climb before sharding, in this order:

  1. Clean up indexes. Every index makes every INSERT more expensive, and an index on a column that gets updated kills HOT updates. Indexes with idx_scan = 0 in pg_stat_user_indexes are the first candidates.
  2. Batching. Between 1000 separate INSERTs and one multi-row INSERT or COPY, the difference can be tenfold. With JDBC it's reWriteBatchedInserts=true, with Hibernate it's hibernate.jdbc.batch_size. One catch: the IDENTITY generator disables insert batching in Hibernate, so you need SEQUENCE.
  3. Aggregate frequent updates. UPDATE posts SET views = views + 1 a thousand times a second: count in Redis and issue one UPDATE every 10 seconds.
  4. Move data where it belongs. Logs and events go to Kafka/ClickHouse, sessions to Redis. Postgres stays for transactional data.
  5. WAL and checkpoints. max_wal_size, checkpoint_timeout; for data you can rebuild, synchronous_commit = off at the transaction level (on a crash you may lose the last few hundred milliseconds).
  6. Partitioning. In a table partitioned by time, the indexes are small and old partitions go away with DROP, with no DELETE and vacuum load.
  7. Split by domain. Moving payments and the catalog into separate databases also splits the write load, but it's much simpler than shards.
  8. A bigger machine and a fast disk. A modern server with NVMe handles more writes than most people think.

If that's still not enough, then sharding or distributed Postgres like Citus. But I come to that decision with numbers: current write TPS, growth rate, and how much each step bought us.