Backend development

Stage 2 · Lesson 11 of 11

The N+1 query problem

Relational databases and SQL

You do not need an to have an N+1 problem; a loop is enough. Load 50 orders, then call GetCustomer(ctx, order.CustomerID) inside the loop. You have made 51 to the database where one would do.

At 2 to 5 ms per round trip, that adds up fast. The fixes are plain . the tables in one query.

Or collect the ids and fetch them all together with WHERE id = ANY($1), then match the results up with a map. handles both well. Log queries with their timings in development, or add a pgx tracer, to count queries per request.

Common traphiding the query inside a small helper, so the loop looks harmless.

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

Also worth your time

Mark this stage as not done?