Video in progress
The application sends the database a huge number of small queries and most of the response time goes to the network. How do you reduce that at the architecture level?
First I measure: how many times a single API request goes to the database. Then I remove N+1, combine queries (JOIN, = ANY, batch), cut the round trips in a single transaction, and if needed bring the application and database closer into one zone and cache reads.
📖 Answer
In one project GET /dashboard took 400 ms, while the database queries totaled only 30 ms. The rest was 180 queries × 2 ms of network. The application was in one zone and the database in another.
First you have to make it visible:
- a metric of the number of SQL queries per HTTP request (Hibernate statistics, datasource-proxy or tracing spans);
- a limit in tests: "this endpoint must not send more than 10 queries". An assertion like that catches regressions.
Then layer by layer:
- N+1.
JOIN FETCH,@EntityGraph,@BatchSize, DTO projection. The biggest win is often here. - Queries over lists. Instead of
findByIdin a loop, oneWHERE id = ANY(?). - Writes. JDBC batch,
reWriteBatchedInserts, Hibernatebatch_size+order_inserts. - Transaction boundaries. If every repository call is its own transaction,
BEGIN/COMMITthemselves are round trips. One transaction per service method. - Placement. Application and database in one AZ (taking failover into account). Between zones it's 1-2 ms, within one zone 0.2-0.5 ms.
- Cache. Rarely changing reference data (categories, settings): I cache it inside the application itself.
"Speeding up" the database with a faster server or a replica barely helps here: the time isn't in the queries, it's in the round trips. That's why I first remove the extra queries in the application code, which is always the cheaper and more reliable win.
Sign up to mark studied questions and save your progress.