Your catalog page 1 answers in 40 ms. Page 40 answers in 900 ms, and page 200 times out. The database CPU chart has a sawtooth you cannot explain. That is the moment this playbook is for.
Here is the sequence: measure p95 response time and the share of requests that go deeper than the 50th page, decide from those two numbers, migrate only the listings that need it, and prove the change with EXPLAIN and a load run before/after. By the end you will have a decision criterion you can hand to your AI assistant and a way to check it did not cheat.
Which symptoms mean this is your problem
Not every slow listing is a pagination problem. These signs point at it specifically:
- Latency grows with page number. Page 1 is fast, page 100 is slow, and the curve looks roughly linear. That is the signature of
LIMIT... OFFSET...scanning and discarding rows. - The slow queries share one shape. In your slow query log the offenders are all
SELECT... ORDER BY <something> LIMIT 20 OFFSET 4000, not a mix of unrelated queries. - Users and crawlers page differently. A bot walking page 2, 3,... 500 for SEO inflates the deep tail; a human rarely goes past page 5. If you only look at averages, the bots hide inside the mean.
- Duplicates or skips on insert. A user paging forward sees the same product twice, or misses one, right after a new item was added to the catalog. With OFFSET, an insert before the current offset shifts every subsequent row by one.
If none of these hold — page 1 is also slow, or the slow queries are joins on filters — you have an index problem, not a pagination problem. Fix the index first; it may be all you need.
Why it happens: OFFSET pays for rows it throws away
OFFSET 4000 does not mean "jump to row 4000". It means "produce 4020 rows in sort order, discard the first 4000, return 20". The database still walks the index (or worse, sorts the whole result set), and the cost grows with depth. On a catalog with a stable sort this is cheap-ish at page 3 and brutal at page 300.
Cursor pagination — also called keyset pagination — replaces the offset with a condition: WHERE (sort_key, id) > ('last_seen_value', 42) ORDER BY sort_key, id LIMIT 20. The index seeks straight to the position, so the cost is roughly constant regardless of depth.
The trade-off is not free:
| Property | OFFSET | Cursor (keyset) |
|---|---|---|
| Cost at depth | grows with page number | roughly constant |
| Jump to "page N" | trivial | not possible without a stored position |
| Behavior on insert during paging | duplicates / skips | stable, no duplicates |
| Requirement | none | unique, stable sort key |
| Sort by relevance or a mutable field | works | breaks unless the key is immutable |
That last row is where most migrations die. If your catalog default sort is "relevance" computed per request, or "popularity" that changes hourly, there is no stable key to seek on. Cursor pagination needs a sort key that is unique and does not change between requests — usually (created_at, id) or (price, id), never a score that is recomputed.
The decision criterion: two numbers, one verdict
Do not argue about which is better. Measure two things over a representative week:
- p95 response time per page bucket (page 1–10, 11–50, 51–200, 200+).
- Share of requests deeper than page 50, split by user agent class (human vs bot).
Then apply the rule:
- Deep tail under ~5% of requests and p95 under your SLO at every bucket → keep OFFSET. Fix the index and move on. Migrating here is churn.
- Deep tail heavy (bots, infinite scroll, large exports) or p95 blows the SLO past page 50 → move the listing and the feed to cursor pagination.
- You need both → keep a separate, crawlable, indexable path for SEO page navigation and move the interactive listing to cursor. They are different clients with different needs; one endpoint does not have to serve both.
The threshold is yours to set from your SLO — 5% is a starting point, not a law. What matters is that the decision comes from logged numbers, not from a blog post (including this one).
Brief for your AI
Hand this block to your assistant as-is. It is written so the AI investigates before it edits and stops rather than guesses. 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 developer working in someone else's repository. The project is a catalog service with a paginated listing endpoint. Stack and details you must confirm by reading the code, not assume: the web framework, the ORM or query builder, the database engine and version, the migration tool, the test runner. What is known: the listing uses OFFSET pagination and some deep pages are slow. What is NOT known: which queries are slow, how deep real traffic goes, whether the sort key is unique and stable. Find those out before changing anything.
B. Goal and Definition of Done
Goal: reduce p95 response time for deep listing pages, or prove that OFFSET with a fixed index already meets the SLO.
Done means all of the following, each with evidence:
- A written measurement of p95 latency per page bucket and the share of requests deeper than page 50, taken from logs or a load run, before any change.
- A decision recorded in writing: keep OFFSET (with index fix) or migrate to cursor — justified by those numbers against the criterion above.
- If migrating: the listing endpoint returns a cursor, the public response shape is either unchanged or versioned, and tests cover first page, next page, last page, and the insert-during-paging case.
- A before/after comparison with the same load command, showing the p95 numbers side by side.
- EXPLAIN output for the deep-page query before and after, showing the plan change.
C. Boundaries
- Do not change the database schema unless a missing index is the proven cause; an index is a schema change, so propose it and wait for approval.
- Do not break the public API contract. If the response must change, add a new versioned path and leave the old one working.
- Do not add dependencies (no new pagination library, no new caching layer) unless you can name why the existing stack cannot do it.
- Do not touch unrelated endpoints, auth, or the SEO sitemap generation.
- Stop and ask if: the sort key is not unique, the sort is computed per request, or you cannot find where the cursor would be produced.
D. Phases — think first, act second
Phase 0 — Understand (no edits). Read the listing handler, the query builder call, the model definition, the indexes on the table, and every call site of the listing function. Write down: the exact SQL generated for page 1 and page 100, the sort columns, whether the sort key is unique, and where the response is serialized. State a hypothesis in writing: "deep pages are slow because X". Do not edit yet.
Phase 1 — Plan and risks. List the steps with the expected effect of each. Name what can break: clients that rely on page/offset parameters, SEO crawlers hitting numbered pages, tests that assert total counts. Name the rollback: keep the old endpoint path until the new one is verified. Write this plan before touching code.
Phase 2 — Prove the hypothesis. Run EXPLAIN (or EXPLAIN ANALYZE) on the deep-page query. Look for a sequential scan, a sort node over the full set, or a high "rows removed by filter" count. Run the load command against page 1 and page 100 and record p95 for each. If the plan does not show the cost growing with offset, your hypothesis is wrong — go back to Phase 0 instead of guessing.
Phase 3 — Implement, minimally. One change at a time, each with its reason in a commit message. If the decision was "keep OFFSET", the change is an index and nothing else. If the decision was "migrate", add the cursor path alongside the old one, wire it to the interactive listing, and keep numbered pages on a separate crawlable route.
Phase 4 — Verify. Run the exact commands: the test suite, the linter, the load run before/after, and EXPLAIN on the new query. Compare p95 numbers. Confirm the insert-during-paging test passes (no duplicates, no skips). Confirm numbered pages still return 200 for a crawler user agent. More on the topic: “Your A/B Test Passed. Now Prove It Wasn't Measuring the Wrong People: SQL Prompts That Hunt Sampling Errors Before You Trust the Uplift”.
Phase 5 — Report. Short list: what was done, p95 before/after per bucket, EXPLAIN plan change, what is still unknown, what a human must check (API consumers, SEO impact, index build time in production).
E. Forbidden
- Acting without a written hypothesis.
- Rewriting code that was not part of the task.
- Inventing API parameters, config flags, or benchmark numbers. If you did not run it, do not report it.
- Reporting "improved" without the before/after numbers.
- Guessing when information is missing — ask and stop.
F. Report format
- Done: …
- Verified with command X: …
- Left open: …
- Risks: …
Prompts to send, in order
1. Diagnose. "Read the listing handler and the query it builds. Show me the exact SQL for page 1 and page 100, the sort columns, and whether the sort key is unique. Do not edit anything. State your hypothesis about why deep pages are slow."
2. Prove. "Run EXPLAIN ANALYZE on the deep-page query and paste the plan. Run the load command against page 1 and page 100 and report p95 for each. Tell me whether the plan confirms or refutes your hypothesis."
3. Plan. "Given those numbers, decide between keeping OFFSET with an index fix and migrating to cursor, using the criterion: deep tail share and p95 per bucket. Write the plan, the risks, and the rollback before any edit."
4. Implement. "Implement only the first step of the plan. Keep the old endpoint working. Add tests for first page, next page, last page, and insert-during-paging."
5. Verify. "Run the tests, the linter, and the same load command as before. Show p95 before/after side by side and the new EXPLAIN plan. If any number did not improve, say so and explain why."
6. Review. "Review the diff against the boundaries: did you change the schema, break the API contract, or add dependencies? Report in the done/verified/left-open/risks format."
How to verify it got better
Success is a number, not a feeling. Compare these before and after, with the same load command and the same data volume:
| Metric | How to get it | What counts as success |
|---|---|---|
| p95 page 1 | load run | unchanged or better |
| p95 page 100 | load run | flat vs page 1 (cursor) or within SLO (OFFSET + index) |
| Deep-page query plan | EXPLAIN ANALYZE | index seek instead of scan + sort |
| Duplicates on insert | integration test | zero |
| Numbered pages for bots | curl with crawler UA | 200 and correct content |
The EXPLAIN check is the one people skip. If the plan still shows a sort node over the full result set, the latency may have dropped by luck (cache, smaller data) and will come back. The plan is the durable proof.
If the number did not move: first confirm the load run hit the deep pages at all (a load test against page 1 proves nothing about depth). Second, check whether the query is actually using the new index — a stale statistics table can make the planner ignore it; run ANALYZE on the table and re-check the plan. Third, if the plan is right but p95 is flat, the bottleneck is elsewhere — serialization, N+1 queries on the result rows, or the reverse proxy — and pagination was not your problem.
What this playbook does not decide for you
The criterion works when you have logs. If you do not yet log page depth per request, the first task is not migration — it is adding that field to the access log and waiting a week. Deciding from a hunch is how teams end up with a cursor endpoint nobody's clients use and a numbered-page endpoint still timing out for bots.
And keep the two clients separate in your head: a human scrolling a feed wants constant time and no duplicates; a crawler wants numbered, indexable pages. Cursor pagination is the right answer for the first and the wrong answer for the second. The playbook's real output is not "cursor everywhere" — it is a measured decision about which path each client takes. More on the topic: “Playbook: speed up slow catalog queries”.