Video in progress
When an inter-service API returns a large list, what is the difference between offset and cursor (keyset) pagination, and which do you choose?
Offset (?page=500&size=50) is simple, but on deep pages the DB still reads the skipped rows, and if the data changes, rows get repeated or dropped. A cursor continues from the last seen key, which is fast and stable. When another service has to read all the data, I pick the cursor.
📖 Answer
The situation: every night report-service pulls 2 million orders a day from order-service. With offset:
SELECT * FROM orders ORDER BY id LIMIT 100 OFFSET 1500000;
The DB reads 1.5 million rows, throws them away and then returns 100. The last pages are hundreds of times slower than the first. On top of that, if a new order is added or one is deleted during the read, the pages shift, and some order arrives twice or never.
Keyset (cursor):
SELECT * FROM orders
WHERE (created_at, id) > (:lastCreatedAt, :lastId)
ORDER BY created_at, id
LIMIT 100;
With a (created_at, id) index, every page is equally fast. The client isn't given the keys openly; it gets an opaque cursor:
{
"items": [ ... ],
"nextCursor": "eyJjIjoiMjAyNi0xMS0wM1QxMDoxNSIsImkiOjgxMn0"
}
Inside the cursor are the created_at and id, base64-encoded. The client sends it back unchanged on the next request. That way, even if you later change the sort key, clients don't break.
Spring Data 3.1+ has ScrollPosition and Window<T> for this:
Window<Order> findFirst100ByOrderByCreatedAtAscIdAsc(ScrollPosition position);
When offset is fine: admin tables a person looks at, where you need to "jump to page 5", or when the data is small. The downside of a cursor is that you can't jump to an arbitrary page and it doesn't give a total count.
The sort key must be unique: if it is only created_at, one of two orders in the same millisecond can be dropped, so id is added at the end.
Sign up to mark studied questions and save your progress.