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.