Part 03 · The Language of the Web
Pagination, Filtering and Sorting
Returning a million rows a page at a time, with offsets, cursors and stable sorts.
⏱ 1 hours · Station 38 of 153
The endpoint that returned everything
GET /orders worked perfectly in development, where there were 40 orders. A year later there are 3 million. One morning an admin opens the orders page and the API tries to load every row, turn it into JSON and send 900 MB down the wire. The database spikes, the server runs out of memory, and the page never loads.
The fix everyone reaches for is "add ?page=2". That works, until a feed shows the same post twice when someone posts while you scroll, or page 50,000 takes seconds while page 1 takes milliseconds.
Pagination means returning a big collection a small, predictable piece at a time. Doing it well needs three things to agree: how you filter (which rows), how you sort (in what order, without ties), and how you remember where you stopped (an offset or a cursor). This lesson builds all three and shows exactly where the popular shortcut breaks.
The problem: big lists, moving data
| Approach | Request | Good at | Breaks when |
|---|---|---|---|
| No pagination | GET /orders | tiny tables | the table grows: memory, time, bandwidth |
| Offset / page number | ?limit=20&offset=40 or ?page=3 | jumping to page N, showing "page 3 of 10" | rows are added or deleted between pages; deep pages get slow |
| Cursor (keyset) | ?limit=20&after=eyJpZCI6ODl9 | infinite scroll, sync, big tables, changing data | you need "jump to page 37" |
The data underneath keeps changing while a user pages through it. Any scheme that says "skip the first N rows" depends on those N rows staying exactly the same.
Think of reading a long list with a bookmark
You're reading a 500-page register at the land office, 20 entries at a time.
- Offset: you remember "I've read 40 entries; skip 40 next time." If a clerk adds a new entry at the top while you're away, every entry shifts down by one. Skipping 40 now lands you one entry early, and you read one again. If an entry is removed, you skip one you never saw.
- Cursor: you remember "the last entry I read was #8,412." Next time you start right after #8,412, wherever it has moved to. New or removed entries elsewhere don't matter.
Where the analogy stops working. A bookmark is free to use. In a database, "skip 40" isn't free: the database still has to walk past those 40 rows to throw them away. With 900,000 rows to skip, that walk is the whole cost of the query.
The building blocks
- Always have a limit. Every collection endpoint returns at most
limititems, with a sensible default (20) and a hard maximum (100). Never let a client ask for everything. - Offset paging:
LIMIT 20 OFFSET 40. Simple, supports jumping to any page, and fine for small or slow-changing data. But the database reads and discards alloffsetrows, so deep pages get slower in proportion, and inserts or deletes between requests cause repeats or gaps. - Cursor (keyset) paging: instead of a count, the client sends the sort key of the last row it saw. The query becomes
WHERE id < 8 ORDER BY id DESC LIMIT 20. With an index onid, the database jumps straight there. Cost stays the same on page 1 and page 50,000. - The sort must be total. If many rows share the same sort value (lots of products at 300 taka), the order between them isn't defined, and pages can repeat or skip them. Add a unique tie-breaker:
ORDER BY price, id. - The cursor must hold the full sort key. Sorting by
(price, id)means the cursor is(300, 3), and the next page isWHERE price > 300 OR (price = 300 AND id > 3), or in PostgreSQL simplyWHERE (price, id) > (300, 3). - Make cursors opaque. Encode the cursor (for example base64 of
{"price":300,"id":3}) and tell clients to pass it back unchanged. Then you can change what's inside later without breaking anyone. Sign it if clients mustn't tamper with it. - Filtering and sorting are query parameters on the collection.
GET /products?max_price=500&sort=price&limit=20. Allow-list which fields can be filtered and sorted, because each one usually needs an index to be fast. - Return the way forward. The response includes the items plus
next_cursor(or a fullnextURL, or aLink: <...>; rel="next"header). Nonextmeans the end. Total counts are expensive on big tables; return them only if they're really needed, or estimate.
A feed is sorted by created_at DESC with cursor paging, and the cursor is just the created_at of the last post. 50 posts were imported in one batch with the exact same created_at. A user's page ends in the middle of that batch. What happens on the next page?
Behind the scenes: one cursor page
GET /products?max_price=500&sort=price&limit=2&after=MzAwLDM
Step 1/5 The client sends back the cursor
It got after=MzAwLDM in the previous response and passes it back unchanged. It doesn't know or care what's inside.
- cursor
- MzAwLDM
The picture to keep in your head
A paginated list is a sorted line with a bookmark.
- Filter decides who's in the line.
- Sort decides the order, and needs a unique tie-breaker so the order never wobbles.
- The bookmark is either a count (offset: simple, jumpable, fragile) or the last position seen (cursor: stable and fast, but no jumping).
- The page is the next
limititems after the bookmark, plus a new bookmark.
Try it: will this pagination hold up?
Solid or shaky?
?page=7&per_page=20
Code from first principles
Posts sorted newest first, read three at a time. Each scenario reads page 1, then changes the table (a new post arrives, or post 9 is deleted), then reads page 2, once with an offset and once with a cursor. A verdict checks what the client saw against the rows it should have seen. The last part filters products by price, sorts by price, and pages with a cursor, once with (price, id) and once with price alone.
package main
import (
"fmt"
"slices"
"strings"
)
func list(xs []string) string { return "[" + strings.Join(xs, " ") + "]" }
func names(ids []int) []string {
out := []string{}
for _, id := range ids {
out = append(out, fmt.Sprint(id))
}
return out
}
// Posts, newest first. Offset paging: skip N rows. Cursor paging: rows older than the last one seen.
func offsetPage(table []int, offset, limit int) []int {
return table[min(offset, len(table)):min(offset+limit, len(table))]
}
func cursorPage(table []int, after, limit int) []int {
out := []int{}
for _, id := range table {
if (after == 0 || id < after) && len(out) < limit {
out = append(out, id)
}
}
return out
}
// verdict compares what the client saw with the rows it should have seen (in order).
func verdict(base []string, shown []string) string {
count := map[string]int{}
repeated, skipped := []string{}, []string{}
last := -1
for _, s := range shown {
if count[s]++; count[s] == 2 {
repeated = append(repeated, s)
}
last = max(last, slices.Index(base, s))
}
for _, b := range base[:last+1] {
if count[b] == 0 {
skipped = append(skipped, b)
}
}
switch {
case len(repeated) > 0:
return "repeated " + list(repeated)
case len(skipped) > 0:
return "skipped " + list(skipped)
}
return "ok"
}
func scenario(kind, change string) {
table := []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
base := names(table)
var p1, p2 []int
if kind == "offset" {
p1 = offsetPage(table, 0, 3)
} else {
p1 = cursorPage(table, 0, 3)
}
p1 = slices.Clone(p1)
if change == "row 11 added" { // someone posts while the client reads page 1
table = append([]int{11}, table...)
} else { // someone deletes post 9
table = slices.DeleteFunc(table, func(id int) bool { return id == 9 })
base = slices.DeleteFunc(base, func(s string) bool { return s == "9" })
}
next := ""
if kind == "offset" {
p2 = offsetPage(table, 3, 3)
} else {
next = fmt.Sprintf(" next=%d", p1[len(p1)-1])
p2 = cursorPage(table, p1[len(p1)-1], 3)
}
shown := append(names(p1), names(p2)...)
fmt.Printf("%-6s %-14s page 1 %s%s, page 2 %s -> %s\n", kind, change+":", list(names(p1)), next, list(names(p2)), verdict(base, shown))
}
type product struct{ id, price int }
func label(p product) string { return fmt.Sprintf("%d:%d", p.id, p.price) }
// Filter and sort, then page with a cursor. With byID the cursor is (price, id); without it, price only.
func productPages(byID bool) string {
all := []product{{1, 700}, {2, 100}, {3, 300}, {4, 300}, {5, 450}, {6, 300}, {7, 500}}
match := []product{}
for _, p := range all {
if p.price <= 500 {
match = append(match, p)
}
}
slices.SortFunc(match, func(a, b product) int { // ORDER BY price, id
if a.price != b.price {
return a.price - b.price
}
return a.id - b.id
})
base := []string{}
for _, p := range match {
base = append(base, label(p))
}
pages, shown := []string{}, []string{}
var cur *product
for {
page := []string{}
var last product
for _, p := range match {
after := cur == nil || p.price > cur.price || (byID && p.price == cur.price && p.id > cur.id)
if after && len(page) < 2 {
page = append(page, label(p))
last = p
}
}
if len(page) == 0 {
pages = append(pages, "[] end")
break
}
shown = append(shown, page...)
next := fmt.Sprintf("next=%d", last.price)
if byID {
next = fmt.Sprintf("next=%d,%d", last.price, last.id)
}
pages = append(pages, list(page)+" "+next)
cur = &last
}
return strings.Join(pages, " | ") + " -> " + verdict(base, shown)
}
func main() {
scenario("offset", "row 11 added")
scenario("cursor", "row 11 added")
scenario("offset", "row 9 deleted")
scenario("cursor", "row 9 deleted")
fmt.Println("price<=500, sort=price,id, 2 per page:")
fmt.Println(" cursor (price,id): " + productPages(true))
fmt.Println(" cursor (price): " + productPages(false))
}const list = (xs) => "[" + xs.join(" ") + "]";
const names = (ids) => ids.map(String);
// Posts, newest first. Offset paging: skip N rows. Cursor paging: rows older than the last one seen.
const offsetPage = (table, offset, limit) => table.slice(offset, offset + limit);
const cursorPage = (table, after, limit) => table.filter((id) => after === 0 || id < after).slice(0, limit);
// verdict compares what the client saw with the rows it should have seen (in order).
function verdict(base, shown) {
const count = new Map();
const repeated = [], skipped = [];
let last = -1;
for (const s of shown) {
count.set(s, (count.get(s) || 0) + 1);
if (count.get(s) === 2) repeated.push(s);
last = Math.max(last, base.indexOf(s));
}
for (const b of base.slice(0, last + 1)) if (!count.has(b)) skipped.push(b);
if (repeated.length) return "repeated " + list(repeated);
if (skipped.length) return "skipped " + list(skipped);
return "ok";
}
function scenario(kind, change) {
let table = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
let base = names(table);
const p1 = kind === "offset" ? offsetPage(table, 0, 3) : cursorPage(table, 0, 3);
if (change === "row 11 added") { // someone posts while the client reads page 1
table = [11, ...table];
} else { // someone deletes post 9
table = table.filter((id) => id !== 9);
base = base.filter((s) => s !== "9");
}
let next = "", p2;
if (kind === "offset") {
p2 = offsetPage(table, 3, 3);
} else {
next = ` next=${p1.at(-1)}`;
p2 = cursorPage(table, p1.at(-1), 3);
}
const shown = [...names(p1), ...names(p2)];
console.log(`${kind.padEnd(6)} ${(change + ":").padEnd(14)} page 1 ${list(names(p1))}${next}, page 2 ${list(names(p2))} -> ${verdict(base, shown)}`);
}
const label = (p) => `${p.id}:${p.price}`;
// Filter and sort, then page with a cursor. With byID the cursor is (price, id); without it, price only.
function productPages(byID) {
const all = [[1, 700], [2, 100], [3, 300], [4, 300], [5, 450], [6, 300], [7, 500]].map(([id, price]) => ({ id, price }));
const match = all.filter((p) => p.price <= 500);
match.sort((a, b) => a.price - b.price || a.id - b.id); // ORDER BY price, id
const base = match.map(label);
const pages = [], shown = [];
let cur = null;
for (;;) {
const page = [];
let last = null;
for (const p of match) {
const after = cur === null || p.price > cur.price || (byID && p.price === cur.price && p.id > cur.id);
if (after && page.length < 2) {
page.push(label(p));
last = p;
}
}
if (page.length === 0) {
pages.push("[] end");
break;
}
shown.push(...page);
const next = byID ? `next=${last.price},${last.id}` : `next=${last.price}`;
pages.push(list(page) + " " + next);
cur = last;
}
return pages.join(" | ") + " -> " + verdict(base, shown);
}
scenario("offset", "row 11 added");
scenario("cursor", "row 11 added");
scenario("offset", "row 9 deleted");
scenario("cursor", "row 9 deleted");
console.log("price<=500, sort=price,id, 2 per page:");
console.log(" cursor (price,id): " + productPages(true));
console.log(" cursor (price): " + productPages(false));use std::collections::HashMap;
fn list(xs: &[String]) -> String {
format!("[{}]", xs.join(" "))
}
fn names(ids: &[i32]) -> Vec<String> {
ids.iter().map(|i| i.to_string()).collect()
}
// Posts, newest first. Offset paging: skip N rows. Cursor paging: rows older than the last one seen.
fn offset_page(table: &[i32], offset: usize, limit: usize) -> Vec<i32> {
table.iter().skip(offset).take(limit).cloned().collect()
}
fn cursor_page(table: &[i32], after: i32, limit: usize) -> Vec<i32> {
table.iter().filter(|&&id| after == 0 || id < after).take(limit).cloned().collect()
}
// verdict compares what the client saw with the rows it should have seen (in order).
fn verdict(base: &[String], shown: &[String]) -> String {
let mut count: HashMap<&String, i32> = HashMap::new();
let mut repeated = vec![];
let mut last: i64 = -1;
for s in shown {
let c = count.entry(s).or_insert(0);
*c += 1;
if *c == 2 {
repeated.push(s.clone());
}
if let Some(i) = base.iter().position(|b| b == s) {
last = last.max(i as i64);
}
}
let skipped: Vec<String> = base.iter().take((last + 1) as usize).filter(|b| !count.contains_key(b)).cloned().collect();
if !repeated.is_empty() {
return format!("repeated {}", list(&repeated));
}
if !skipped.is_empty() {
return format!("skipped {}", list(&skipped));
}
"ok".to_string()
}
fn scenario(kind: &str, change: &str) {
let mut table = vec![10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
let mut base = names(&table);
let p1 = if kind == "offset" { offset_page(&table, 0, 3) } else { cursor_page(&table, 0, 3) };
if change == "row 11 added" {
// someone posts while the client reads page 1
table.insert(0, 11);
} else {
// someone deletes post 9
table.retain(|&id| id != 9);
base.retain(|s| s != "9");
}
let mut next = String::new();
let p2 = if kind == "offset" {
offset_page(&table, 3, 3)
} else {
let last = *p1.last().unwrap();
next = format!(" next={}", last);
cursor_page(&table, last, 3)
};
let mut shown = names(&p1);
shown.extend(names(&p2));
println!("{:<6} {:<14} page 1 {}{}, page 2 {} -> {}", kind, format!("{}:", change), list(&names(&p1)), next, list(&names(&p2)), verdict(&base, &shown));
}
#[derive(Clone, Copy)]
struct Product {
id: i32,
price: i32,
}
fn label(p: &Product) -> String {
format!("{}:{}", p.id, p.price)
}
// Filter and sort, then page with a cursor. With by_id the cursor is (price, id); without it, price only.
fn product_pages(by_id: bool) -> String {
let all = [(1, 700), (2, 100), (3, 300), (4, 300), (5, 450), (6, 300), (7, 500)];
let mut matched: Vec<Product> = all.iter().map(|&(id, price)| Product { id, price }).filter(|p| p.price <= 500).collect();
matched.sort_by_key(|p| (p.price, p.id)); // ORDER BY price, id
let base: Vec<String> = matched.iter().map(label).collect();
let mut pages = vec![];
let mut shown = vec![];
let mut cur: Option<Product> = None;
loop {
let mut page = vec![];
let mut last = None;
for p in &matched {
let after = match cur {
None => true,
Some(c) => p.price > c.price || (by_id && p.price == c.price && p.id > c.id),
};
if after && page.len() < 2 {
page.push(label(p));
last = Some(*p);
}
}
if page.is_empty() {
pages.push("[] end".to_string());
break;
}
shown.extend(page.clone());
let l = last.unwrap();
let next = if by_id { format!("next={},{}", l.price, l.id) } else { format!("next={}", l.price) };
pages.push(format!("{} {}", list(&page), next));
cur = last;
}
format!("{} -> {}", pages.join(" | "), verdict(&base, &shown))
}
fn main() {
scenario("offset", "row 11 added");
scenario("cursor", "row 11 added");
scenario("offset", "row 9 deleted");
scenario("cursor", "row 9 deleted");
println!("price<=500, sort=price,id, 2 per page:");
println!(" cursor (price,id): {}", product_pages(true));
println!(" cursor (price): {}", product_pages(false));
}def lst(xs):
return "[" + " ".join(xs) + "]"
def names(ids):
return [str(i) for i in ids]
# Posts, newest first. Offset paging: skip N rows. Cursor paging: rows older than the last one seen.
def offset_page(table, offset, limit):
return table[offset:offset + limit]
def cursor_page(table, after, limit):
return [i for i in table if after == 0 or i < after][:limit]
def verdict(base, shown):
"""Compare what the client saw with the rows it should have seen (in order)."""
count = {}
repeated, skipped = [], []
last = -1
for s in shown:
count[s] = count.get(s, 0) + 1
if count[s] == 2:
repeated.append(s)
last = max(last, base.index(s) if s in base else -1)
skipped = [b for b in base[: last + 1] if b not in count]
if repeated:
return "repeated " + lst(repeated)
if skipped:
return "skipped " + lst(skipped)
return "ok"
def scenario(kind, change):
table = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
base = names(table)
p1 = offset_page(table, 0, 3) if kind == "offset" else cursor_page(table, 0, 3)
if change == "row 11 added": # someone posts while the client reads page 1
table = [11] + table
else: # someone deletes post 9
table = [i for i in table if i != 9]
base = [s for s in base if s != "9"]
nxt = ""
if kind == "offset":
p2 = offset_page(table, 3, 3)
else:
nxt = f" next={p1[-1]}"
p2 = cursor_page(table, p1[-1], 3)
shown = names(p1) + names(p2)
print(f"{kind:<6} {change + ':':<14} page 1 {lst(names(p1))}{nxt}, page 2 {lst(names(p2))} -> {verdict(base, shown)}")
def label(p):
return f"{p[0]}:{p[1]}"
def product_pages(by_id):
"""Filter and sort, then page with a cursor. With by_id the cursor is (price, id); without it, price only."""
all_products = [(1, 700), (2, 100), (3, 300), (4, 300), (5, 450), (6, 300), (7, 500)]
match = sorted((p for p in all_products if p[1] <= 500), key=lambda p: (p[1], p[0])) # ORDER BY price, id
base = [label(p) for p in match]
pages, shown = [], []
cur = None
while True:
page, last = [], None
for p in match:
after = cur is None or p[1] > cur[1] or (by_id and p[1] == cur[1] and p[0] > cur[0])
if after and len(page) < 2:
page.append(label(p))
last = p
if not page:
pages.append("[] end")
break
shown += page
nxt = f"next={last[1]},{last[0]}" if by_id else f"next={last[1]}"
pages.append(lst(page) + " " + nxt)
cur = last
return " | ".join(pages) + " -> " + verdict(base, shown)
scenario("offset", "row 11 added")
scenario("cursor", "row 11 added")
scenario("offset", "row 9 deleted")
scenario("cursor", "row 9 deleted")
print("price<=500, sort=price,id, 2 per page:")
print(" cursor (price,id): " + product_pages(True))
print(" cursor (price): " + product_pages(False))import java.util.*;
public class Main {
static String list(List<String> xs) { return "[" + String.join(" ", xs) + "]"; }
static List<String> names(List<Integer> ids) {
List<String> out = new ArrayList<>();
for (int id : ids) out.add(String.valueOf(id));
return out;
}
// Posts, newest first. Offset paging: skip N rows. Cursor paging: rows older than the last one seen.
static List<Integer> offsetPage(List<Integer> table, int offset, int limit) {
return new ArrayList<>(table.subList(Math.min(offset, table.size()), Math.min(offset + limit, table.size())));
}
static List<Integer> cursorPage(List<Integer> table, int after, int limit) {
List<Integer> out = new ArrayList<>();
for (int id : table) if ((after == 0 || id < after) && out.size() < limit) out.add(id);
return out;
}
// verdict compares what the client saw with the rows it should have seen (in order).
static String verdict(List<String> base, List<String> shown) {
Map<String, Integer> count = new HashMap<>();
List<String> repeated = new ArrayList<>(), skipped = new ArrayList<>();
int last = -1;
for (String s : shown) {
if (count.merge(s, 1, Integer::sum) == 2) repeated.add(s);
last = Math.max(last, base.indexOf(s));
}
for (String b : base.subList(0, last + 1)) if (!count.containsKey(b)) skipped.add(b);
if (!repeated.isEmpty()) return "repeated " + list(repeated);
if (!skipped.isEmpty()) return "skipped " + list(skipped);
return "ok";
}
static void scenario(String kind, String change) {
List<Integer> table = new ArrayList<>(List.of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1));
List<String> base = names(table);
List<Integer> p1 = kind.equals("offset") ? offsetPage(table, 0, 3) : cursorPage(table, 0, 3);
if (change.equals("row 11 added")) { // someone posts while the client reads page 1
table.add(0, 11);
} else { // someone deletes post 9
table.remove(Integer.valueOf(9));
base.remove("9");
}
String next = "";
List<Integer> p2;
if (kind.equals("offset")) {
p2 = offsetPage(table, 3, 3);
} else {
int last = p1.get(p1.size() - 1);
next = " next=" + last;
p2 = cursorPage(table, last, 3);
}
List<String> shown = new ArrayList<>(names(p1));
shown.addAll(names(p2));
System.out.printf("%-6s %-14s page 1 %s%s, page 2 %s -> %s%n", kind, change + ":", list(names(p1)), next, list(names(p2)), verdict(base, shown));
}
record Product(int id, int price) {}
static String label(Product p) { return p.id() + ":" + p.price(); }
// Filter and sort, then page with a cursor. With byId the cursor is (price, id); without it, price only.
static String productPages(boolean byId) {
int[][] all = {{1, 700}, {2, 100}, {3, 300}, {4, 300}, {5, 450}, {6, 300}, {7, 500}};
List<Product> match = new ArrayList<>();
for (int[] p : all) if (p[1] <= 500) match.add(new Product(p[0], p[1]));
match.sort(Comparator.comparingInt(Product::price).thenComparingInt(Product::id)); // ORDER BY price, id
List<String> base = new ArrayList<>();
for (Product p : match) base.add(label(p));
List<String> pages = new ArrayList<>(), shown = new ArrayList<>();
Product cur = null;
while (true) {
List<String> page = new ArrayList<>();
Product last = null;
for (Product p : match) {
boolean after = cur == null || p.price() > cur.price() || (byId && p.price() == cur.price() && p.id() > cur.id());
if (after && page.size() < 2) {
page.add(label(p));
last = p;
}
}
if (page.isEmpty()) {
pages.add("[] end");
break;
}
shown.addAll(page);
String next = byId ? "next=" + last.price() + "," + last.id() : "next=" + last.price();
pages.add(list(page) + " " + next);
cur = last;
}
return String.join(" | ", pages) + " -> " + verdict(base, shown);
}
public static void main(String[] args) {
scenario("offset", "row 11 added");
scenario("cursor", "row 11 added");
scenario("offset", "row 9 deleted");
scenario("cursor", "row 9 deleted");
System.out.println("price<=500, sort=price,id, 2 per page:");
System.out.println(" cursor (price,id): " + productPages(true));
System.out.println(" cursor (price): " + productPages(false));
}
}Output (the same in all five languages):
offset row 11 added: page 1 [10 9 8], page 2 [8 7 6] -> repeated [8]
cursor row 11 added: page 1 [10 9 8] next=8, page 2 [7 6 5] -> ok
offset row 9 deleted: page 1 [10 9 8], page 2 [6 5 4] -> skipped [7]
cursor row 9 deleted: page 1 [10 9 8] next=8, page 2 [7 6 5] -> ok
price<=500, sort=price,id, 2 per page:
cursor (price,id): [2:100 3:300] next=300,3 | [4:300 6:300] next=300,6 | [5:450 7:500] next=500,7 | [] end -> ok
cursor (price): [2:100 3:300] next=300 | [5:450 7:500] next=500 | [] end -> skipped [4:300 6:300]
Reading the output:
- Offset, row 11 added: page 2 starts with
8again. The new row pushed everything down by one, andOFFSET 3now lands on 8. Repeated[8]. - Cursor, row 11 added: page 2 asks for rows older than 8 and gets
7 6 5. The new row at the top doesn't matter. - Offset, row 9 deleted: everything moved up by one, so
OFFSET 3lands on 6. Row7was never shown, and the user has no idea it exists. Skipped[7]. - Cursor, row 9 deleted: still
7 6 5. Nothing lost. - Cursor on
(price, id): three pages, every product exactly once, and an empty page marks the end. - Cursor on price alone: page 1 ended on a 300-taka product, so "price > 300" jumped over the other two 300-taka products. Skipped
[4:300 6:300], silently.
And the speed side, in real PostgreSQL 16 with a million posts:
$ psql -q -e < page.sql
CREATE TABLE posts AS SELECT g AS id, 'post ' || g AS title FROM generate_series(1, 1000000) g;
ALTER TABLE posts ADD PRIMARY KEY (id);
ANALYZE posts;
EXPLAIN (ANALYZE, COSTS OFF, BUFFERS OFF) SELECT id, title FROM posts ORDER BY id DESC LIMIT 20 OFFSET 900000;
QUERY PLAN
------------------------------------------------------------------------------------------------------
Limit (actual time=141.159..141.163 rows=20 loops=1)
-> Index Scan Backward using posts_pkey on posts (actual time=0.021..118.588 rows=900020 loops=1)
Planning Time: 0.152 ms
Execution Time: 141.177 ms
(4 rows)
EXPLAIN (ANALYZE, COSTS OFF, BUFFERS OFF) SELECT id, title FROM posts WHERE id < 100001 ORDER BY id DESC LIMIT 20;
QUERY PLAN
------------------------------------------------------------------------------------------------
Limit (actual time=0.040..0.043 rows=20 loops=1)
-> Index Scan Backward using posts_pkey on posts (actual time=0.039..0.041 rows=20 loops=1)
Index Cond: (id < 100001)
Planning Time: 0.111 ms
Execution Time: 0.057 ms
(5 rows)
OFFSET 900000readrows=900020rows through the index just to throw 900,000 of them away. 141 ms for 20 rows.- The keyset query
WHERE id < 100001readrows=20: the index jumped straight to the spot. 0.057 ms, about 2,500 times faster, for the very same 20 rows. - Page 1 with offset would be fast too. The difference only shows on deep pages, which is why offset problems appear months after launch.
Real engineering
- Default and maximum limits on every list endpoint, enforced on the server, documented in the API spec.
- Use cursor pagination for feeds, activity logs, sync APIs, exports and anything big or fast-changing. Keep offset for small admin tables where "page 7 of 12" matters.
- Index for the sort and filter you allow. A cursor query on
(created_at, id)needs an index on(created_at, id). For filtered lists, an index starting with the filter column ((status, created_at, id)) keeps pages fast. - Allow-list filter and sort fields. Never paste a
sortparameter into SQL (Module 9 covers injection), and don't let clients sort by unindexed columns on big tables. - Return links, not instructions:
{"items": [...], "next_cursor": "..."}or aLinkheader withrel="next". Clients shouldn't build cursors themselves. - Think about consistency. A cursor gives no repeats or gaps for rows that existed, but a row edited so its sort key moves (a post bumped to the top) can appear again or be missed. For exports that must be exact, page over a snapshot or by an immutable key like
id.
When it breaks
Pick a failure
LIMIT 20 OFFSET 80000
Think before you read on
Cursor pagination can't jump to "page 37". Yet Google search results and many shops show page numbers. How can a big site offer page numbers without the deep-offset problem?
Reveal
Mostly by not letting you go deep. Search engines cap results (you can't reach page 2,000), so the largest offset stays small. Shops do the same and encourage filters instead ("under 500 taka, in stock"), which shrink the list so that page numbers stay cheap. Some systems remember a cursor for each page boundary as you move, so "page 4" is really "after the cursor where page 3 ended". And when an exact page is truly needed in a huge table, a precomputed position column (rank) turns "page 37" into a fast WHERE rank BETWEEN 721 AND 740. The common idea: page numbers are fine as long as nothing has to skip a huge number of rows.
Check yourself
1. Why does offset pagination show repeats or skip rows on changing data?
Answer
The offset counts positions, and positions shift when rows are inserted or deleted before them. An insert pushes rows down (a repeat on the next page); a delete pulls them up (a row is skipped).
2. Why does OFFSET 900000 get slow?
Answer
The database has to read past all 900,000 rows to discard them before returning the next few. Cost grows with the offset. A cursor query uses an index to jump straight to the starting point.
3. Why add id to ORDER BY price?
Answer
Many rows can share a price, and their order is then undefined. A unique tie-breaker makes the order total and stable, so each row has exactly one place, and the cursor (price, id) points at exactly one spot.
4. Why should cursors be opaque to clients?
Answer
So clients pass them back without building or parsing them. The server can then change what's inside (new sort fields, different encoding) without breaking any client.
Your challenge: opaque cursors and limit + 1
Upgrade the product listing:
- Encode the cursor as base64 of
price,id(use your language's standard library) and decode it on the next request. - Fetch
limit + 1items. Return onlylimitof them, and includenext_cursoronly if the extra item existed. - Clamp
limitto at most 3, so a request for 50 still returns 3 per page.
Before you run it, predict how many pages a request with limit=2 returns, and whether the last page has a next_cursor.
You've succeeded when limit=2 gives 3 pages where the third has no next_cursor (and no empty fourth page is needed), the cursors look like MzAwLDM=, and limit=50 gives pages of 3.
The mental model
Never return a whole collection: filter, sort with a unique tie-breaker, and hand back a limited page plus a way to the next one. Offset paging counts positions, so it's simple and jumpable but repeats or skips rows when data changes and gets slower the deeper you go. Cursor (keyset) paging remembers the last sort key seen, so with a matching index every page costs the same and changing data can't shift it. Keep cursors opaque, allow-list filters and sorts, clamp limits, and avoid exact counts on big tables.
Station stamp
Finish the chapter
Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.
Go Pro to earn XP →