8. DatabasesPooling and N+1
Pooling and N+1
These are two of the most common causes of a slow database-backed app. The N+1 problem is when code fetches a list of items with one query, then runs one more query per item to get related data: 100 blog posts and their authors becomes 101 round trips instead of one or two. It often hides inside ORMs, libraries that map database rows to objects, and the fix is to batch, with a join, a single “WHERE id IN (…)” query or the ORM’s eager loading. Connection pooling tackles a related cost: opening a database connection is slow, so a pool keeps a set of open connections and lends them out to requests, taking them back when each is done.
In this lesson: A query counter demo.