Fixing a Slow Query in 5 Minutes
Last Monday, our database monitoring dashboard fired an alert: CPU utilization had spiked to 98%. The culprit was a user-facing order history filtering feature. Instead of rushing to scale up our AWS RDS instance and adding hundreds of dollars to the monthly bill, I ran EXPLAIN ANALYZE to break down the query execution plan.
The orders table has around 2.5 million rows. The bottleneck query looked like this:
EXPLAIN ANALYZE
SELECT id, customer_id, total_amount, created_at
FROM orders
WHERE customer_id = 45892
ORDER BY created_at DESC
LIMIT 20;
The output clearly pinpointed the problem:
Limit (cost=45230.12..45230.17 rows=20 width=32) (actual time=312.450..312.455 rows=20 loops=1)
-> Sort (cost=45230.12..45241.50 rows=4552 width=32) (actual time=312.448..312.451 rows=20 loops=1)
Sort Key: created_at DESC
Sort Method: top-N heapsort Memory: 26kB
-> Seq Scan on orders (cost=0.00..45020.00 rows=4552 width=32) (actual time=0.042..309.820 rows=4600 loops=1)
Filter: (customer_id = 45892)
Rows Removed by Filter: 2495400
Planning Time: 0.145 ms
Execution Time: 312.512 ms
Two major bottlenecks were immediately apparent:
- Seq Scan: Postgres had to scan the entire table sequentially.
- Rows Removed by Filter: 2495400: The engine read nearly 2.5 million rows from disk just to filter down to 4,600 matching records, taking over 310ms. Afterward, the
Sortnode burned additional CPU cycles sorting that dataset.
The most straightforward fix was to create a composite index covering both the filter column and the sort order:
CREATE INDEX CONCURRENTLY idx_orders_customer_created
ON orders (customer_id, created_at DESC);
Running EXPLAIN ANALYZE again to verify the result:
Limit (cost=0.43..2.85 rows=20 width=32) (actual time=0.052..0.065 rows=20 loops=1)
-> Index Scan using idx_orders_customer_created on orders (cost=0.43..550.10 rows=4552 width=32) (actual time=0.050..0.061 rows=20 loops=1)
Planning Time: 0.120 ms
Execution Time: 0.088 ms
Execution time dropped from 312ms down to 0.088ms—more than 3,500 times faster. Database CPU usage dropped right back down to 15% without touching any hardware configurations.
How to Read Execution Plans Without Getting Lost
A plain EXPLAIN command only provides estimates based on catalog statistics. Only when you add the ANALYZE flag does Postgres actually execute the query, measure real elapsed time, and count the actual rows processed at each step.
1. The Plan Tree Structure
The rule of thumb: read from the inside out, bottom to top. The deepest indented node executes first, streaming its output up into its parent nodes.
2. Essential Metrics
- cost=X..Y: Arbitrary internal cost units calculated by the planner. X is the startup cost to fetch the first row. Y is the total cost to complete the node.
- actual time=A..B: Actual elapsed execution time in milliseconds (ms). A is when the first row was returned; B is when the node finished execution.
- rows vs actual rows:
rowsis the planner’s estimate, whileactual rowsis the count actually produced. If there is an order-of-magnitude discrepancy (for example, estimating 20 rows but returning 300,000), table statistics are stale, causing the planner to pick suboptimal scan strategies. - loops: How many times the node executed. Total real execution time =
actual time * loops.
3. Four Common Scan Types
- Seq Scan (Sequential Scan): Reads every block sequentially from the start to the end of the table. This is optimal for small tables (under a few thousand rows) or when retrieving more than ~30% of the data. Conversely, reading 20 rows out of millions makes it an I/O disaster.
- Index Scan: Traverses the index tree to locate physical tuple IDs (TIDs), then jumps to the main table (heap) to read data pages. Highly efficient for retrieving small numbers of rows.
- Bitmap Index Scan + Bitmap Heap Scan: When row matches are moderate (thousands to tens of thousands), a regular Index Scan triggers excessive random I/O. Postgres mitigates this by scanning the index first to build an in-memory bitmap marking which heap pages to read. Then,
Bitmap Heap Scanreads those pages sequentially in physical disk order. - Index Only Scan: The optimal scenario. All columns requested in the
SELECTclause are present directly within the index. Postgres satisfies the query straight from the index without fetching heap blocks (provided the visibility map indicates the pages are all-visible).
Choosing the Right Index Type: B-Tree, GIN, or BRIN?
A common pitfall when designing schemas is slapping a standard B-Tree index on every column. While B-Tree is versatile, it is not always optimal in terms of query performance and storage overhead.
1. B-Tree: The Default for Equality and Range Queries
B-Tree handles operators like =, <, <=, >, >=, BETWEEN, and ORDER BY efficiently. It works best on high-cardinality columns such as user_id, uuid, or email.
CREATE INDEX idx_users_email ON users(email);
2. GIN: Built for JSONB, Arrays, and Full-Text Search
B-Tree cannot index internal elements nested inside JSONB documents or array types. GIN (Generalized Inverted Index) resolves this by decomposing each key or element into an inverted index entry.
-- Create an optimized GIN index for the containment operator (@>) on a JSONB column
CREATE INDEX idx_audit_payload ON audit_logs USING GIN (payload jsonb_path_ops);
-- Postgres will perform a Bitmap Index Scan directly on the GIN index:
EXPLAIN ANALYZE
SELECT id, created_at FROM audit_logs
WHERE payload @> '{"status": "failed", "service": "payment"}';
When debugging JSON API payloads or testing complex regex patterns sent down to Postgres, you can leverage online formatting utilities like toolcraft.app (such as toolcraft.app/en/tools/developer/json-formatter) to quickly inspect and validate JSON syntax without opening a heavy IDE.
3. BRIN: The Optimal Pick for Massive Timeseries and Log Tables
For append-only tables containing hundreds of millions of rows—such as audit logs, clickstream events, or IoT telemetry—incoming data naturally correlates with physical disk order over time (via auto-incrementing id or created_at columns). Storing a standard B-Tree index on such tables can easily consume 10GB to 30GB of memory.
BRIN (Block Range Index) divides the table into block ranges (defaulting to 128 blocks, roughly 1MB) and stores only the minimum (min) and maximum (max) values for each range.
-- The tracking_events table contains 120 million rows, logged chronologically
CREATE INDEX idx_events_brin_created
ON tracking_events USING BRIN (created_at);
Real-world comparison on a 120-million-row table:
- Standard B-Tree Index: consumes approximately 2.6 GB.
- BRIN Index: consumes a mere 14 MB.
The BRIN index is nearly 200 times smaller, fitting entirely in RAM while delivering comparable filtering performance for time-range lookups.
Production Optimization Best Practices
- Always specify CONCURRENTLY when creating indexes: A standard
CREATE INDEXtakes an exclusive lock (ShareLock) on the table, blocking incomingINSERT,UPDATE, andDELETEstatements. Always useCREATE INDEX CONCURRENTLYso production traffic continues uninterrupted while Postgres builds the index in the background. - Wrap EXPLAIN ANALYZE in a transaction when testing write queries: Because
ANALYZEexecutes the query against the database engine, testing withEXPLAIN ANALYZE DELETE FROM sessions...will permanently delete real records. Always wrap it inside aBEGIN ... ROLLBACK;block:
BEGIN;
EXPLAIN ANALYZE
DELETE FROM sessions WHERE last_active < NOW() - INTERVAL '30 days';
ROLLBACK;
- Update statistics with ANALYZE after large data ingestions: When the query planner repeatedly chooses inappropriate Seq Scans, the root cause is often outdated statistics. Explicitly trigger
ANALYZE VERBOSE table_name;so the planner refreshes its distribution metadata. - Use Partial Indexes to conserve disk space and RAM: If queries predominantly filter for active or unhandled records, avoid indexing the entire table:
-- Index only the 2% of orders that are in 'pending' status
CREATE INDEX CONCURRENTLY idx_orders_pending
ON orders (created_at)
WHERE status = 'pending';
By mastering the execution plan tree and selecting appropriate index types tailored to your data access patterns, you can eliminate the vast majority of I/O bottlenecks without incurring expensive hardware upgrades.

