tezvyn:

The N+1 query problem and how to fix it

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

recognizing ORM lazy-loading waste.

OUTLINE

one query for a list plus one per item for its relation, fix with eager loading or a batched join.

RED FLAG

blaming the database, or fixing it by caching instead of reducing round trips.

WHAT THIS TESTS The question probes whether you understand ORM lazy loading and can diagnose a latency problem caused by query count rather than query complexity.

A GOOD ANSWER COVERS The shape of the problem. You run one query to load a collection, say all blog posts, which returns N rows. Then in a loop you access each post's author, which the ORM lazily resolves with a separate query per post. The result is one initial query plus N follow-up queries, hence N+1. The dominant cost is network round trips and per-query overhead, which crushes latency as N grows even though each query is trivial.

HOW TO FIX IT Eager loading. Instruct the ORM to load the relation alongside the parents, either with a single SQL join that returns posts and authors together, or with a second batched query using WHERE author_id IN the collected ids. This collapses N+1 into one or two queries. Most ORMs expose this as join fetch, includes, selectinload, or prefetch_related.

COMMON WRONG ANSWERS Throwing a cache in front of the lazy loads, which only hides repeated round trips, or blaming the database engine when the access pattern is the cause.

LIKELY FOLLOW-UPS How do you detect it (query logs, APM, or assertion tools), when does a join fetch cause a Cartesian explosion, and when is a batched IN query preferable to a join.

ONE CONCRETE EXAMPLE Rendering 100 posts with their authors lazily issues 1 + 100 queries. Switching to selectinload or join fetch issues 1 query for posts and at most 1 batched query for authors, cutting 101 round trips to 2.

Read the original → dev.to

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.