hardScenarioConceptMidSeniorStaff
A list endpoint that returns fifty orders issues more than a hundred queries, and rewriting it as an async endpoint made it slower. Explain both.
5 min readUpdated 2026-08-15
Answer
Short answer
An N+1 happens when the ORM follows a relation lazily once per row; select_related fixes forward foreign keys with a SQL join, prefetch_related issues one extra query per relation and joins in Python.
Was this answer helpful?
Likely follow-ups
- When would prefetch_related be slower than the N+1 it replaces?
- How would you prefetch only the unshipped items of each order into a separate attribute?
- What happens if you call the Django ORM synchronously from inside an async view?
- How would you detect a blocking call inside an event loop in a running service?
Related questions
- A Spring Data repository method looks like one clean line, but the endpoint issues several hundred queries per request. How do you diagnose the N+1, and what would you actually change?hardAlso on n-plus-one4 min
- This endpoint logs one query per row. Why are you seeing N+1 queries, and how do you fix them?mediumAlso on n-plus-one6 min
- A worker picks up the job you queued and cannot find the row it was told about. What went wrong?hardAlso on django-orm5 min
- This EF Core query is slow. How do you work out why, and what does change tracking have to do with it?mediumAlso on n-plus-one5 min