Backend development

Stage 2 · Lesson 11 of 11

The N+1 query problem

Relational databases and SQL

is not an , but a loop is enough to cause the N+1 problem. Load 50 orders, then await find_customer(&pool, order.customer_id) inside a for loop, and you have made 51 to the database where one would do. Each await looks harmless, and the handler still passes tests with three rows.

The fixes are plain SQL. the tables in one query. Or collect the ids into a Vec, fetch them all together with WHERE id = ANY($1), and match them up with a HashMap.

SQLx logs every statement it runs through the tracing , so turn that on in development and count the queries per request.

Common traphiding the query inside a small helper function, so the loop in the handler looks innocent.

A question to check yourself, an AI practice session and 1 cheat sheet entry come with the full roadmap. Unlock

Resources for this stage

Start with· follow one of these

Practise

Keep handy

  • Query macros, pools, transactions, migrations and offline mode, with PostgreSQL examples

Also worth your time

Mark this stage as not done?