API latency learning path Level 2 This level · 7 of 7
Medium java backend

OFFSET pagination is slow on page 5,000. Why, and how do you fix it?

The 30 second answer

With OFFSET, the database still reads and throws away all the skipped rows, so a deep page means scanning a huge number of rows just to return a few. The fix is keyset pagination: remember the last sort key and ask for rows after it, with an index on the sort columns. Every page then costs about the same.

Could you say this in an interview?

With OFFSET the database still reads and throws away all skipped rows, so deep pages get slower. I switch to keyset pagination: the client sends the last id and timestamp, and I query 'where key is less than that, order by key, limit 20' with an index on those columns.

Alternate interview scenarios

"Shopify-style incident: third-party apps page through millions of products with page numbers, and unrelated queries start timing out."

Shopify's engineering blog describes exactly this. The post isn't about PostgreSQL specifically, but the mechanics are the same: the PostgreSQL docs say "the rows skipped by an OFFSET clause still have to be computed inside the server". On a test shop with 14 million products, OFFSET pages got slower with depth; tests at an offset of 1,000,000 and above "consistently timed out". Worse, many deep-offset requests "pile up faster than they can be executed", so "unrelated, quick queries" time out waiting for database connections, including for other shops on the same database. Their fix was relative cursors: remember the last record and continue from it, which they measured as over 400 times faster at an offset of 100,000. For a sort on a non-unique column, the cursor carries the sort value plus the ID, and the index must match:

CREATE INDEX products_title_id ON products (title, id);

SELECT id, title FROM products
WHERE (title, id) > (:last_title, :last_id)   -- row-value comparison
ORDER BY title, id
LIMIT 50;

The post notes that without a suitable index on title and ID, this "could be even slower than using a page number". The cost is no jumping to an arbitrary page, so APIs return an opaque next-page cursor. Elasticsearch has the same pattern as search_after.


Sources (6)
  1. PostgreSQL 17 docs: LIMIT and OFFSETpostgresql.org
  2. Use The Index, Luke: Paging through resultsuse-the-index-luke.com
  3. Spring Data Commons source: PageableHandlerMethodArgumentResolverSupport (max page size and boundary handling)github.com
  4. Spring Boot application properties: spring.data.web.pageable.max-page-sizedocs.spring.io
  5. Shopify Engineering: Pagination with relative cursorsshopify.engineering
  6. PostgreSQL docs: Row constructor comparisonpostgresql.org
Previous
Next