Skip to content

Lesson 6 of 13 · 20m

Indexes and Query Paths

Reading `EXPLAIN`, composite-index column order, `CREATE INDEX CONCURRENTLY`, the N+1 pattern, and why the planner sometimes picks `Seq Scan` on purpose.

Before replicas, before sharding, before any of it: EXPLAIN (ANALYZE, BUFFERS) on the slow query. Most of the time the database is doing a Seq Scan — reading every row in the table and discarding most of them — and the fix is a B-tree index, which turns "scan 50 million rows" into "descend a tree four levels deep."

What a B-tree actually does

An index is a sorted structure keyed on the indexed columns, stored as pages. WHERE id = 42 walks root → branch → leaf and reads one row. Sorting explains the composite-index rule: (tenant_id, created_at) is sorted by tenant first, then created_at within each tenant — so it serves WHERE tenant_id = 7, and WHERE tenant_id = 7 AND created_at > now() - interval '7 days', but a bare WHERE created_at > ... walks the whole index. Leftmost prefix: constrain columns from the left or the index can't help.

It also explains what a B-tree can't do: WHERE name LIKE '%son' isn't a sortable lookup — that needs pg_trgm plus a GIN index.

CREATE INDEX CONCURRENTLY idx_events_tenant_created
    ON events (tenant_id, created_at);

CONCURRENTLY isn't decoration. Plain CREATE INDEX holds a lock that blocks writes; on a live table that is a production outage measured in seconds. CONCURRENTLY skips the blocking lock, costs 2–3x longer, can't run inside a transaction (Django migrations need atomic = False; Alembic needs it outside the transaction wrapper), and leaves an INVALID index to drop and rebuild if it fails midway — REINDEX CONCURRENTLY exists since PG12.

What EXPLAIN is telling you

Seq Scan on a big table for a selective predicate = missing index. Index Scan with Rows Removed by Filter: 900000 = the index doesn't match the predicate order. Bitmap Heap Scan + Recheck Cond = a moderately selective lookup. Index Only Scan = the query never touched the table — that's a covering index, e.g. ON events (tenant_id) INCLUDE (status).

A partial index goes one step further: ON jobs (created_at) WHERE status = 'pending' indexes only the hot slice — tiny, fast, and exactly the rows the poller scans. EXPLAIN's cost= units are planner-internal (comparing plans, not milliseconds) — ANALYZE adds the real actual time= numbers you can trust.

The counterintuitive case: Postgres still chooses Seq Scan when a predicate matches a large fraction of the table — walking ~10–20% of rows through index pointers is slower than reading the file straight through. An index that "isn't used" is sometimes the planner being right.

The N+1

posts = Post.limit(50)                    # 1 query
posts.each { |p| puts p.user.name }       # + 50 queries

One query becomes 51 and the ORM hid it in a loop. Post.includes(:user) makes it two. pg_stat_statements (enabled via shared_preload_libraries) shows which normalized queries eat the most total time — optimize by aggregate, not by the single worst call.

Indexes cost writes

Every index is a structure every INSERT and UPDATE must also write. Ten indexes on a hot table is ten writes per insert. Auditing is one query: pg_stat_user_indexes.idx_scan shows reads per index — an index with zero scans is pure write tax. And keep indexed columns stable when you can: an UPDATE that doesn't touch them can do a HOT update on the same page and skip index maintenance entirely.

The connection ceiling

Postgres forks one process per connection and defaults max_connections to 100 — twenty app pods with ten connections each exhaust it instantly. PgBouncer in transaction mode multiplexes thousands of clients onto dozens of real connections, and historically broke prepared statements (fixed since PgBouncer 1.21 via max_prepared_statements). Apps hit this wall long before they hit table-size problems.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.