Video in progress

Staff 🌱 Spring

Pagination on a very large table is slow. How do you compare offset and keyset (seek) pagination, and how do you design the API?

Offset gets slow on deep pages because the database still reads all the skipped rows, and when data changes, rows get duplicated or dropped. Keyset fetches what comes after the last seen key using an index, so each page is fast and stable, but you can't jump to an arbitrary page. In the API I return a cursor (an opaque token).

📖 Answer

Offset:

select * from orders order by created_at desc, id desc offset 500000 limit 20;

The database reads 500,020 rows and throws away 500,000 of them.

Keyset:

select * from orders
where (created_at, id) < (:lastCreatedAt, :lastId)
order by created_at desc, id desc
limit 20;

With an index on (created_at, id) every page is equally fast. id is added so that rows with the same timestamp have a well-defined order.

The API:

{
  "items": [ ... ],
  "nextCursor": "eyJjIjoiMjAyNi0xMC0zMVQxMjowMDowMFoiLCJpIjo5ODc2fQ"
}

The cursor holds the last element's keys, in base64 (signed if possible). The client doesn't know what's inside, so even if you change the ordering later, the contract isn't broken.

In Spring Data 3.1+, ScrollPosition and Window<T> support keyset:

Window<Order> findFirst20ByStatusOrderByCreatedAtDescIdDesc(Status s, ScrollPosition pos);

Where offset remains: small tables, and an admin panel where you need "jump to page N" or a total count.

On a big table, don't compute count(*) on every request. An approximate number or showing "1000+" is usually enough.