Skip to main content
Back to Knowledge Library
Database Performance4 min read

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.

AK

J Ananthakrishnan

Developer · SAP Labs India

PostgreSQLQuery OptimizationBackend EngineeringPerformanceSQL

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:

  1. Mismatched composite index column order causing unexpected sequential scans or expensive in-memory sorts.
  2. Stale planner statistics / low selectivity tricking the optimizer into nested loops over huge row sets.
  3. 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.

diagnostics/inspect_plan.sql
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 the ORDER BY natively.
Anatomy of an Index-Only Top-N Lookup

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:

migrations/002_orders_composite_index.sql
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:

repositories/order_loader.py
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) over OFFSET for deep lists so page 500 stays just as fast as page 1.
Found this engineering note useful? Share it with a teammate.
LinkedInX

Continue Reading

Related Articles