Video in progress
Service traffic is expected to grow 10x in a year. What breaks first in the Hibernate and database layer, and how do you plan capacity?
Usually the connection pool and the CPU/IO of the single writer database fill up first, then N+1 and unindexed queries, large tables and lock contention show up. I start planning from current measurements: query count and database time per endpoint, then I use load tests to find which resource saturates first.
📖 Answer
10x load does not grow evenly: one endpoint or one table causes all the trouble. So first I collect the number for "how much does one request cost the database right now":
- the SQL count and total database time per endpoint (via tracing or datasource-proxy);
- the top queries in
pg_stat_statementsand their total time; - Hikari:
active,pending, connection hold time.
A simple calculation: an endpoint with 8 queries and 15 ms of database time, at 500 RPS at peak, means 4000 queries/s on the database and about 7-8 busy connections on average. At 10x, that is 40 thousand queries/s and 75+ connections. Just raising the pool to 200 is not a solution: PostgreSQL gets worse with many connections.
Things usually break in this order:
- N+1 and redundant queries: at 10x load they hurt more than 10x. The cheapest and biggest win is here: fetch plan, DTO projection, batch fetch.
- Connections: long transactions, external calls inside transactions. I shorten them and, if needed, put PgBouncer (transaction mode) in front.
- The writer database: I move reads to a replica, heavy reports to a separate read model, and use caching (L2 or application) for reference data that is read a lot.
- Large tables: partitioning, archiving, revisiting indexes.
- Hot rows: an atomic UPDATE for counters and stock, splitting rows, or a queue.
The load test (k6, Gatling) has to run with prod-sized data: on an empty database everything is fast. In the test, at 2x, 5x and 10x steps, I note which metric goes out of bounds first.
The cost of the fixes differs: fixing queries takes weeks, a replica takes months, sharding takes a quarter or more and brings a lot of complexity. So I start with the cheap ones and remeasure after each step. Often a large part of the 10x is covered by the first two steps alone.
Sign up to mark studied questions and save your progress.