Video in progress

What safeguards do you put in the team so the N+1 problem doesn't keep coming back to prod?

In integration tests I assert the number of SQL queries for every important endpoint, in dev the Hibernate statistics and slow query log are on, and open-in-view is off. That way, even if an N+1 slips through code review, the test fails.

📖 Answer

Fixing an N+1 once is easy. The hard part is making sure it does not come back next month when another developer adds dto.getCustomer().getName().

The layers of protection I use:

Counting queries in tests. Through datasource-proxy or Hibernate Statistics:

@Test
void orderListDoesNotTriggerNPlusOne() {
    Statistics stats = sessionFactory.getStatistics();
    stats.clear();

    orderService.listForUser(userId); // returns 50 orders

    assertThat(stats.getPrepareStatementCount()).isLessThanOrEqualTo(3);
}

This test runs against a real PostgreSQL in Testcontainers and checks that the number of queries does not depend on the data size.

spring.jpa.open-in-view=false. That way lazy loading does not quietly happen inside the controller or during serialization, and LazyInitializationException points at the problem right away.

A global hibernate.default_batch_fetch_size=50 is a safety net. Even if an N+1 is left somewhere, it drops to 1 + N/50.

On prod I watch a "queries per request" metric in the APM (or Micrometer + datasource-proxy). The list of endpoints above 100 is reviewed every sprint.