Reading Execution Plans Like a Detective: Indexes, Cardinality, and Silent N+1 Traps
A systematic approach to diagnosing slow backend endpoints by inspecting EXPLAIN ANALYZE plans, designing composite B-Tree indexes around actual access patterns, and fixing hidden N+1 loops.
J Ananthakrishnan
Developer · SAP Labs India
Why Slow Queries Rarely Look Slow in Code Review
An endpoint that loads cleanly in 18 milliseconds on a laptop with 200 seeded rows can silently degrade to 6 seconds once a table crosses a few million records. Almost every production query regression I have investigated comes down to one of three culprits:
- Mismatched composite index column order causing unexpected sequential scans or expensive in-memory sorts.
- Stale planner statistics / low selectivity tricking the optimizer into nested loops over huge row sets.
- ORM-induced N+1 round trips hiding behind clean-looking object traversal.
Step 1: Never Guess, Read EXPLAIN (ANALYZE, BUFFERS)
Before adding an index, always inspect both timing and buffer reads. Execution time fluctuates with OS cache warmth; shared buffer hits/reads tell you how much actual work the database did.
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, status, created_at, total_cents
FROM orders
WHERE tenant_id = 't_42'
AND status = 'OPEN'
ORDER BY created_at DESC
LIMIT 25;Look closely at three signals in the output:
- Estimated rows vs. Actual rows: A 100x mismatch signals stale statistics (
ANALYZE) or correlated columns needing extended statistics. Rows Removed by Filter: High numbers here mean the index matched far too many rows and PostgreSQL had to fetch heap pages only to discard them.Sort Method: external merge Disk: The query spilled to disk because no index satisfied theORDER BYnatively.
Equality Prefix
(tenant_id, status)
Sort / Range Key
created_at DESC
Covering Payload
INCLUDE (total_cents)
Early Termination
Stop after 25 index tuples
Step 2: The Equality-First, Range/Sort-Last Rule
For the query above, a single-column index on tenant_id or created_at leaves work on the table. A composite covering index aligned with the predicate lets PostgreSQL jump directly to (tenant_id, status), read the first 25 entries already sorted by created_at DESC, and avoid heap fetches entirely:
CREATE INDEX CONCURRENTLY idx_orders_tenant_status_created
ON orders (tenant_id, status, created_at DESC)
INCLUDE (total_cents);Why Column Order Is Not Symmetric
A B-Tree index on (tenant_id, status, created_at DESC) serves:
WHERE tenant_id = ?WHERE tenant_id = ? AND status = ?WHERE tenant_id = ? AND status = ? ORDER BY created_at DESC
It does not efficiently serve WHERE status = ? alone, because tenant_id is the leading key. Always derive indexes from your hottest read shapes, and periodically prune unused indexes, because every extra index slows down writes and inflates WAL volume.
Step 3: Catching Silent N+1 Loops Early
Sometimes every individual SQL query executes in < 1 ms, yet the API request takes 900 ms. When you inspect query telemetry, you find 1 query fetching 100 orders followed by 100 individual queries fetching line items.
Fix it structurally with batched IN / ANY lookups or explicit eager joins:
from collections import defaultdict
import psycopg
def fetch_orders_with_items(conn: psycopg.Connection, tenant_id: str, limit: int = 25) -> list[dict]:
orders = conn.execute(
"""
SELECT id, status, created_at, total_cents
FROM orders
WHERE tenant_id = %s
ORDER BY created_at DESC
LIMIT %s
""",
(tenant_id, limit),
).fetchall()
if not orders:
return []
order_ids = [row[0] for row in orders]
# Single batched round-trip instead of N separate queries
item_rows = conn.execute(
"""
SELECT order_id, sku, quantity
FROM order_items
WHERE order_id = ANY(%s)
""",
(order_ids,),
).fetchall()
items_by_order: dict[str, list[dict]] = defaultdict(list)
for order_id, sku, qty in item_rows:
items_by_order[order_id].append({"sku": sku, "quantity": qty})
return [
{
"id": oid,
"status": status,
"created_at": created_at,
"total_cents": total_cents,
"items": items_by_order[oid],
}
for oid, status, created_at, total_cents in orders
]Checklist Before Shipping Any Data-Heavy Endpoint
- Capture
EXPLAIN (ANALYZE, BUFFERS)against realistic table cardinalities, not 50-row test fixtures. - Add a query-count assertion in integration tests so an accidental ORM N+1 regression fails CI immediately.
- Prefer keyset (cursor) pagination (
WHERE created_at < $cursor) overOFFSETfor deep lists so page 500 stays just as fast as page 1.
Continue Reading
Related Articles
Distributed Systems · 5 min read
Designing Idempotent Asynchronous Pipelines: Transactional Outbox & Retry Budgets
Why naive 'write to database, then publish to queue' fails in production, how the Transactional Outbox pattern closes the dual-write gap, and how to design consumers that survive duplicate deliveries gracefully.
Aug 18, 2026
AI & Tooling · 4 min read
AI-Assisted Code Review Workflows That Actually Help Engineers
Practical engineering lessons on pairing deterministic static checks with scoped LLM review prompts to cut review turnaround without flooding pull requests with noisy comments.
Jun 12, 2026
AI & Tooling · 3 min read
Exploring the Wonders of ChatGPT: A Glimpse into Conversational AI
Turn your GitHub Issues into a powerful Next.js blog to write more and publish faster!
Apr 2, 2024