Playbook: speed up slow catalog queries

Your catalog page takes 2.4 seconds. You open the code, nothing looks wrong — the query is three lines, the ORM is doing its job. You add a cache, it gets better for a day, then the catalog is slow again, and now you have two problems: the slowness and a cache that hides a bug. Sound familiar?

The trap is that "slow catalog" has at least three different causes that live in three different places: the SQL text, the index, and the application loop. Each one has its own fix, and the fixes do not overlap. This playbook gives you a way to find which one you have — from database logs, not from reading code and hoping — and a ready brief you can hand to your AI assistant so it does the same thing instead of guessing.

Which symptoms mean this is your problem

Before you touch anything, check that you are actually in the catalog-query case and not in a frontend, network, or cold-start case. The signs are specific: More on the topic: “Audit Your Own Query Log Before Choosing BM25 or Embeddings for RAG”.

  • Time scales with catalog size, not with traffic. 10,000 products load in 400 ms, 200,000 in 6 seconds. That is a query plan problem, not a server problem.
  • The same page is fast on the second load. A cache or the database's own buffer pool is masking a query that is genuinely expensive on first read.
  • p95 latency is bad, the average is fine. Averages hide the tail; a few slow queries drag the percentile up while most requests are quick.
  • Response time grows with the number of items on the page. 20 products are fast, 100 products crawl. That is the signature of N+1: one query per row.
  • The database CPU is high but the query count per request is low. That points to a single heavy query with a bad plan, not to a storm of small ones.

If none of these hold — if the page is slow even when the database is idle — stop. You are debugging the wrong layer, and no index will save you. More on the topic: “Your Backend Is a Slow Leak: LLM Prompts That Catch Memory Hogs, Query Bloat, and Crash Triggers Before the Pager Goes Off”.

Why it happens: three causes, three mechanisms

A catalog query is slow for one of three reasons, and the mechanism matters because it tells you which tool will see it.

Missing or unused index. The database has to scan every row of the products table to find the 20 that match your filter. On 200,000 rows that is cheap-ish; on 5 million it is not. The database log shows one query with a high total time and a plan full of Seq Scan. The fix is an index — but only if the filter column and the sort order actually match what the query asks for.

N+1. Your code loads 100 products in one query, then for each product fires a separate query to fetch its category or price. That is 101 queries where 2 would do. The database log shows 101 near-identical fast queries per request. No index helps, because each query is already fast — the cost is in the count. This is the most common misdiagnosis: people see slow catalog, add an index, and nothing changes, because the problem was never the query.

Bad plan on a correct query. The index exists, the query is fine, but the planner chooses a sequential scan because statistics are stale or the query is written in a way the planner cannot use the index (a function on the column, a type mismatch, a LIKE '%term%' that cannot use a B-tree). The log shows the query, the plan shows the scan, and EXPLAIN on the exact statement shows why.

What it costs: every 100 ms of catalog latency is a visitor deciding whether to wait. You do not need a study to know that a catalog that takes seconds loses sessions — but the honest engineering cost is simpler. You spend days adding caches and micro-optimizations to a problem that one index or one JOIN would have closed in an hour, and every cache you add is a new source of stale data you now have to keep accurate.

The cause decides the tool A missing index shows up as few queries with high total time. N+1 shows up as many queries with low individual time. A bad plan shows up as a correct query with a scan in `EXPLAIN`. Read the log before you choose a fix, or you will fix the wrong layer.

The five numbers you read first

You do not need a dashboard. You need pg_stat_statements — the PostgreSQL extension that aggregates execution statistics per normalized query — plus the slow query log. The normalized form of a query is the statement with literals replaced by placeholders, so 10,000 calls of the same shape collapse into one row with a call count. That collapse is exactly how you tell N+1 from a single heavy query.

Turn it on once (this is a config example — verify the exact syntax against your PostgreSQL version):

-- postgresql.conf
shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.track = all

Then read the top offenders by total time, not by mean time:

SELECT calls,
       round(total_exec_time::numeric, 1) AS total_ms,
       round(mean_exec_time::numeric, 1)  AS mean_ms,
       rows,
       left(query, 120) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;

Read the result like this:

Pattern in the log What it means Where to look next
One query, high total_ms, high mean_ms, many rows Heavy query with a bad plan EXPLAIN (ANALYZE, BUFFERS) on that statement
One query shape, calls in the thousands, mean_ms under 1 N+1 Application loop that calls it per row
calls grows with page size, rows is always 1 N+1 on a lookup (category, price) The code that fetches per item
High total_ms, rows low, mean high Scanning a lot to return little Missing or unusable index

That table is the whole diagnosis. If calls for one query shape is roughly the number of items on the page times the number of requests, you have N+1. If it is one call with a high mean, you have a query problem.

Brief for your AI

Copy this block to your assistant. It is written so the assistant proves the cause before editing, and stops instead of guessing. More on the topic: “Stop Guessing at Indexes: Prompts That Make an LLM Read EXPLAIN ANALYZE Like a DBA”.

A. Role and context

You are a backend developer working in an existing repository you did not write. The project is a product catalog: a PostgreSQL database behind an application server, with an ORM or query builder. The catalog endpoint is slower than acceptable. You do NOT yet know whether the cause is the SQL, the index, or the application code — that is what you must find out. Do not assume any of the three. More on the topic: “SQL and Databases: What You Need to Know Before Starting — A Real-World Problem Breakdown and Pitfalls”.

B. Goal and Definition of Done

The catalog endpoint must return the same data, in the same order, with the same fields, and respond measurably faster. Done means:

  • The cause is named in writing and backed by a log line, a metric, or an EXPLAIN output.
  • The change is minimal and touches only what the cause requires.
  • A before/after measurement exists, produced by the same command run twice, with the numbers written down.
  • The response payload is identical before and after (same rows, same order, same fields).

"Improve performance" is not a Definition of Done. A number and an identity check are.

C. Boundaries

  • Do not change the public API: same route, same parameters, same response schema.
  • Do not change the database schema beyond adding an index, and only if the cause requires it.
  • Do not change user-visible behaviour: no pagination changes, no reordering, no dropped fields.
  • Do not add caching, connection-pool tuning, or a new dependency unless the cause is proven to be outside the query and you ask first.
  • Stop and ask if you cannot reproduce the slowness locally, or if the log does not clearly point to one cause.

D. Phases — think first, act second

Phase 0 — Understand. No edits. Read the catalog endpoint code. Find every query it issues and every place it loops over rows. Write down your hypothesis about the cause in one sentence, before touching anything. Editing in this phase is forbidden.

Phase 1 — Plan and risks. List the steps with the expected effect of each. For every step, name what could break and how you would roll it back. If the plan requires a schema change, say so explicitly and wait for confirmation.

Phase 2 — Prove the hypothesis. Run a cheap experiment that confirms or kills your hypothesis: query pg_stat_statements and check whether the call count matches N+1 or whether one query has a high mean. If the hypothesis fails, return to Phase 0. Do not guess a second cause — go back and read.

Phase 3 — Implement. One minimal change at a time, each with its reason stated. If you add an index, create it without locking the table (see the online-index note below). If you fix N+1, replace the per-row query with one batched query and keep the result order identical.

Phase 4 — Verify. Give the exact commands: the test suite, the linter, and the before/after measurement command with its expected output. Not "make sure it works" — a command and a number.

Phase 5 — Report. What changed, the before/after numbers, what is still unknown, and what a human must check.

E. Forbidden

  • Acting without a stated hypothesis.
  • Rewriting code that is not part of the cause.
  • Inventing an API, a flag, a PostgreSQL parameter, or a number.
  • Adding a cache to hide a query problem.
  • If information is missing — ask and stop. Do not fill the gap with an assumption.

F. Report format

Done: …
Verified with command: … → output: …
Before/after: … ms → … ms
Left open: …
Risks: …

Ready-to-send prompts

  1. Diagnose. "Read the catalog endpoint and every function it calls. Do not edit anything. List every SQL query it issues and flag any query fired inside a loop. State your hypothesis about the cause in one sentence."
  2. Prove. "Here is the output of pg_stat_statements ordered by total time. Tell me which cause the numbers point to — missing index, N+1, or bad plan — and what single experiment confirms it. Do not propose a fix yet."
  3. Plan. "Given the confirmed cause, write a plan: the minimal change, what could break, and how to roll back. If it needs an index, give the exact CREATE INDEX statement and confirm it does not lock the table."
  4. Implement. "Apply only the change from the plan. One change. State the reason for each line you touch."
  5. Verify. "Give me the exact commands to run the tests, the linter, and a before/after timing on the same endpoint with the same data. Tell me what output counts as success."
  6. Review. "Review your own change against the boundaries: did the API, schema, order, or fields change? Report done / verified / left open / risks."

Adding an index without freezing the catalog

If the cause is a missing index, the naive CREATE INDEX blocks writes to the table for the whole build. On a large products table that is minutes of a frozen catalog — the fix causes a worse outage than the bug.

Use the concurrent form (verify against your PostgreSQL version; this is standard syntax):

CREATE INDEX CONCURRENTLY idx_products_category_created
  ON products (category_id, created_at DESC);

What you pay: CONCURRENTLY cannot run inside a transaction block, it takes longer to build, and if it fails it leaves an invalid index you must drop and rebuild. What you gain: writes keep flowing while it builds. On a catalog that is live, that trade is almost always worth it.

Match the index to the query, not the column An index on category_id does not help a query that filters by category and sorts by created_at DESC. The composite index above matches both the filter and the sort, so the planner can use it for both. Check the plan after creating it — if it still says Seq Scan, the index does not match the query shape.

How to verify it got better

A fix without a measurement is a guess with extra steps. Compare before and after with the same command, the same data, and the same endpoint.

First, confirm the plan actually changed:

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, name, price
FROM products
WHERE category_id = 42
ORDER BY created_at DESC
LIMIT 20;

What counts as success: Index Scan or Bitmap Index Scan instead of Seq Scan, and a lower Execution Time. If the plan did not change, the index does not match the query — go back, do not re-run and hope.

Second, measure the endpoint. Run the same request N times and compare the p95, not the average:

# example: verify the tool and flags against your setup
for i in $(seq 1 50); do
  curl -s -o /dev/null -w "%{time_total}\n" \
    "https://your-host/api/catalog?category=42&limit=20"
done | sort -n | tail -5

Success criteria, decide them before you start:

  • The p95 drops by a margin you agreed on (for example, from 2.4 s to under 400 ms).
  • The row count and order of the response are identical to the pre-change response — diff the JSON.
  • pg_stat_statements shows the call count per request dropped (N+1 case) or the mean time dropped (index case).

If the number did not change, do not add a cache. Go back to Phase 0: either the cause was different, or the index does not match the query, or the bottleneck moved to the application (serialization, N+1 still present behind the fixed query). Measure again before touching anything.

Accuracy is part of the definition of done A faster catalog that returns different rows, a different order, or a missing field is not a fix — it is a new bug with better latency. Diff the response payload before and after, every time.

The mistakes that cost the most

Adding a cache first. It makes the symptom disappear on warm loads and hides the cause. When the cache misses, the catalog is still slow, and now you debug two layers.

Adding an index to fix N+1. Each of the 101 queries is already fast; the index changes nothing about the count. You spend an hour and learn nothing.

Creating the index without CONCURRENTLY on a live table. The build locks writes, the catalog freezes, and you have turned a slow page into a short outage.

Trusting the average. The average looks fine because most requests are quick; the p95 is where users live. Measure the tail.

Declaring victory from one run. A single fast request proves nothing — the buffer pool was warm. Run the same command many times and compare the same percentile.

None of this is exotic. The whole playbook is one discipline: read the log, name the cause, prove it with a cheap experiment, make the minimal change, and measure the same number you measured before. Hand the brief to your AI and it will do the same — as long as you hold it to the rule that it states a hypothesis before it edits a line.

AssetMaterials for this article

A document from this article — download and apply it.

  • XLSXCatalog Query Triage Sheet pg_stat_statements to Cause and Fix.xlsxXLSX · 8.5 KBDownload
← All posts

Ask AI about this article

Ask a question about this article — ASI Biont will answer based on its text and the attached files.