Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

N+1 problems keep reaching production in your team's services. How do you detect them automatically before release?

I would make tests count SQL statements, with datasource-proxy or a Hibernate StatementInspector or Hibernate statistics, and assert the expected count for each important use case, and review SQL logs in integration tests for repeated statements. In production, I would record query counts per request in tracing spans and alert on outliers. A global hibernate.default_batch_fetch_size is a safety net that limits the damage, but hot paths still get explicit fixes.

Why this question is asked

N+1 problems reach production because nothing in the normal development loop shows them. The code compiles, unit tests with mocks pass, integration tests with three rows pass, and the reviewer sees a clean loop. Only with real data volumes does the page with 100 rows run 300 queries. Interviewers ask this scenario because the answer separates people who fix N+1 one incident at a time from people who build a system that catches it. In this answer, we will see why N+1 slips through, build statement-count assertions into tests, use logs and statistics as a second line, add production detection, and decide where a batch fetch size fits.

1Why N+1 Slips Through

An N+1 is one query for a list plus one query per element for an association, usually hidden behind a getter. Three habits let it through. Unit tests mock the repository, so no SQL runs. Integration tests insert one or two rows, so 1 + 2 queries looks normal. And code review looks at Java, where order.getCustomer().getName() in a loop looks harmless.

So detection has to look at the SQL itself, with enough rows to make N visible, and compare the count against an expectation. Everything below is a way of doing that at a different stage.

2Counting Statements in Tests

The strongest guard is a test that runs a use case against a real database, counts the statements and asserts the number. datasource-proxy wraps the DataSource and sees every statement at the JDBC level, whatever produced it. Hibernate's own statistics, enabled with hibernate.generate_statistics, also count prepared statements. A StatementInspector, a Hibernate hook that sees every SQL string before it runs, configured through hibernate.session_factory.statement_inspector, can count or record them too.

Java
@SpringBootTest(properties = "spring.jpa.properties.hibernate.generate_statistics=true")
@Testcontainers
class OrderListQueryCountTest {
@Autowired EntityManagerFactory emf;
@Autowired OrderQueryService service;
@Test
void listOpenOrders_runsTwoStatements() {
fixtures.createOrders(20, 20); // 20 orders, 20 different customers
Statistics stats = emf.unwrap(SessionFactory.class).getStatistics();
stats.clear();
service.listOpenOrders(PageRequest.of(0, 20));
assertThat(stats.getPrepareStatementCount()).isEqualTo(2); // orders + count query
// with the N+1 back, this reports 22
}
}
Step throughA statement-count test
  1. Insert fixture dataenough distinct rows to make N visible
  2. Reset the counterstatistics.clear() or proxy reset
  3. Run the use caseservice method, not the repository
  4. Count equals expectation?
    YesPassNoFail with the SQL listed

4 steps in order. Play them, or step through them one at a time.

Notice the data: 20 orders with 20 different customers. With one customer, the N+1 would load it once and the count would barely move. The fixture must make N large enough to matter, so the difference between 2 and 22 is obvious. These tests run on a real database, typically PostgreSQL in Testcontainers, because counts on an in-memory database can differ from production SQL.

3Logs and Statistics as a Second Line

Not every use case will have a count test. For the rest, integration tests can log SQL and a small helper can flag repetition: the same statement shape, with only the parameters differing, appearing more than, say, five times within one test. That pattern is the signature of an N+1. Hibernate's statistics also log a summary per session when enabled with debug logging, showing how many statements and entity loads a unit of work caused.

Developers should see this while working, not only in CI. Turning on SQL logging, with bound parameters, in the local profile makes repeated statements visible the first time someone runs the feature. It costs nothing and catches many problems before a test is even written.

4Detecting It in Production

Some N+1s only appear with production data shapes, so we also measure in production. With tracing in place, for example Micrometer Tracing with JDBC observations through a library such as datasource-micrometer, each request span carries child spans or a count for its SQL statements. A dashboard of statements per request by endpoint shows outliers quickly: an endpoint that normally runs 4 statements and sometimes runs 400 is an N+1 that depends on data.

An alert on the 99th percentile of statements per request for each endpoint, or on a threshold such as more than 50, turns this into a signal the team sees the same day. Database-side views such as pg_stat_statements help too: a small query with millions of calls per hour and a tiny average time is often the inner query of an N+1.

Step throughLayers of N+1 detection
  1. Developer machineSQL logging in the local profile
  2. Integration testsstatement-count assertions on key use cases
  3. CIrepeated-statement detector on SQL logs
  4. Productionstatements per request in traces, alerts on outliers
  5. Databasepg_stat_statements: high call counts for tiny queries

5 layers, from the top down. Step through them one at a time.

5Where a Global Batch Size Fits

Setting hibernate.default_batch_fetch_size, to about 16 to 50, makes every lazy association load in batches with IN lists. An N+1 of 100 becomes 1 + 2 to 7 queries. That is an excellent safety net, because it limits the damage of the problems we have not found yet.

But it should not become the fix. With batching, a page still runs more queries than a fetch join would, and the count depends on what is in the session. So I treat the batch size as the floor and still fix hot paths explicitly with fetch joins, entity graphs or projections, guarded by count tests. The tests should be written with the batch size active, so their expectations match production.

6Follow-up questions

Is an exact count assertion too brittle?

It can be if the expected number is arbitrary. I assert the number that the design intends, like 2 for a page and its count, and when it changes, the developer either fixes the regression or updates the number with a reason in the diff. That conversation is the point of the test.

Which use cases deserve a count test?

The ones with the most traffic and the ones that render lists: list pages, search results, exports and batch jobs. Ten to twenty such tests usually cover most of the risk in a service.

Can a static check find N+1 in code review?

Only partly. Tools can flag getters on lazy associations inside loops, but they cannot know whether the data was fetched earlier. Counting statements at runtime is far more reliable, so static checks are a supplement at most.

7Conclusion

In this answer, we saw that N+1 slips through because tests mock the database or use too little data and reviews read Java instead of SQL. We built detection in layers: statement-count tests with datasource-proxy, a StatementInspector or Hibernate statistics, repeated-statement checks on SQL logs, statements per request in production traces with alerts, and a global batch fetch size as a safety net while hot paths are fixed explicitly.

What to say in the interviewAbout 80 seconds aloud

Open with

N+1 slips through because unit tests mock the repository, integration tests use two rows, and reviewers read Java, not SQL. So I would detect it by counting SQL.

Then, if they want more

The main guard is statement-count tests: for each important use case, a test on a real database, usually PostgreSQL in Testcontainers, inserts enough distinct rows to make N visible, say 20 orders with 20 customers, resets a counter, runs the service method and asserts the expected number.

The counter can be datasource-proxy at the JDBC level, a Hibernate StatementInspector, or Hibernate statistics with getPrepareStatementCount. As a second line, integration tests log SQL, and a helper flags the same statement shape repeated many times in one test; locally, developers run with SQL logging on so they see repetition while building the feature.

In production, I would add statement counts per request to tracing spans, chart them by endpoint and alert on outliers, and check pg_stat_statements for tiny queries with huge call counts. I would also set hibernate.default_batch_fetch_size, around 16 to 50, as a safety net that turns any remaining N+1 into a few IN queries.

But that is a floor, not the fix: hot paths still get fetch joins, entity graphs or projections, guarded by the count tests.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "N+1 problems keep reaching production in your team's services. How do you detect them...": https://scrivio-interview-library.netlify.app/databases/jpa-performance/05391f50fa/