What are N+1, eager loading and lazy loading?
Try code in the playgroundUnderstand the concept
N+1 is a data-access pattern where fetching N parent records leads to roughly N more queries for related records. Eager loading fetches configured relations up front, while lazy loading waits until the relation is accessed. Both loading styles can waste work if they do not match the endpoint's real needs.
Important ideas
-
N+1 means one list query followed by a query for each row.
-
Eager loading fetches configured relations automatically; lazy loading fetches on access.
-
Use measured joins or batch queries, and select only needed fields.
-
A giant join can multiply rows; batching can sometimes be clearer and cheaper than loading every relation at once.
Can you explain it without the notes?
What are N+1, eager loading and lazy loading?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
N+1 is a data-access pattern where fetching N parent records leads to roughly N more queries for related records. Eager loading fetches configured relations up front, while lazy loading waits until the relation is accessed. Both loading styles can waste work if they do not match the endpoint's real needs.
Turn this concept into a clear answer.
- Count queries and returned rows, not just the number of lines in the repository call.
Keep connecting the ideas.
Next lesson: Why use migrations instead of automatic schema sync?Adapted from 03_NESTJS.md · “What are N+1, eager loading and lazy loading?”. Examples are study fragments; framework behavior can depend on your version.