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:
- Clean up indexes. Every index makes every
INSERTmore expensive, and an index on a column that gets updated kills HOT updates. Indexes withidx_scan = 0inpg_stat_user_indexesare the first candidates. - Batching. Between 1000 separate
INSERTs and one multi-rowINSERTorCOPY, the difference can be tenfold. With JDBC it'sreWriteBatchedInserts=true, with Hibernate it'shibernate.jdbc.batch_size. One catch: theIDENTITYgenerator disables insert batching in Hibernate, so you needSEQUENCE. - Aggregate frequent updates.
UPDATE posts SET views = views + 1a thousand times a second: count in Redis and issue oneUPDATEevery 10 seconds. - Move data where it belongs. Logs and events go to Kafka/ClickHouse, sessions to Redis. Postgres stays for transactional data.
- WAL and checkpoints.
max_wal_size,checkpoint_timeout; for data you can rebuild,synchronous_commit = offat the transaction level (on a crash you may lose the last few hundred milliseconds). - Partitioning. In a table partitioned by time, the indexes are small and old partitions go away with
DROP, with noDELETEand vacuum load. - Split by domain. Moving payments and the catalog into separate databases also splits the write load, but it's much simpler than shards.
- 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.
Sign up to mark studied questions and save your progress.