Why page 40 took fourteen seconds

A paginated grid in a multi-tenant payments service got slower with every page. Four stacked mistakes, one flat result: page 1 and page 100 now cost the same.

This is the first post in a series about making a payments module for a property-management product fast, and then making its background jobs safe to run on a shared database. We start with the screen, because it was the first thing users complained about, and because it taught us a diagnostic we still use.

The screen

Operators open a grid of properties that can take payments. A large tenant has on the order of 15,000 active properties. The API is paginated at 25 rows per page, with free-text search and sorting by column. Nothing about that is exotic.

We measured it live against one large tenant. The network floor to that environment was about 0.9 seconds, so every figure below includes it.

RequestBefore
Page 1, 25 rowsabout 1.9s end to end
Page 40about 14s, climbing roughly 0.3s per page
Search for a short term35 to 50s
Three of those searches at onceeach still about 44s
Five ordinary concurrent list callslatency nearly doubled

Other list endpoints on the same service sat between roughly 1s and 6s. This grid was the outlier, and it got worse the deeper you scrolled. The three concurrent searches did not run in parallel. They queued behind each other on the same database CPU, which is why each of them still took 44 seconds.

The diagnostic: time the deep page

The most useful number in that table is the steady climb. Page 40 does not cost 14 seconds because the database is slow at skipping rows. It costs 14 seconds because something expensive happens for every row that gets skipped.

If page N is slower than page 1 by a steady amount per row, the work is happening before LIMIT is applied. That is a design bug in the query, not a load problem, and no amount of hardware makes it go away. We now time page 1, a deep page, a selective filter, a search that matches nothing, and a few concurrent callers before we call any list endpoint done.

Four mistakes, stacked

Authorization as a giant parameter list. The handler first loaded every property id the user was allowed to see, about 15,000 uuids, and then passed them to the main query as IN (...) or = ANY($1). Parsing, planning and transferring that list dominated the cost of even a simple page. The planner sees 15,000 constants where it should see a relation.

Offset pagination over a query that did too much per row. Skipping 975 index entries is cheap. Skipping 975 rows that each run a correlated subquery, or sit on top of a wide join, is not. Each skipped row paid for its own totals before being thrown away.

Sorting by an aggregate in application code. Sorting by unpaid amount used to load every managed property id, sort them in the API process, and then slice out the page. The database never saw the ORDER BY, so it could not use an index for it, and the API process held the whole set in memory for every request.

Counting the hard way, one step after paging. The total for the pager ran after the page query, not alongside it, and it repeated the same heavy joins. It also used COUNT(DISTINCT ...) in places where the joins could not multiply rows, which forces a sort or hash for no benefit.

Any one of these is survivable at a few thousand rows. Stacked, at 15,000 rows with search, they produced numbers like 14 and 44 seconds.

What we changed

Scope with a join, not a list. We stopped shipping the full id list into the query. The user’s visibility is expressed as a join, or a semijoin, against a membership table, so the planner reasons about a relation with statistics and an index instead of an opaque array.

-- before: the application resolves 15,000 ids first
SELECT ... FROM properties WHERE id = ANY($1) ORDER BY ... LIMIT 25 OFFSET 975;

-- after: the database resolves visibility itself
SELECT p.* FROM properties p
WHERE EXISTS (
  SELECT 1 FROM user_properties m
  WHERE m.property_id = p.id AND m.user_id = :user
)
ORDER BY ... LIMIT 25 OFFSET 975;

Make each skipped row cheap. The correlated subqueries became a join to a small stats table holding the charge totals per property. The next post in this series is about why that table matters for search, and post three is about how it is built. For this post, what matters is the effect on the query: every row the database skips or returns costs one indexed lookup, not a round of aggregation.

Sort and limit in SQL. Sorting by unpaid amount now happens on the stats table, with an index, inside the database. The API process asks for 25 rows and receives 25 rows.

Count and page together. The count query lost its DISTINCT wherever the join is one to one, and the count and the page now run concurrently with Promise.all rather than one after the other.

Never trust a sort field from the client. Unknown sort fields fall back to a stable, indexed column. The API does not accept arbitrary column names, which keeps both the query plan and the attack surface predictable.

After

These are service-level timings on the same large dataset with the indexes in place, so they exclude the network floor from the earlier table.

CaseBeforeAfter
Page 11318ms58ms
Page 40791ms58ms
Page 100773ms58ms
Search, common term898ms130ms
Search, no match4809ms148ms

The result to look at is the flat line in the middle. Pages 1, 10, 40 and 100 cost the same, because the cost no longer depends on how many rows come before the page. The speedup on page 1 is nice, but the flatness is the actual fix.

A later pass got a warm unpaid-amount sort to roughly one second end to end at both page 1 and page 40. Before, that sort degraded without bound as you paged.

We did not switch to keyset pagination. Offset is still there. The win came from making every skipped row cheap and indexed, which was a much smaller change to the API contract than rewriting every client to carry a cursor.

Two pitfalls

A stats table lies if a write path forgets to update it. Ours is maintained when charges and payments change, with a periodic repair for anything that slipped through. The list path can notice a missing row and backfill it, but that backfill must never run inside the request a user is waiting on. We made the repair non-blocking for interactive sorts. A cold cache turning into a slow page is exactly the failure we were removing.

Faster on page 1 can hide a query that still scans everything. A query that reads the whole table and then applies LIMIT can look fine on page 1 and fall over on page 40, or on a search with no match. If you only time the first page, you are measuring the best case.

What to take from it

Do the filter, sort and page in SQL, on a narrow set of rows. Express scope as a relation the planner can see. Make the work per skipped row so small that the page number stops mattering. Then check the flatness yourself, with a deep page and a search term, before you believe it.

The search numbers in the table above are a separate story with a separate cause, and they are the next post: what to do when the user types a term and the database has no index that can help.

Next in the series: Leading-wildcard search without a sequential scan.