Pagination for very large lists
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's order list was fast with 50 orders. Now one customer has thousands and the admin export has millions, and GET /orders times out. How do you return a long list safely?
Your turn: design the order list
GET /api/v1/orders returns every order. Meena has 4,000 orders and the admin export covers 2 million.
Before you read on, think about these questions and write your design in a few lines.
- What breaks first when the list has 2 million rows, and for whom?
- What would the client send to ask for "a little at a time", and what maximum would the server enforce?
- How can the database find "the next 20 rows" without counting from the start every time?
Why returning all rows fails
Pagination means returning a long list in small pieces, called pages, instead of all at once. Every list endpoint returns one page and a way to ask for the next one.
Count what one unpaged response costs when ShopLite has 2 million orders of about 300 bytes of JSON each.
Example 1 · What one unpaged response of 2 million orders costs
public class AllRowsCost { public static void main(String[] args) { long orders = 2_000_000; // GET /orders with no paging, for an admin screen int bytesPerOrderJson = 300; // id, customer, status, time, total as JSON double phoneMbps = 10; // a decent 4G connection
double megabytes = orders * bytesPerOrderJson / 1_000_000.0; double seconds = megabytes * 8 / phoneMbps;
System.out.printf("Response size: %.0f MB%n", megabytes); System.out.printf("Download on 4G: %.0f seconds (about %.0f minutes)%n", seconds, seconds / 60); System.out.println("Server memory: the whole list is built before the first byte is sent");
int pageSize = 20; System.out.printf("One page of %d: %.1f KB%n", pageSize, pageSize * bytesPerOrderJson / 1000.0); }}Response size: 600 MB Download on 4G: 480 seconds (about 8 minutes) Server memory: the whole list is built before the first byte is sent One page of 20: 6.0 KB
What this code does
- 2 million orders at about 300 bytes of JSON each is 600 MB, which takes about 8 minutes on a 10 Mbps phone connection, if nothing times out first.
- One page of 20 is 6 KB. Paging is not an optimisation here; it is the difference between working and failing.
An endpoint that returns every row works in testing with 50 orders and fails in production with 2 million. The server builds the whole list in memory, the database reads every row, the response takes minutes to download on a phone, and some proxy or client gives up with a timeout first.
The fix is to never return an unbounded list. Every list endpoint returns one page and a way to ask for the next, and the server decides the largest page it will ever send.
Offset/limit pagination and deep pages
Offset pagination asks for a page number and a size, and the server runs LIMIT size OFFSET page x size. It is simple and lets users jump to any page, but deep pages are slow.
Offset pagination is what ShopLite's v1 contract uses: page from 0, size 20 by default, 100 at most. The query below asks for page 50,000.
-- page 50,000 of 20: reads 1,000,020 rows, returns 20SELECT id, status, total FROM ordersORDER BY idLIMIT 20 OFFSET 1000000;Example 2 · Rows read: OFFSET vs keyset as pages get deeper
public class OffsetCostDemo { // Simplified model: with OFFSET the database walks past every skipped row; // with a keyset (WHERE id > ?) it jumps straight to the start through the index. static long offsetRowsRead(long page, int size) { long offset = page * size; return offset + size; }
static long keysetRowsRead(int size) { return size; }
public static void main(String[] args) { int size = 20; long[] pages = {0, 100, 10_000, 50_000}; System.out.println("page OFFSET rows read keyset rows read"); for (long page : pages) { System.out.printf("%-9d %16d %16d%n", page, offsetRowsRead(page, size), keysetRowsRead(size)); } }}page OFFSET rows read keyset rows read 0 20 20 100 2020 20 10000 200020 20 50000 1000020 20
What this code does
- This is a simplified model: with OFFSET the database walks past every skipped row, so page 50,000 reads over a million rows to return 20.
- With a keyset condition and an index, every page reads about 20 rows, however deep it is.
Offset pages are simple and let users jump to page 7. The catch is deep pages: OFFSET 1000000 does not jump, because the database reads a million rows in order and throws them away before it returns 20.
Each page is slower than the one before. That is fine for a product list people rarely scroll far, and bad for an export job or an infinite feed.
Fix the error
Fix the last page
This page method crashes past the end of the list. Pick the fix.
Page 2 of 7 ids, with 3 per page, crashes. Which line fixes it?
Error
Exception in thread "main" java.lang.IndexOutOfBoundsException: toIndex = 9
Cursor (keyset) pagination
Cursor (keyset) pagination remembers where the last page ended instead of counting rows. The client sends the last id it saw, and the server runs WHERE id > :lastId ORDER BY id LIMIT size.
Cursor pagination sends the last id the client saw, and the query asks for the rows after it. Here is page 50,000 again, this time with a cursor.
-- every page reads about 20 rowsSELECT id, status, total FROM ordersWHERE id > 1000000ORDER BY idLIMIT 20;Example 3 · Cursor paging over a sorted map
import java.util.ArrayList;import java.util.List;import java.util.NavigableMap;import java.util.TreeMap;
public class CursorPagination { static TreeMap<Integer, String> orders = new TreeMap<>(); // sorted by id, like an index
// Same idea as: SELECT ... WHERE id > :afterId ORDER BY id LIMIT :size static List<Integer> page(int afterId, int size) { NavigableMap<Integer, String> rest = orders.tailMap(afterId, false); List<Integer> ids = new ArrayList<>(); for (int id : rest.keySet()) { if (ids.size() == size) { break; } ids.add(id); } return ids; }
public static void main(String[] args) { for (int id = 501; id <= 511; id++) { orders.put(id, "order " + id); }
int cursor = 0; // start before the first id int pageNumber = 1; while (true) { List<Integer> ids = page(cursor, 4); if (ids.isEmpty()) { break; } System.out.println("page " + pageNumber++ + " (after " + cursor + "): " + ids); cursor = ids.get(ids.size() - 1); } }}page 1 (after 0): [501, 502, 503, 504] page 2 (after 504): [505, 506, 507, 508] page 3 (after 508): [509, 510, 511]
What this code does
TreeMap.tailMap(afterId, false)gives the entries after the cursor, likeWHERE id > :afterIdon an index; the loop stops aftersizeitems.- The last id of each page becomes the next cursor. An empty page means the end of the list.
With an index on id, the database jumps straight to lastId and reads only 20 rows, so page 50,000 is as fast as page 1.
The cost: you cannot jump to "page 7", only go to the next page. The sort must be on a unique, indexed key, or on a key plus id as a tie-breaker, a unique column that makes every position in the order different.
id to the sort and to the cursor.Simulation: the item shifted between pages
Watch a live newest-first list while a new order arrives between page 1 and page 2, once with offset pages and once with a cursor.
Example 4 · Offset repeats an item when a new order arrives; the cursor does not
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
public class ShiftBugDemo { static List<Integer> orders = new ArrayList<>(); // order ids, newest first
static List<Integer> byOffset(int page, int size) { int from = Math.min(page * size, orders.size()); int to = Math.min(from + size, orders.size()); return orders.subList(from, to); }
// newest first: WHERE id < :beforeId ORDER BY id DESC LIMIT :size static List<Integer> byCursor(int beforeId, int size) { List<Integer> result = new ArrayList<>(); for (int id : orders) { if (id < beforeId && result.size() < size) { result.add(id); } } return result; }
static void newOrder(int id) { orders.add(id); orders.sort(Comparator.reverseOrder()); }
public static void main(String[] args) { for (int id = 501; id <= 508; id++) { orders.add(id); } orders.sort(Comparator.reverseOrder());
List<Integer> offsetPage1 = new ArrayList<>(byOffset(0, 4)); List<Integer> cursorPage1 = byCursor(Integer.MAX_VALUE, 4); System.out.println("page 1 (both): " + offsetPage1);
newOrder(509); // someone orders while Meena reads System.out.println("new order 509 arrives");
System.out.println("offset page 2: " + byOffset(1, 4) + " <- 505 shown again"); int lastSeen = cursorPage1.get(cursorPage1.size() - 1); System.out.println("cursor page 2: " + byCursor(lastSeen, 4) + " <- continues after 505"); }}page 1 (both): [508, 507, 506, 505] new order 509 arrives offset page 2: [505, 504, 503, 502] <- 505 shown again cursor page 2: [504, 503, 502, 501] <- continues after 505
What this code does
- Page 1 is the four newest orders. Order 509 then arrives at the top, shifting every row down by one.
- Offset page 2 (rows 5 to 8) now starts with 505, which the user already saw. The cursor page asks for ids below 505 and continues correctly with 504.
Offset pages are counted from the top of the list at the moment of each request. If a new order is added at the top, every row moves down one place, so page 2 starts with the last item of page 1 again. A delete does the opposite and an item is skipped without anyone noticing.
A cursor does not have this problem: page 2 is "orders older than the last one I saw", and that set does not change when new orders arrive at the top.
Predict the output
A new order arrives
The feed is newest first, 3 per page. Predict page 2.
Round 1 of 2
Offset page 2 after order 509 arrives. What is printed?
Response shape: items, nextCursor, hasMore
A cursor is an opaque token that marks where the last page ended. The client sends it back unchanged to get the next page, so the server is free to change what is inside it later.
A cursor-paged response has three parts: items (this page), nextCursor (what to send for the next page, or null at the end) and hasMore.
{ "items": [ { "id": 101, "status": "PLACED", "total": 1299.00 }, ... ], "nextCursor": "aWQ6MTIw", "hasMore": true}Example 5 · An opaque cursor, hasMore and a capped page size
import java.nio.charset.StandardCharsets;import java.util.ArrayList;import java.util.Base64;import java.util.List;
record Page(List<Integer> items, String nextCursor, boolean hasMore) {}
public class PageResponseDemo { static final int DEFAULT_SIZE = 20; static final int MAX_SIZE = 100; static List<Integer> orderIds = new ArrayList<>(); // sorted ascending
// The cursor is opaque to clients: they pass it back, never build it themselves static String encode(int lastId) { return Base64.getUrlEncoder().withoutPadding() .encodeToString(("id:" + lastId).getBytes(StandardCharsets.UTF_8)); }
static int decode(String cursor) { String text = new String(Base64.getUrlDecoder().decode(cursor), StandardCharsets.UTF_8); return Integer.parseInt(text.substring(3)); }
static Page list(String cursor, Integer requestedSize) { int size = requestedSize == null ? DEFAULT_SIZE : Math.min(requestedSize, MAX_SIZE); int after = cursor == null ? 0 : decode(cursor); List<Integer> items = new ArrayList<>(); boolean more = false; for (int id : orderIds) { if (id <= after) { continue; } if (items.size() == size) { more = true; // fetched size + 1 rows: one extra tells us there is more break; } items.add(id); } String next = more ? encode(items.get(items.size() - 1)) : null; return new Page(items, next, more); }
public static void main(String[] args) { for (int id = 1; id <= 210; id++) { orderIds.add(id); } Page p1 = list(null, 5000); System.out.println("asked 5000, got " + p1.items().size() + ", hasMore=" + p1.hasMore() + ", nextCursor=" + p1.nextCursor()); Page p2 = list(p1.nextCursor(), null); System.out.println("next page: first=" + p2.items().get(0) + ", count=" + p2.items().size() + ", nextCursor=" + p2.nextCursor()); Page last = list(p2.nextCursor(), 100); System.out.println("last page: " + last.items().get(0) + ".." + last.items().get(last.items().size() - 1) + ", hasMore=" + last.hasMore() + ", nextCursor=" + last.nextCursor()); }}asked 5000, got 100, hasMore=true, nextCursor=aWQ6MTAw next page: first=101, count=20, nextCursor=aWQ6MTIw last page: 121..210, hasMore=false, nextCursor=null
What this code does
- A request for 5,000 items gets 100, the server maximum; a missing size gets the default of 20. The cursor is
id:<last>encoded in Base64 so clients treat it as an opaque token. - The loop notices one row beyond the page, which sets
hasMore; on the last pagehasMoreisfalseandnextCursorisnull.
The cursor is opaque: an encoded string the client passes back unchanged. The server also caps the page size. A missing size gets the default (20), a huge size is reduced to the maximum (100), and a size below 1 is a 400.
A neat trick for hasMore: fetch size + 1 rows. If the extra row exists, there is another page, and no separate COUNT query is needed.
Order of execution
Order one cursor page
Put the server steps for one cursor page in order.
Next step
Check your understanding
11 quick questions