Course contents

04. Database Fundamentals Lesson 10 of 10

Query Performance

See N+1 queries exhaust a connection pool, a join fix it, EXPLAIN reveal a missing foreign-key index, and keyset pagination replace slow OFFSET pages.

15 minIntermediate8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • N+1 queries make many cheap round trips; the connection is held for all of them.
  • Fetch related rows with one join or one batch: fewer round trips beat faster queries.
  • EXPLAIN (ANALYZE, BUFFERS) shows where time goes; a Seq Scan removing millions of rows on a selective filter means a missing index.
  • OFFSET reads and discards every skipped row; keyset pagination seeks and costs the same on every page.
  • Pool capacity = connections ÷ connection time per request, so query cost decides how much traffic you can serve.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Query performance is how much database time each request costs and where that time goes: executing the query, moving data, or waiting on round trips and connections. For an application it shows up in two places: latency per request, and how many requests per second the database and its connection pool can serve.

Why it exists

A request holds a pooled connection for as long as its database work takes. If that is 76 ms and the pool has 20 connections, the system tops out at about 260 requests per second, whatever the application servers can do. Most slow systems are not slow because the database is underpowered but because requests do far more database work than they need: too many round trips, scans where a lookup would do, rows read only to be thrown away.

How it works

N+1 queries. An ORM loads a list (1 query), then lazily loads a related object for each item (N queries). Each query may execute in well under a millisecond, but each is a full network round trip, executed one after another while the connection is held. 50 items cost 51 round trips. The database looks idle in per-query statistics; latency and pool time are consumed by the network.

Joins and batches. The fix is to fetch related data in bulk: a join, or one second query with WHERE id = ANY($1). ORMs call this eager loading (include, joinedload/selectinload, select_related/prefetch_related, JOIN FETCH).

Plans. EXPLAIN shows the plan the planner chose; EXPLAIN (ANALYZE, BUFFERS) runs the query and reports actual rows, time and pages per step. Warning signs: a Seq Scan with a large "Rows Removed by Filter" on a selective condition, estimated rows far from actual rows (stale statistics; run ANALYZE), sorts or hashes spilling to disk, nested loops over many rows.

Foreign keys. Postgres creates indexes for primary keys and unique constraints, not for the referencing column of a foreign key. Filtering or joining on orders.customer_id, or deleting a customer (which checks for referencing orders), scans the table unless you add that index.

Pagination. LIMIT 50 OFFSET 100000 reads 100,050 rows and returns 50, so cost grows with page depth. Keyset (seek) pagination remembers the last row's sort key and asks for WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 50; with an index on (created_at, id) every page is an index seek plus 50 rows.

When to use it

  • Before scaling hardware or pools: find the top queries by total time and cut their work first.
  • When latency rises with traffic while database CPU stays moderate: suspect round trips and pool wait.
  • When a query's latency grows with data volume: suspect scans and OFFSET.
  • In code review: watch for queries inside loops and unbounded result sets.

When not to

  • Do not hand-optimise queries that are a negligible share of total database time; sort by total, not by worst single execution.
  • Do not replace every lazy load with giant joins: joining several one-to-many relations multiplies rows. A second batched query is often better.
  • Do not force keyset pagination where users truly need to jump to arbitrary pages of small result sets; OFFSET on a few hundred rows is fine.

Trade-offs

Choice You gain You pay
Join instead of N+1 One round trip, predictable latency Wider rows; row multiplication with several one-to-many joins
Batched second query (= ANY) Few round trips, no row multiplication Two queries, assembly in the application
New index Lookups instead of scans Write cost, disk, memory; must be used by the planner
Keyset pagination Constant cost per page, stable under inserts No random page access; needs a unique, indexed sort key
Caching results Removes queries entirely Staleness and invalidation (see Cache-Aside)

Alternatives

  • Caching hot, rarely changing results in the application or a cache tier.
  • Denormalised or materialised views for expensive aggregates read often.
  • Read replicas to spread read load, once queries themselves are efficient.
  • Precomputed counts instead of COUNT(*) over large tables for "page X of Y".

Failure modes

  • N+1 that grows with data: fine with 10 items in development, 500 round trips in production.
  • Plan flips: statistics change and the planner switches to a worse plan; latency jumps without a deploy.
  • Missing foreign-key indexes causing slow joins and slow deletes on the parent table.
  • Deep OFFSET pages hit by crawlers or exports, quietly saturating the database.
  • Unbounded queries returning huge result sets that exhaust memory in the application.
  • Slow queries exhausting the pool, turning a single slow endpoint into errors everywhere.

In production

Enable pg_stat_statements and review the top queries by total time regularly. Use auto_explain with a duration threshold to capture plans of slow statements, and log_min_duration_statement for outliers. Trace requests so the number of queries per request is visible (an N+1 detector in tests helps too). Build indexes with CREATE INDEX CONCURRENTLY. After any fix, verify the new plan with EXPLAIN (ANALYZE, BUFFERS) on production-like data, and set statement_timeout so a runaway query cannot hold a connection forever.

Common misconceptions

  • "Each query is fast, so the page is fast." Fifty fast queries in sequence are a slow page.
  • "Postgres indexes foreign keys." It indexes the referenced key, not the referencing column.
  • "OFFSET with an index is cheap." The index avoids a sort, but skipped rows are still read.
  • "More connections fix slow queries." They let more slow queries run at once and add contention.

Interview angle

Interviewers probe whether you connect query cost to capacity: "each request holds a connection for X ms, the pool has N, so the ceiling is N ÷ X". Expect to spot an N+1 in a code sample, read a simple plan, propose the right index (and mention foreign keys), and choose keyset pagination for feeds and infinite scroll. Mentioning pg_stat_statements and total time versus mean time shows production experience.

Model assumptions

Simulated with a cost model, not a benchmark and not a query planner. Each request makes one call to the database in the engine; its duration is set by hand to stand for all of the request's database work, including round trips while the connection is held: ≈76 ms for 1 + 50 queries (≈0.5 ms execution plus ≈1 ms round trip each), ≈4 ms for one join, ≈150 ms with a sequential scan of two million rows, ≈5 ms with the index, ≈5/40/120 ms for OFFSET pages at depth 0/10,000/100,000 and ≈3 ms with keyset pagination. The database has 20 connections and a 1 s pool timeout. The round-trip packets and EXPLAIN annotations are scripted illustrations. Arrivals are random (Poisson), durations lognormal. Numbers are illustrative.

The lesson as textEvery step of the simulation, written out.
  1. 1. One page, fifty-one queries

    The orders page lists the 50 latest orders with their customer’s name. The ORM loads the orders with one query, then lazily loads each customer: one more query per order. That is 1 + 50 = 51 queries, the *N+1* pattern.

    Each query is fast, about half a millisecond, but each is also a network round trip with the connection held: together about 76 ms of connection time per page. At 100 pages per second the database pool is already about 40% busy. The slowed-down packets on the API are a scripted close-up of one page’s 51 round trips; the traffic behind them is simulated.

    Scene: Users load the orders page 100 times per second. Each page makes 51 small queries to Postgres, one after another; the scripted close-up shows the 51 round trips. Each page holds a connection for about 76 ms.

    Key idea: N+1 queries are many cheap queries whose round trips add up. The cost is latency and connection time, not database CPU.

  2. 2. Peak traffic exhausts the pool

    One second in, traffic grows to 300 pages per second. Twenty connections held for ~76 ms each can serve only about 260 pages per second, so the pool is always full.

    Pages now wait for a connection before their 51 queries can start. The line keeps growing and P95 climbs from about 130 ms to several hundred milliseconds, still rising; left alone, waits pass the 1 s pool timeout and pages start to fail. Database CPU is not the problem; nothing in a per-query view looks slow. The time goes into round trips and waiting.

    Scene: Traffic rises to 300 pages per second, more than 20 connections can serve. Pages queue for a connection, the queue keeps growing and latency climbs steadily toward the 1 s pool timeout.

    Key idea: Connection time per request × requests per second must fit in the pool. N+1 multiplies the first factor.

  3. 3. Fetch it in one query

    Replace the 51 queries with one join: SELECT o.*, c.name FROM orders o JOIN customers c ON c.id = o.customer_id ORDER BY o.created_at DESC LIMIT 50. In the ORM that is eager loading (include, joinedload, select_related, JOIN FETCH); a batched WHERE id = ANY($1) second query works too.

    One round trip, about 4 ms of connection time instead of 76. The pool drops to a few percent busy and P95 falls to around 25 ms at the same 300 pages per second. Fewer round trips beat faster queries.

    Scene: Each page now makes one join query: one round trip and about 4 ms of connection time. At 300 pages per second the pool is mostly idle and latency is low.

    Key idea: Fix N+1 by fetching related rows in one query (join) or one batch, not one row at a time.

  4. 4. A new query, and EXPLAIN says Seq Scan

    One second in, a release adds the customer’s previous orders to the page: SELECT … FROM orders WHERE customer_id = $1. Latency explodes and pool timeouts appear.

    EXPLAIN ANALYZE shows why (see the annotation): a Seq Scan over all two million orders, discarding all but about 50 rows, about 146 ms. customer_id is a foreign key, and Postgres indexes primary keys and unique constraints automatically, but not the referencing column of a foreign key. At 150 ms per page the pool can serve only about 130 pages per second.

    Scene: A new query filters orders by customer id without an index. The plan shows a sequential scan of two million rows; each page now holds a connection for about 150 ms, the pool saturates and requests time out.

    Key idea: Read the plan: “Seq Scan … Rows Removed by Filter: millions” on a selective filter means a missing index.

  5. 5. Index the foreign key

    CREATE INDEX CONCURRENTLY orders_customer_id_idx ON orders (customer_id) builds the index without blocking writes. One second in, it is ready and the plan changes to an Index Scan that reads only the matching rows, well under a millisecond.

    The page is back to about 5 ms of connection time, the waiting pages drain and errors stop. Always check the plan after the change: an index that the planner does not use is pure write overhead (see Database Indexes).

    Scene: One second in, the index on customer_id is ready. The plan becomes an index scan, each page takes about 5 ms of connection time again, the backlog clears and errors stop.

    Key idea: Index foreign-key columns you filter or join on, build it CONCURRENTLY, and confirm the new plan with EXPLAIN.

  6. 6. OFFSET gets slower with every page

    The order archive is paginated with ORDER BY created_at DESC LIMIT 50 OFFSET $n, and a partner’s export job plus a crawler walk it page by page at 150 requests per second. To return page *n*, the database still reads and throws away every row before it: OFFSET 100,000 reads 100,050 index entries to return 50.

    As they go deeper, the average query cost rises: about 40 ms at OFFSET 10,000 one second in, about 120 ms at OFFSET 100,000 from 2.5 s. The pool fills and P95 climbs, although the query text never changed.

    Scene: Clients page through the archive with growing OFFSET values. Each query reads and discards more rows, its cost rises from 5 to 120 ms, the pool fills and P95 latency climbs.

    Key idea: OFFSET pagination costs O(offset): deep pages read and discard everything before them.

  7. 7. Keyset pagination: continue from the last row

    Instead of a page number, the API returns a cursor: the (created_at, id) of the last row. The next page asks for WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 50, with an index on (created_at, id).

    The database seeks straight to that position in the index and reads 50 entries, whether it is page 2 or page 2,000. One second in, the job switches over: about 3 ms per page, the pool drains, latency drops. The trade-off: no jumping to “page 517”, and the sort key must be unique (hence the id tie-breaker).

    Scene: One second in, pagination switches to a keyset cursor. Every page is an index seek reading 50 rows, about 3 ms; the pool drains and latency drops.

    Key idea: Keyset (seek) pagination costs the same on every page: an index seek plus LIMIT rows.

  8. 8. Find the expensive queries, then read their plans

    Query time × query rate is the load on your pool and database. Find where it goes with pg_stat_statements (sort by total time, not just mean), auto_explain for slow statements in production, and application traces that show round trips per request (the N+1 signature).

    Then read the plan with EXPLAIN (ANALYZE, BUFFERS): sequential scans on selective filters, rows removed by filter, estimates far from actual rows, sorts spilling to disk. The fixes in this lesson, fewer round trips, the right index, keyset pagination, each cut connection time by an order of magnitude; no amount of pool tuning would.

    Scene: The Orders API serves archive pages with keyset pagination at 150 requests per second; each holds a connection for about 3 ms and nothing fails.

    Key idea: Measure total time per query shape, read the plan, and remove work: round trips, scans, discarded rows.