Your catalog search takes 1.8 seconds at p95. The first instinct — drop Redis in front of it — feels right until a price update lands and buyers see stale prices for ten minutes, or a new SKU doesn't appear until the cache expires. That's not a search fix; it's a symptom hider.
The real fix is to read the query plan, add the right indexes, and rewrite the queries that can't use them. This playbook gives your AI assistant a step-by-step brief to do exactly that — and a measurement to prove it worked.
Signs the problem is yours (before you touch the cache)
If any of these sound familiar, you're in the right place:
- p95 latency creeps up as the catalog grows. Search was fine at 10k products; at 200k it's painful. Cache hides it until the cache misses.
- Filter combinations feel random.
category + price rangeis fast, butcategory + price + in_stockis slow. That's a missing composite index, not a network issue. - Search by partial name is slow.
LIKE '%phone%'scans every row because a B-tree can't help with a leading wildcard. - The ORM logs show a burst of queries per search. One search page fires 40 queries — classic N+1.
- You've already added hardware. More RAM helped for a week, then the data grew again.
Why it happens: the mechanism and the cost
A database executes a query by choosing a plan. If there's no index that matches your filter columns in the right order, it falls back to a sequential scan (seq scan) — reading every row in the products table. At 100k rows that's milliseconds; at 2 million it's seconds, and it gets worse linearly. More on the topic: “Your Index Guess Is a Coin Flip: Prompts That Make an LLM Read EXPLAIN ANALYZE and Name the Bottleneck First”.
Composite indexes work left-to-right. An index on (category, price) helps WHERE category =? AND price >? but not WHERE price >? alone. If your search filters on category, price, and status, you need an index that starts with the most selective column and includes the others. Without it, the planner may still choose a seq scan because the estimated cost of using a partial index is higher than just scanning.
Partial-text search has the same issue. LIKE '%text%' cannot use a B-tree index because the wildcard is at the start. PostgreSQL's pg_trgm extension provides trigram indexes that make ILIKE '%text%' fast — but only if the extension is installed and the index is created with the right operator class.
And then there's the ORM. A search result page often loads products, then for each product loads its category, brand, and stock — 1 + N queries. With 50 results that's 51 round trips. The fix is eager loading (JOIN or IN), not a cache.
The cost is concrete: a seq scan on a 1M-row table might take 800ms; with the right index it's 5ms. Multiply by every search request and you're burning CPU and IOPS that you then try to fix with a bigger instance. The cache adds memory cost and staleness risk on top.
- Hides slow query until cache miss
- Serves stale prices after updates
- Costs memory and invalidation logic
- Does not fix N+1 or seq scans
- Makes every query fast at the source
- Always returns current data
- Costs one-time index creation
- Eliminates N+1 with eager loading
The playbook: a brief for your AI assistant
Hand this block to your AI. It assumes the assistant has access to the repository and can run commands. It is written as a sequence of phases; each phase requires thinking before acting.
A. Role and context
You are a developer working in an existing repository. The project is a web catalog with a search feature. The stack is [fill in: e.g., PostgreSQL 15, Django 4.2, Redis optional]. Known: search is slow at p95; there is no query logging enabled yet. Unknown: which queries are slow, whether indexes exist, how the ORM generates SQL.
B. Goal and Definition of Done
Reduce the p95 latency of the catalog search endpoint from its current baseline to under [target, e.g., 200ms] on the same dataset, without adding a cache layer. Done means: (1) slow query log enabled and top-3 queries identified by total cost; (2) at least one composite index and one trigram index added if the plan shows seq scans; (3) N+1 queries eliminated; (4) before/after measurement recorded; (5) a regression test that fails if p95 exceeds the target.
C. Boundaries
Do not change the public API, database schema (except adding indexes), or user-visible behavior. Do not add new dependencies without asking. Do not introduce Redis or any cache. Stop and ask if you need to modify application logic beyond query construction.
D. Phases
Phase 0 — Understand. Read the search endpoint code, the ORM models, and any existing migrations. Find every call site that builds the search query. Write a hypothesis about the cause (e.g., "missing composite index on (category, price, status) causes seq scan") before any edit. Editing is forbidden in this phase.
Phase 1 — Plan and risks. List the steps with expected effect, what can break (e.g., index creation locks writes), and how to roll back (drop index). Estimate the time for each step.
Phase 2 — Prove the hypothesis. Enable slow query logging (e.g., log_min_duration_statement = 200 in PostgreSQL). Run a representative search. Use EXPLAIN (ANALYZE, BUFFERS) on the top query. Confirm the plan shows Seq Scan or high cost. If the hypothesis fails, return to Phase 0.
Phase 3 — Implement. Add indexes one at a time, each with a comment explaining why. For composite indexes, order columns by selectivity. For trigram, CREATE EXTENSION IF NOT EXISTS pg_trgm; then CREATE INDEX... USING gin (column gin_trgm_ops);. Rewrite ORM queries to use select_related/prefetch_related or explicit joins. Each change must have a reason tied to the plan.
Phase 4 — Verify. Run the same search with EXPLAIN (ANALYZE, BUFFERS) and record execution time. Run the application's test suite. Measure p95 latency with a load test (e.g., ab or wrk) before and after. Expected: p95 drops below target; plan shows Index Scan or Bitmap Index Scan.
Phase 5 — Report. List what was done, numbers before/after, what is still unknown (e.g., behavior under write load), and what a human must check (e.g., migration on production).
E. Forbidden
Do not act blindly. Do not rewrite code that was not asked for. Do not invent API names, flags, or numbers. If information is missing, ask questions and stop.
F. Report format
A short list: done / verified with command X / left open / risks.
Ready-to-send prompts for your AI
Use these in order. Replace bracketed placeholders.
- Diagnose: "Read the search endpoint in [file path] and the related models. List every query it generates. Do not edit anything. Write a hypothesis about why it's slow, citing the specific columns and filters."
- Plan: "Based on your hypothesis, propose a plan to prove it. Include the exact commands to enable slow query logging and run EXPLAIN ANALYZE. List risks and rollback steps."
- Implement: "Add the indexes and query changes you proposed, one at a time. After each change, run EXPLAIN ANALYZE and paste the output. If the plan does not improve, revert and explain."
- Verify: "Measure p95 latency before and after using [load test command]. Record the numbers. Run the test suite. Confirm no regressions."
- Review: "Review the diff. Check that no public API or schema changed. Confirm the regression test fails if p95 exceeds [target]."
How to verify it got better
Compare these numbers before and after:
| Metric | Before | After | Target |
|---|---|---|---|
| p95 latency (search endpoint) | 1800 ms | ? | < 200 ms |
| Top query execution time (EXPLAIN ANALYZE) | 800 ms | ? | < 10 ms |
| Number of queries per search | 51 | ? | 2 |
| Seq scans on products table | yes | no | no |
Success is when p95 is below target and the plan shows index usage. If the number did not change, check: (1) did you run ANALYZE after creating the index? (2) is the query using the index or still seq scanning? (3) did the ORM generate the expected SQL? (4) is the load test hitting a cached layer you forgot about?
What this playbook does not cover
This is for read-heavy search on a relational database. If your catalog is sharded across multiple databases, or if you need full-text search with ranking, consider a dedicated search engine — but only after you've fixed the basics. The same measurement discipline applies.
One neutral reference: PostgreSQL documentation on EXPLAIN and pg_trgm is the primary source for the commands used here. Always verify syntax against your database version.
The bottom line
A cache is a bet that your data doesn't change. Catalog data always changes. The playbook above turns a vague "search is slow" into a measured, indexed, tested fix — and leaves you with a regression test so it doesn't come back. More on the topic: “Playbook: speed up slow catalog queries”.