
Cursor pagination splits a long list into pages by remembering where the last page ended and asking for the rows after that point. Offset pagination counts and skips rows from the top each time instead, so it can repeat or miss rows when the list changes, and gets slower the deeper you go.
In this post we stay with the shop from the caching strategies post. Its staff app has an orders page, newest first, and on a sale day new orders arrive every few seconds. First we see what pagination is, using a pile of letters. Then we build the usual page-number version, catch it showing the same order twice, and fix it with a cursor. We measure both on a million orders, look at how real APIs such as Stripe and Slack hand out cursors, and finish with when page numbers are still the better choice and the mistakes beginners make.
A few words first. A database is the program that stores the shop's data. A table is a grid in it, where each row is one record, such as one order. SQL is the language you ask it questions in, and one question is a query. An API (application programming interface) is the set of addresses an app calls to get data from a server, such as GET /orders. And an index is a sorted list the database keeps next to a table so it can find rows without reading them all; the database indexing post explains how.
Key takeaways
- Pagination means sending a long list a few items at a time, a page each request, instead of all at once.
- Offset pagination asks for "page 2" as "skip 5 rows, then give me 5" (
LIMIT 5 OFFSET 5). If a new row arrives between two requests, a row is shown twice; if one is deleted, a row is never shown. - Cursor pagination (also called keyset pagination) asks for "the 5 rows after the last one I saw" (
WHERE (placed_at, id) < (?, ?)). New and deleted rows don't shift it. - Deep pages: on a million orders, the last page by OFFSET made SQLite read 1,000,000 rows. By cursor, it read 20.
- Sort by something unique. Ordering by time alone lets two orders with the same time trip up the cursor, so add the
idas a tiebreaker, and index both columns. - Give clients an opaque cursor: a string they pass back without reading. Sign it, check it, and cap the page size the client asks for.
What is pagination in simple words?
Picture a big pile of letters on a desk, with the newest always put on top. You ask a helper to read them to you, five at a time. There are two ways to say "the next five".
The first: "skip the top five, and read me the next five." That's fine if the pile stays still. But while you were listening to the first five, the postman dropped a new letter on top. Now "skip the top five" skips the new letter and four you've already heard, so the fifth letter you heard comes round again. That's offset pagination: the request says how many to skip, counted from the top.
The second: you put a bookmark under the last letter you heard, and say "read me the five under the bookmark." New letters on top don't matter, because you're not counting from the top any more. That bookmark is a cursor, and asking for "the ones after the bookmark" is cursor pagination.
On the web, the pile is a table, the five letters are a page, and the request is an API call such as GET /orders?limit=5. Every list you scroll through, from a chat history to a shop's search results, comes in pages like this, because sending a million rows at once would be slow for the server, the network and the phone.
What is offset pagination?
It's the one most tutorials start with, because SQL has it built in. Page 1 is LIMIT 5 OFFSET 0, page 2 is LIMIT 5 OFFSET 5, page n is OFFSET (n - 1) * 5. The PostgreSQL docs describe the parts: "OFFSET says to skip that many rows before beginning to return rows." And "If both OFFSET and LIMIT appear, then OFFSET rows are skipped before starting to count the LIMIT rows that are returned."
The rows also need a fixed order, or "page 2" means nothing. The same docs: "When using LIMIT, it is important to use an ORDER BY clause that constrains the result rows into a unique order. Otherwise you will get an unpredictable subset of the query's rows." (ORDER BY is the part of a query that sets the sort.) So the shop's orders page sorts by placed_at (the time the order was placed), newest first, and then by id, so that two orders placed at the same time still have a fixed order.
Offset pagination is easy to build, and it gives you things people like: page numbers, a "go to page 37" box, and "page 3 of 40". It has two problems, and we'll see both in code.
What goes wrong with offset pagination?
1. Rows shift under you. OFFSET counts from the top every time. On a list where new rows arrive at the top, each new row pushes everything down by one, so page 2 starts one row early and repeats the last row of page 1. On the shop's staff app, that's an order shown twice. If a row above is deleted, everything moves up by one, and a row falls into the gap between pages: an order nobody sees. On a busy sale day, with orders arriving every few seconds, this happens all the time.
2. Deep pages get slow. To show the last page of a million orders, 20 to a page, OFFSET has to skip 999,980 rows, and the database still has to find them, in order, one by one, before it can throw them away. The PostgreSQL docs: "The rows skipped by an OFFSET clause still have to be computed inside the server; therefore a large OFFSET might be inefficient." SQLite's docs say exactly how: "What really happens with "LIMIT x OFFSET y" is that SQLite computes the query as "LIMIT x+y" and discards the first y values without returning them to the application." So the work grows with the page number. In the terms of the Big O post, the cost of a page is O(offset), even though the page itself is always the same size.
What is cursor pagination?
Instead of a count, the request carries the bookmark: the sort values of the last row the client saw. Say the last order on page 1 was order 8, placed at 10:21 (we'll build this exact shop in Python below). The next page is "orders that come after order 8 in our order", which in SQL is:
SELECT id, placed_at FROM orders
WHERE (placed_at, id) < ('2026-11-30 10:21', 8)
ORDER BY placed_at DESC, id DESC
LIMIT 5;
The (placed_at, id) < (...) part is a row value comparison: it compares the pair of values the way a dictionary compares words, first by placed_at, and only if those are equal, by id. The PostgreSQL docs: "For the <, <=, > and >= cases, the row elements are compared left-to-right, stopping as soon as an unequal or null pair of elements is found." We use < because the list is newest first, so the next page holds smaller values. A list sorted oldest first would use >. Some databases don't understand the pair form. The same rule written out longhand works everywhere: WHERE placed_at < ? OR (placed_at = ? AND id < ?).
The SQLite docs use this very example for a scrolling list of contacts. "A more efficient approach is to remember the last entry currently displayed and then use a row value comparison in the WHERE clause". And: "assuming there is an appropriate index, it does so very efficiently — much more efficiently than OFFSET." The index is the reason. With an index on (placed_at, id), the database jumps straight to order 8's place in the sorted index and reads the next 5 entries. It doesn't matter whether that place is near the top or a million rows down.
This is also called keyset pagination, because the bookmark is a set of key values (here, two of them). "Cursor" is the name APIs use for the string that carries it.

How do you build cursor pagination in Python?
Let's build the shop's orders page both ways, with SQLite, the small database that comes with Python, so there's nothing to install. It has 12 orders, 5 to a page, and two of them (orders 7 and 8) were placed in the same minute, as happens on a busy day.
# orders.py
"""The shop's orders page, newest first: by page number (OFFSET), and by cursor."""
import base64
import hashlib
import hmac
import json
import sqlite3
MAX_LIMIT = 100
class BadCursor(ValueError):
pass
def open_shop(orders):
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, placed_at TEXT NOT NULL, item TEXT NOT NULL)")
db.execute("CREATE INDEX orders_newest ON orders (placed_at, id)")
db.executemany("INSERT INTO orders VALUES (?, ?, ?)", orders)
return db
def page_by_number(db, page, size=5):
rows = db.execute("SELECT id FROM orders ORDER BY placed_at DESC, id DESC LIMIT ? OFFSET ?",
(size, (page - 1) * size)).fetchall()
return [r[0] for r in rows]
def sign(body, secret):
return hmac.new(secret, body.encode(), hashlib.sha256).hexdigest()[:16]
def make_cursor(placed_at, order_id, secret):
body = base64.urlsafe_b64encode(json.dumps([placed_at, order_id]).encode()).decode().rstrip("=")
return f"{body}.{sign(body, secret)}"
def read_cursor(cursor, secret):
body, _, sig = cursor.partition(".")
if not hmac.compare_digest(sig.encode(), sign(body, secret).encode()):
raise BadCursor("this cursor wasn't made by us, or it was changed")
placed_at, order_id = json.loads(base64.urlsafe_b64decode(body + "=" * (-len(body) % 4)))
return placed_at, order_id
def list_orders(db, secret, cursor=None, limit=5):
limit = max(1, min(limit, MAX_LIMIT)) # never trust the size a client asks for
where, args = "", []
if cursor:
where, args = "WHERE (placed_at, id) < (?, ?)", list(read_cursor(cursor, secret))
rows = db.execute(f"SELECT id, placed_at FROM orders {where} ORDER BY placed_at DESC, id DESC LIMIT ?",
[*args, limit + 1]).fetchall() # ask for one extra row: is there a next page?
page, more = rows[:limit], len(rows) > limit
return {"orders": [r[0] for r in page],
"next_cursor": make_cursor(page[-1][1], page[-1][0], secret) if more else None}
if __name__ == "__main__":
SECRET = b"for this demo only: a real app loads a long random secret"
times = {n: f"2026-11-30 10:{n * 3:02d}" for n in range(1, 14)}
times[8] = times[7] # two orders placed in the same minute
first_12 = [(n, times[n], "kettle") for n in range(1, 13)]
order_13 = (13, times[13], "lamp")
print("1) Page numbers. Page 1, then order 13 arrives, then page 2")
db = open_shop(first_12)
print(" page 1:", page_by_number(db, 1))
db.execute("INSERT INTO orders VALUES (?, ?, ?)", order_13)
print(" page 2:", page_by_number(db, 2))
print("2) Page numbers. Page 1, then order 12 is deleted, then page 2")
db = open_shop(first_12)
print(" page 1:", page_by_number(db, 1))
db.execute("DELETE FROM orders WHERE id = 12")
print(" page 2:", page_by_number(db, 2))
print("3) Cursor. First page, then order 13 arrives, then the next page")
db = open_shop(first_12)
first = list_orders(db, SECRET)
print(" first page:", first["orders"], "next_cursor:", first["next_cursor"])
db.execute("INSERT INTO orders VALUES (?, ?, ?)", order_13)
print(" next page: ", list_orders(db, SECRET, first["next_cursor"])["orders"])
print("4) Cursor. Every page, until next_cursor is None")
db, seen, cursor = open_shop(first_12), [], None
while True:
page = list_orders(db, SECRET, cursor)
print(" ", page["orders"])
seen += page["orders"]
cursor = page["next_cursor"]
if cursor is None:
break
print(f" orders seen: {len(seen)}, seen twice: {len(seen) - len(set(seen))}")
print("5) Someone makes their own cursor, to jump ahead")
forged = make_cursor("2026-11-30 10:12", 4, b"a guess at the secret")
try:
list_orders(db, SECRET, forged)
except BadCursor as e:
print(" 400 Bad Request:", e)
A few lines to look at before we run it:
page_by_numberis offset pagination:LIMIT 5 OFFSET (page - 1) * 5.list_ordersis the cursor version, shaped like an API: it returns the page and anext_cursorfor the client to send back. With no cursor, it returns the first page.- It asks for
limit + 1rows. If the extra row comes back, there's another page, so it makes a cursor; if not,next_cursorisNoneand the client knows it has reached the end. The extra row is never shown. - The cursor is the last order's
placed_atandid, turned into JSON (a plain-text way of writing lists and values, such as["2026-11-30 10:21", 8]), then into base64, a way of writing any data with only letters, digits and a couple of symbols. Python'surlsafe_b64encodeuses the version that's safe in a web address: it "substitutes - instead of + and _ instead of / in the standard Base64 alphabet". We drop the=signs base64 adds at the end to pad out its length, since=means something in a web address, and put it back before decoding. - The cursor is signed. An HMAC is a short code made from the data plus a secret key only the server knows. Change one letter of the cursor, or make one without the key, and the code no longer matches.
read_cursorchecks it withhmac.compare_digest, which Python's docs recommend "instead of the == operator to reduce the vulnerability to timing attacks" (attacks that guess a correct signature a character at a time by timing how long each wrong guess takes to be rejected). MAX_LIMIT: the client picks the page size, but the server caps it, so nobody can ask for a million rows in one request.
Make a new folder, save the file in it as orders.py, open a terminal (a command-line window) in that folder and run it. In the output blocks, a line starting with $ is what you type, without the $; the lines under it are what it prints:
$ python orders.py
1) Page numbers. Page 1, then order 13 arrives, then page 2
page 1: [12, 11, 10, 9, 8]
page 2: [8, 7, 6, 5, 4]
2) Page numbers. Page 1, then order 12 is deleted, then page 2
page 1: [12, 11, 10, 9, 8]
page 2: [6, 5, 4, 3, 2]
3) Cursor. First page, then order 13 arrives, then the next page
first page: [12, 11, 10, 9, 8] next_cursor: WyIyMDI2LTExLTMwIDEwOjIxIiwgOF0.615ed5b91b13b897
next page: [7, 6, 5, 4, 3]
4) Cursor. Every page, until next_cursor is None
[12, 11, 10, 9, 8]
[7, 6, 5, 4, 3]
[2, 1]
orders seen: 12, seen twice: 0
5) Someone makes their own cursor, to jump ahead
400 Bad Request: this cursor wasn't made by us, or it was changed
Let's read it step by step:
- The repeat. Page 1 showed orders 12 to 8. Then order 13 arrived on top, so everything moved down one place. Page 2 (skip 5) skipped 13, 12, 11, 10 and 9, and started at order 8, which the staff member had already seen.
- The gap. This time order 12 was deleted after page 1. Everything moved up one place, page 2 skipped 11, 10, 9, 8 and 7, and started at 6. Order 7 was never on any page.
- The cursor doesn't care. Same arrival of order 13, but the next page asked for "after order 8, placed at 10:21", and got 7 to 3. Nothing repeated. Order 13 isn't lost either: it's at the top the next time someone opens page 1. Even deleting order 8 itself wouldn't break it: the cursor holds order 8's values, not its position, so "after (10:21, 8)" still starts at order 7.
- Walking the whole list. The client keeps sending back the
next_cursorit was given until it getsNone: 12 orders in 3 pages, none twice. Orders 7 and 8 share a time, and theidkept them in order across the page break. - A made-up cursor is refused. Someone built a cursor of their own, with a guessed key. The signature didn't match, so the API answers 400 Bad Request (the HTTP status for "your request is wrong") instead of running a query with values it never handed out.
The cursor in step 3 looks like random letters, but it isn't secret. The part before the dot is just base64: decode WyIyMDI2LTExLTMwIDEwOjIxIiwgOF0 and you get ["2026-11-30 10:21", 8]. The signature stops people changing it, not reading it. Never put anything private in a cursor.
Why is cursor pagination faster than OFFSET?
Let's measure it. This script fills a table with a million orders, newest first, 20 to a page, and asks for the same pages both ways. To show the work and not just the time, it gives SQLite a tiny Python function, look, that counts every row the query reads. (Python's create_function lets you "Create or remove a user-defined SQL function".) The timing runs the query without it.
# deep_page.py
"""A million orders, newest first, 20 to a page. How much work is a page deep in the list?"""
import sqlite3
import time
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, placed_at TEXT NOT NULL, item TEXT NOT NULL)")
db.execute("""
INSERT INTO orders
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1000000)
SELECT i, datetime('2026-01-01', '+' || (i * 30) || ' seconds'), 'kettle' FROM n""")
db.execute("CREATE INDEX orders_newest ON orders (placed_at, id)")
rows_read = 0
def look(order_id): # SQLite calls this once for every row it reads
global rows_read
rows_read += 1
return True
db.create_function("look", 1, look)
BY_OFFSET = "SELECT id, placed_at, item FROM orders WHERE {check} ORDER BY placed_at DESC, id DESC LIMIT 20 OFFSET ?"
BY_CURSOR = "SELECT id, placed_at, item FROM orders WHERE (placed_at, id) < (?, ?) AND {check} ORDER BY placed_at DESC, id DESC LIMIT 20"
def measure(name, sql, args):
global rows_read
best = float("inf")
for _ in range(5): # time the real query, best of 5
start = time.perf_counter()
page = db.execute(sql.format(check="1"), args).fetchall()
best = min(best, time.perf_counter() - start)
rows_read = 0 # run it once more, counting the rows it reads
db.execute(sql.format(check="look(id)"), args).fetchall()
print(f"{name:<29} orders {page[0][0]:>9,} to {page[-1][0]:>7,} rows read: {rows_read:>9,} best time: {best * 1000:.2f} ms")
measure("page 1", BY_OFFSET, (0,))
for page in (25_000, 50_000):
skip = (page - 1) * 20
measure(f"page {page:,} by OFFSET {skip:,}", BY_OFFSET, (skip,))
last_seen = db.execute("SELECT placed_at, id FROM orders WHERE id = ?", (1_000_001 - skip,)).fetchone()
measure(f"page {page:,} by cursor", BY_CURSOR, last_seen)
$ python deep_page.py
page 1 orders 1,000,000 to 999,981 rows read: 20 best time: 0.05 ms
page 25,000 by OFFSET 499,980 orders 500,020 to 500,001 rows read: 500,000 best time: 31.68 ms
page 25,000 by cursor orders 500,020 to 500,001 rows read: 20 best time: 0.05 ms
page 50,000 by OFFSET 999,980 orders 20 to 1 rows read: 1,000,000 best time: 68.83 ms
page 50,000 by cursor orders 20 to 1 rows read: 20 best time: 0.06 ms
Both ways return the same 20 orders. The difference is the work. For page 25,000, OFFSET read 500,000 rows and threw 499,980 of them away. For the last page, it read every one of the million rows. The cursor read 20 rows each time, the 20 it returned, wherever the page was. The times are from one run (the best of 5 tries) on a laptop: OFFSET took about 32 ms and 69 ms, and the cursor stayed at 0.05 to 0.06 ms. Your numbers will differ, but the shape won't: OFFSET grows with the page number, the cursor stays flat. This is a database in memory on the same computer. A real database on another server, with orders that don't fit in memory, makes the OFFSET pages slower still.
Who asks for page 50,000? More callers than you'd think: a program copying all your orders into a spreadsheet, a search engine's crawler following "next" links, or someone who keeps scrolling. For each of them, every page is slower than the one before it, so walking the whole list by OFFSET costs far more than walking it by cursor.
What should a cursor look like in an API?
Real APIs that use cursors all do roughly what list_orders does: the client sends a page size and the cursor it was given, and the server sends back a page plus the next cursor.
- Stripe (payments) uses an object's id as the cursor: "Stripe's list API methods use cursor-based pagination through the starting_after and ending_before parameters." Its docs give the example: "if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include starting_after=obj_foo to fetch the next page of the list." Each reply also has
has_more, "Whether or not there are more elements available after this set." - Slack hands out an opaque string: "Paginated responses include a top-level response_metadata object that includes a next_cursor when there are additional results to be retrieved." And it ends the same way ours does: "An empty, null, or non-existent next_cursor in the response indicates no further results."
- GitHub puts the next page's address in a
linkheader of the response, so the client doesn't build it: "The URL for the next page is followed by rel="next"." Its endpoints mix both styles: "each paginated endpoint will use the page, before / after, or since query parameters."
Google's API design guide, AIP-158, adds three rules worth copying. First, keep the cursor opaque: "Page tokens provided by APIs must be opaque (but URL-safe) strings, and must not be user-parseable." The reason is that if clients can read it, they'll start building their own, and then you can never change it: "This effectively makes the implementation details of your API's pagination become part of the API surface, and it becomes impossible to update those details without breaking users." The same guide warns: "Base-64 encoding an otherwise-transparent page token is not a sufficient obfuscation mechanism." In other words, base64 hides nothing: anyone can decode it. Our signature stops people changing a cursor, but they can still read it; an API that must hide what's inside goes further, by encrypting the cursor or keeping it on the server and handing out only a random id for it.
Second, cap the page size, as MAX_LIMIT does. AIP-158's example: "The maximum value is 1000; values above 1000 will be coerced to 1000."
Third, paginate from day one: "RPCs returning collections of data must provide pagination at the outset, as it is a backwards-incompatible change to add pagination to an existing method." (An RPC, a remote procedure call, is Google's word for one API method.) An app written when your list endpoint returned everything will happily show only the first page once you add pages, and never know the rest exists. That's the kind of change the previous post in this series, on API versioning, is about.
When should you use offset pagination instead?
| Offset (page numbers) | Cursor (keyset) | |
|---|---|---|
| Asks for | "Skip 40, give me 20" | "The 20 after the last one I saw" |
| Jump to page 37, show "page 3 of 40" | Yes | No |
| New or deleted rows | Repeats or skips rows | No repeats or gaps |
| Deep pages | Slower the deeper you go | Same speed, with an index |
| Needs | ORDER BY on unique columns | ORDER BY on unique columns, plus a matching index |
- When people need page numbers. A cursor only knows "next" (and, with a second cursor, "previous"). It can't jump to page 37, and it doesn't know how many pages there are. An admin table, a forum thread or search results where people really do click "page 4" may be better off with OFFSET.
- When the list is small or doesn't change. A product's 30 reviews, a settings list, last year's closed invoices: OFFSET's problems need a big or busy list. You can also cap how deep OFFSET may go, and send anyone who needs to go deeper to a cursor.
- When users can sort by many columns. Each sort (price, rating, name) needs its own cursor, built from its columns plus the id, and its own index to be fast. Without the index, both ways read and sort the whole list, so the cursor loses its speed edge, though it still doesn't repeat rows. A sort that mixes directions, such as cheapest first but newest first among equal prices, can't be written as one
(a, b) > (?, ?)comparison either. If that's too much to build for a small list, OFFSET with a cap on how deep it goes is simpler.
Everywhere else, and always for an infinite scroll or an API other programs will walk to the end, use a cursor. Feeds, chat history, activity logs and "export all my data" jobs are where rows arrive while people read, and where somebody eventually asks for page 50,000.
What mistakes do beginners make with cursor pagination?
1. Sorting by a value that isn't unique. Ordering by placed_at alone looks fine until two orders are placed in the same second. The cursor then says "after 10:21", and an order at exactly 10:21 that hadn't been shown yet is skipped for good. Always add a unique column, usually the id, as the last thing in the ORDER BY, in the cursor and in the index. Question 1 in the Try it box below breaks orders.py this way so you can see it happen.

2. A sort column that can be empty. In SQL, an empty value is NULL, and a comparison with NULL is neither true nor false. The PostgreSQL docs, on row comparisons: "If either of this pair of elements is null, the result of the row comparison is unknown (null)". A row with a NULL in a sort column never matches the cursor's WHERE, so it vanishes from every page after the first, and if the last row on a page has one, every page after it comes back empty. Sort by columns that are NOT NULL, as orders.py does.
3. Sorting by a value that changes. A list sorted by "last updated" moves while people page through it. If someone updates an order you haven't reached yet, it jumps to the top, above your bookmark, and this pass never shows it at all. One you've already passed jumps to the top too, so you won't see its new state until you start again. That's fine for some lists, but know it's happening. Sort by something fixed, such as when the row was created, when you need every row exactly once.
4. Trusting the cursor and the page size. Both come from the client, so treat them like any other input. Check the cursor's signature, answer 400 for a bad one, cap the limit, and never paste a cursor's contents into SQL as text: pass them as ? parameters, as list_orders does. And remember that the cursor only says where the page starts. The rest of the query has to stay the same: if a page is filtered to one shop in a multi-tenant app (one app serving many shops, each seeing only its own data), the server must apply that filter on every page, from the login, not from anything in the cursor. AIP-158 makes the same rule: while paging, every other parameter must match the call that handed out the cursor.
1) In orders.py, change the cursor line in list_orders so it uses the time only:
where, args = "WHERE placed_at < ?", [read_cursor(cursor, secret)[0]]
Run it again. What does step 4 print, and which order went missing?
2) Put the cursor line back. In step 4, change list_orders(db, SECRET, cursor) to list_orders(db, SECRET, cursor, limit=4). The 12 orders now fill exactly 3 pages. Does the client have to make a fourth request that comes back empty?
3) The shop adds a "cheapest first" product list, sorted by price, with the product id as the tiebreaker. Write its cursor query for "the 20 products after the one priced 499 with id 31", and the index it needs.
Show the answers
1) Step 4 now prints:
4) Cursor. Every page, until next_cursor is None
[12, 11, 10, 9, 8]
[6, 5, 4, 3, 2]
[1]
orders seen: 11, seen twice: 0
Order 7 is missing. Page 1 ended at order 8, placed at 10:21, and the cursor asked for orders placed before 10:21. Order 7 was placed at 10:21 too, so it wasn't "before", and no page ever showed it. Step 3 skips it the same way. Nothing errors, and the count is only one short, which is why this bug survives testing.
2) No. Step 4 prints [12, 11, 10, 9], [8, 7, 6, 5], [4, 3, 2, 1], then orders seen: 12, seen twice: 0. On the third request, list_orders asked for 5 rows and got only 4, so it knew there was nothing after them and returned next_cursor: None. That's what the limit + 1 is for. Without it, the server would hand out a cursor after every full page, and the client would make a fourth request just to get an empty list.
3) Cheapest first means the next page holds bigger values, so the comparison flips to > and both sorts are ascending:
CREATE INDEX products_cheapest ON products (price, id);
SELECT id, name, price FROM products
WHERE (price, id) > (499, 31)
ORDER BY price, id
LIMIT 20;
A product priced 499 with an id above 31 comes next; one priced 499 with an id below 31 was already shown. In an app, the 499 and 31 come from the signed cursor and are passed as ? parameters.
Questions people ask
What is the difference between offset and cursor pagination?
Offset pagination asks for a page by how many rows to skip, such as "skip 40, give me 20". Cursor pagination asks for the rows after the last one the client saw. Offset gives page numbers but can repeat or miss rows when the list changes, and gets slower on deep pages. A cursor doesn't repeat or skip rows when rows are added or removed, and stays fast with an index, but it can't jump to a page number.
Is cursor pagination the same as keyset pagination?
Mostly, yes. Keyset pagination is the database technique: a WHERE on the sort columns, such as (placed_at, id) < (?, ?), instead of an OFFSET. Cursor pagination is the API side of it: the server wraps those key values in an opaque string, the cursor, and the client sends it back to get the next page.
Why is OFFSET slow for large pages?
Because the database can't jump to row 1,000,000 of a sorted list. It finds the rows in order and throws away the ones it was told to skip, so the work grows with the offset. In our test on a million orders, the last page made SQLite read 1,000,000 rows to return 20. A cursor uses an index to start at the right place and reads only the 20.
Can cursor pagination go to the previous page?
Yes, with a second cursor made from the first row of the page. The query flips the comparison and the sort, for example (placed_at, id) > (?, ?) ordered oldest first, and then reverses the rows before returning them. Stripe's API offers this as its ending_before parameter. What a cursor can't do is jump to page 37 or say how many pages there are.
What should a pagination cursor contain?
The sort values of the last row on the page, such as its time and id, and nothing private. Encode it so it's safe in a web address, sign it so it can't be changed, and treat it as opaque so clients don't build their own. If its contents must stay hidden, encrypt it or store it on the server and hand out a random id.
Keep going
- Previous in this System Design series: "API versioning", how to change an API without breaking the apps that already use it.
- Next: "Feature flags", how to turn a new feature on for some users without a new release.
- Related: Database indexing, the sorted list that makes a cursor fast, and Caching strategies, the other way to keep a busy list page quick.
Checked on 29 November 2026 against the 10 sources below.
Sources
- PostgreSQL documentation: LIMIT and OFFSET
- PostgreSQL documentation: Row and Array Comparisons (row constructor comparison)
- SQLite documentation: Row Values (scrolling window queries)
- Stripe API reference: Pagination
- Slack developer docs: Pagination
- GitHub Docs: Using pagination in the REST API
- Google API Improvement Proposals: AIP-158, Pagination
- Python documentation: base64
- Python documentation: hmac
- Python documentation: sqlite3 (create_function)
Every Python sample in this post was run in Python 3.13 with SQLite 3.45 before publishing, on 29 November 2026, and both SQL queries in Try it 3 were run in SQLite.