Keyset pagination for large tables
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's order history grows by thousands of rows each day. Page 1000 must open as fast as page 1, and a new order arriving must not push a row from one page onto the next.
Why OFFSET gets slow
OFFSET paging asks the database to skip a number of rows and then take a page: LIMIT 20 OFFSET 400000. The database cannot skip rows for free, so the work grows with the page number.
To show rows 400,001 to 400,020 of 5 lakh orders, the database still walks the first 400,020. Example 1 measures it.
Example 1 · OFFSET 0 vs OFFSET 400000 on 5 lakh orders (MySQL EXPLAIN ANALYZE)
Runs in: MySQL 8.4 with a practice table of 500,000 orders
mysql -u root -p -B -r practice -e "SET cte_max_recursion_depth = 1000000;CREATE TABLE orders ( order_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, customer_id INT NOT NULL, status VARCHAR(10) NOT NULL, ordered_at DATETIME NOT NULL, INDEX idx_orders_ordered_at_id (ordered_at, order_id));INSERT INTO orders (customer_id, status, ordered_at) WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 500000) SELECT 1 + i % 5000, 'DELIVERED', TIMESTAMP('2024-01-01') + INTERVAL (i * 120 + (i * 7919) % 97) SECOND FROM n;EXPLAIN ANALYZE SELECT order_id, ordered_at FROM orders ORDER BY ordered_at DESC, order_id DESC LIMIT 20 OFFSET 0;EXPLAIN ANALYZE SELECT order_id, customer_id, status, ordered_at FROM orders ORDER BY ordered_at DESC, order_id DESC LIMIT 20 OFFSET 400000;"EXPLAIN
-> Limit: 20 row(s) (cost=0.0139 rows=20) (actual time=1.02..1.03 rows=20 loops=1)
-> Covering index scan on orders using idx_orders_ordered_at_id (reverse) (cost=0.0139 rows=20) (actual time=1.02..1.02 rows=20 loops=1)
EXPLAIN
-> Limit/Offset: 20/400000 row(s) (cost=50240 rows=20) (actual time=1007..1007 rows=20 loops=1)
-> Sort: orders.ordered_at DESC, orders.order_id DESC, limit input to 400020 row(s) per chunk (cost=50240 rows=498955) (actual time=947..992 rows=400020 loops=1)
-> Table scan on orders (cost=50240 rows=498955) (actual time=1.46..451 rows=500000 loops=1)What this code does
EXPLAIN ANALYZEruns the query and reports what MySQL really did:actual timein milliseconds (first row..last row) androwsread at each step.- Offset 0: a reverse scan of the index that stops after 20 entries, about 1 ms.
- Offset 400,000: a full table scan of 500,000 rows and a sort of 400,020 of them, about 1 second for the same 20 rows.
MySQL reads and sorts the first 400,020 rows and then throws 400,000 of them away. Page 0 takes about 1 ms and reads 20 index entries. The same 20 rows at offset 400,000 take about 1 second: MySQL scanned all 500,000 rows and sorted 400,020 of them. Your numbers will differ, but the gap grows with the offset on any machine.
Offset paging has a second problem on busy tables. If a new order arrives while a user is on page 1, every row moves down by one, and page 2 shows the last row of page 1 again.
The keyset idea: WHERE (ordered_at, order_id) < (?, ?)
Keyset paging (also called cursor or seek paging) asks for the rows after the last one shown, using that row's sort values, the key, instead of skipping a number of rows. An index lets the database jump straight to the key.
For newest-first orders, the next page is WHERE ordered_at < ? OR (ordered_at = ? AND order_id < ?) with the same ORDER BY and LIMIT 20. Example 2 shows the SQL.
Example 2 · The keyset query, and the row-comparison form that MySQL did not optimise
Runs in: MySQL 8.4 with a practice table of 500,000 orders
mysql -u root -p -B -r practice -e "EXPLAIN ANALYZE SELECT order_id, customer_id, status, ordered_at FROM orders WHERE ordered_at < '2024-05-18 21:22:16' OR (ordered_at = '2024-05-18 21:22:16' AND order_id < 100001) ORDER BY ordered_at DESC, order_id DESC LIMIT 20;EXPLAIN ANALYZE SELECT order_id, customer_id, status, ordered_at FROM orders WHERE (ordered_at, order_id) < ('2024-05-18 21:22:16', 100001) ORDER BY ordered_at DESC, order_id DESC LIMIT 20;"EXPLAIN
-> Limit: 20 row(s) (cost=50240 rows=20) (actual time=12.7..12.7 rows=20 loops=1)
-> Index range scan on orders using idx_orders_ordered_at_id over (ordered_at < '2024-05-18 21:22:16') OR (ordered_at = '2024-05-18 21:22:16' AND order_id < 100001) (reverse), with index condition: ((orders.ordered_at < TIMESTAMP'2024-05-18 21:22:16') or ((orders.ordered_at = TIMESTAMP'2024-05-18 21:22:16') and (orders.order_id < 100001))) (cost=50240 rows=202735) (actual time=12.7..12.7 rows=20 loops=1)
EXPLAIN
-> Limit: 20 row(s) (cost=0.0139 rows=20) (actual time=3799..3799 rows=20 loops=1)
-> Filter: ((orders.ordered_at,orders.order_id) < ('2024-05-18 21:22:16',100001)) (cost=0.0139 rows=20) (actual time=3799..3799 rows=20 loops=1)
-> Index scan on orders using idx_orders_ordered_at_id (reverse) (cost=0.0139 rows=20) (actual time=1.54..3654 rows=400020 loops=1)What this code does
- The key (2024-05-18 21:22:16, 100001) is the last row of the page at offset 400,000. The OR form uses an
Index range scanstarting at that key: about 13 ms for the same depth. - The row comparison returns the same rows, but here MySQL read the index from the top and filtered 400,020 entries: about 3.8 seconds.
- Always check the plan of your keyset query with
EXPLAINon realistic data.
The key of a newest-first order list is (ordered_at, order_id) of the last order shown. With an index on (ordered_at, order_id), MySQL starts reading at the key and stops after 20 entries, wherever in the table the key is. New rows do not shift anything, because the next page is defined by the key, not by a count.
The key must be unique, so it ends with the id: two orders can share a timestamp, but never an id. Write the condition in the expanded OR form on MySQL. The shorter row comparison (ordered_at, order_id) < (?, ?) gives the same rows, but in Example 2 MySQL 9.4 did not use the index range for it and scanned 400,020 entries.
Predict the output
Predict the next page
Pick the right condition and result.
Round 1 of 2
Newest first. The last row shown has ordered_at 10:40 and order_id 12. What must the next page ask for?
Spring Data scrolling: ScrollPosition.keyset() and Window<T>
ScrollPosition is where a scroll query starts: ScrollPosition.keyset() is the beginning, and window.positionAt(i) is the position after row i. The repository method returns a Window<T> with the rows and hasNext().
Spring Data writes the keyset condition for you: pass the position of the last row to the next call. Examples 3 and 4 show it.
Example 3 · src/main/java/com/shoplite/order/OrderRepository.java (page-lab)
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.order;
import org.springframework.data.domain.Page;import org.springframework.data.domain.Pageable;import org.springframework.data.domain.ScrollPosition;import org.springframework.data.domain.Window;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.Query;
public interface OrderRepository extends JpaRepository<Order, Integer> {
// A collection fetch join + paging: see the Pageable, Page and Slice lesson @Query(value = "select o from Order o join fetch o.items", countQuery = "select count(o) from Order o") Page<Order> findAllWithItems(Pageable pageable);
// Keyset scrolling: newest first, id breaks ties, 5 orders per window Window<Order> findFirst5ByOrderByOrderedAtDescIdDesc(ScrollPosition position);
// The same for one customer's order history, 2 per window Window<Order> findFirst2ByCustomerIdOrderByOrderedAtDescIdDesc(Integer customerId, ScrollPosition position);
}(no output: Example 4 uses the keyset methods)
What this code does
Window<Order> findFirst5ByOrderByOrderedAtDescIdDesc(ScrollPosition position): newest first, id as the tiebreaker, 5 rows per window.- The customer version adds
CustomerIdto the method name, so its WHERE combines the customer filter with the keyset condition. findAllWithItemsbelongs to the first lesson of this module and is not part of keyset paging.
Example 4 · lab/OrderFeedDemo.java: scrolling all 16 orders, 5 at a time
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.lab;
import java.time.format.DateTimeFormatter;
import org.springframework.data.domain.ScrollPosition;import org.springframework.data.domain.Window;import org.springframework.stereotype.Component;
import com.shoplite.order.Order;import com.shoplite.order.OrderRepository;
@Component("keyset")class OrderFeedDemo implements LabDemo {
private static final DateTimeFormatter WHEN = DateTimeFormatter.ofPattern("dd MMM HH:mm");
private final OrderRepository orders;
OrderFeedDemo(OrderRepository orders) { this.orders = orders; }
@Override public void run() { ScrollPosition position = ScrollPosition.keyset(); // start at the newest order int screen = 1; Window<Order> window; do { window = orders.findFirst5ByOrderByOrderedAtDescIdDesc(position); System.out.print("Screen " + screen++ + ":"); window.forEach(o -> System.out.print(" #" + o.getId() + " (" + o.getOrderedAt().format(WHEN) + ")")); System.out.println(" hasNext=" + window.hasNext()); if (window.hasNext()) { position = window.positionAt(window.size() - 1); // the keys of the last order shown System.out.println(" next position: " + position); } } while (window.hasNext()); }}$ java -jar target/page-lab-0.1.0.jar --demo=keyset
DEBUG org.hibernate.SQL : select o1_0.order_id,o1_0.customer_id,o1_0.address_id,o1_0.ordered_at,o1_0.status from orders o1_0 order by o1_0.ordered_at desc,o1_0.order_id desc limit ?
Screen 1: #16 (29 Sept 16:30) #15 (27 Sept 09:55) #14 (21 Sept 21:05) #13 (15 Sept 14:15) #12 (10 Sept 10:40) hasNext=true
next position: KeysetScrollPosition [FORWARD, {id=12, orderedAt=2026-09-10T10:40}]
DEBUG org.hibernate.SQL : select o1_0.order_id,o1_0.customer_id,o1_0.address_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.ordered_at<? or o1_0.ordered_at=? and o1_0.order_id<? order by o1_0.ordered_at desc,o1_0.order_id desc limit ?
Screen 2: #11 (04 Sept 18:00) #10 (30 Aug 12:25) #9 (22 Aug 15:50) #8 (15 Aug 20:35) #7 (09 Aug 11:00) hasNext=true
next position: KeysetScrollPosition [FORWARD, {id=7, orderedAt=2026-08-09T11:00}]
DEBUG org.hibernate.SQL : select o1_0.order_id,o1_0.customer_id,o1_0.address_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.ordered_at<? or o1_0.ordered_at=? and o1_0.order_id<? order by o1_0.ordered_at desc,o1_0.order_id desc limit ?
Screen 3: #6 (03 Aug 17:20) #5 (28 Jul 09:30) #4 (21 Jul 22:10) #3 (18 Jul 13:05) #2 (05 Jul 19:45) hasNext=true
next position: KeysetScrollPosition [FORWARD, {id=2, orderedAt=2026-07-05T19:45}]
DEBUG org.hibernate.SQL : select o1_0.order_id,o1_0.customer_id,o1_0.address_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.ordered_at<? or o1_0.ordered_at=? and o1_0.order_id<? order by o1_0.ordered_at desc,o1_0.order_id desc limit ?
Screen 4: #1 (02 Jul 10:12) hasNext=falseWhat this code does
- The first window has no WHERE; every later one has
ordered_at<? or ordered_at=? and order_id<?with the keys of the last order shown, and never an OFFSET. positionAt(window.size() - 1)prints asKeysetScrollPosition [FORWARD, {id=12, orderedAt=2026-09-10T10:40}]: exactly the key of order 12.- No COUNT runs. Spring Data fetched one extra row to set
hasNext(), just like aSlice.
The method name or a Sort gives the order, and findFirst5By... the size. Pass positionAt(...) of the last row to the next call, and Spring Data writes the ordered_at < ? or (ordered_at = ? and order_id < ?) condition itself.
In a REST API the position becomes a cursor: an opaque string the client sends back, such as the Base64 text of 2026-09-10T10:40|12. The client never builds SQL; it just says "after this cursor".
Trade-offs: no page N, a unique key and a matching index
Keyset paging is not a free upgrade: it changes what the screen can offer, and it needs the right index.
-- One index that matches the filter AND the keyset order, for a customer's historyCREATE INDEX idx_orders_customer_ordered_at ON orders (customer_id, ordered_at, order_id);-- Next page of customer 2's orders after the last one shown (2026-08-09 11:00, id 7)SELECT order_id, status, ordered_at FROM ordersWHERE customer_id = 2 AND (ordered_at < '2026-08-09 11:00:00' OR (ordered_at = '2026-08-09 11:00:00' AND order_id < 7))ORDER BY ordered_at DESC, order_id DESCLIMIT 20;- No jumping to page N and usually no total count: it fits "Load more", infinite scroll and exports, not a "1 2 3 ... 57" page bar.
- The sort must end with a unique column (id), and the client may not change the sort in the middle of scrolling.
- It is only fast with an index that matches the filter and the order, like (customer_id, ordered_at, order_id) below.
- Going backwards needs the reverse condition; Spring Data supports it with
ScrollPosition.backward(...).
ShopLite keeps offset paging, because its contract promises page numbers and its lists are small. A high-traffic feed or an export of millions of rows would use keyset.
Next step
Check your understanding
11 quick questions