Indexes and query performance · Scenario
1,200 queries for one page
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
The orders page in our admin app takes 6 seconds. The database dashboard shows no single slow query, but one page load makes about 1,200 queries. What's going on, and how do you fix it?
Then
Follow-ups the interviewer asks next
- How do you confirm it's an N+1 problem?
- Why are 1,200 fast queries slower than one slow query?
- Fix it in the ORM you know best.
- You add a fetch join with pagination, and memory on the app server jumps. Why?
- The page must now show orders with items and payments for 500 orders. How do you keep it fast?
- How do you stop N+1 from coming back?
- Have you fixed an N+1 problem? Which ORM?
The answer
What a strong answer covers
- Confirms with SQL logging or an APM trace: one query for the list, then one per order for the customer and one per order for the items.
- Each query is quick, but 1,200 round trips, plus waiting for a pooled connection, add up to seconds and starve other requests.
- Fixes: eager loading (
JOIN FETCHor@EntityGraphin JPA,includein Prisma or Sequelize,select_related/prefetch_relatedin Django), batch loading withWHERE id IN (…)(Hibernate batch size, DataLoader for GraphQL), or one hand-written query. - Twist: a collection fetch join plus pagination makes Hibernate log "firstResult/maxResults specified with collection fetch; applying in memory": it loads every row and pages in memory. Page the order ids first, then fetch their items.
- Also fixes the page fetching 600 orders when it shows 50.
- Prevents it: a query-count assertion in tests (Hibernate statistics, Django
assertNumQueries), an APM alert on queries per request, code review.
The red pen
Common traps
Avoid:"add a cache in front"; raising the connection pool size; eager-loading everything everywhere.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.