LeepCast
Subscribe
All posts
Software

Keyset Pagination Explained: Why OFFSET Slows Down and How Cursor Pagination Stays Fast

Why LIMIT and OFFSET get slower on every page and return duplicates when data changes, and how keyset pagination with row value comparisons and opaque cursors fixes both.

LeepCast9 min read

Almost every API that returns a list eventually needs pagination, and the first version usually looks the same everywhere: a page number from the client, LIMIT and OFFSET in the query, done. It works fine in a demo with a few hundred rows. It starts to hurt when the table grows into the millions, when clients walk deep into the list, or when new rows arrive while someone is paging. Keyset pagination, also called the seek method or cursor pagination, fixes both the speed problem and the consistency problem with a small change to the WHERE clause.

This explainer covers why OFFSET gets slower the further you go, how a keyset query skips straight to the right spot in an index, how to handle ties with row value comparisons, how to turn the position into an opaque cursor for an API, and when OFFSET is still the better choice. A short Python script at the end shows both approaches side by side so you can watch OFFSET return a duplicate.

What OFFSET really asks the database to do

OFFSET carries exactly one piece of information: a count of rows to throw away. The database has no idea which rows those were or where the previous page ended, so the only way to honour the request is to produce the rows in order and discard them one at a time until the count runs out. The PostgreSQL manual says this plainly: rows skipped by OFFSET still have to be computed inside the server, so a large offset can be inefficient. Page 1 reads 20 rows. Page 5,000 reads 100,020 rows and returns the last 20.

With a matching B-tree index the database can at least walk the index in sorted order instead of sorting the whole table, but it still has to step over every skipped entry. Cost grows linearly with page depth. That is why deep pages in admin panels, data exports and API clients that sync a full collection are the first places offset pagination falls over.

The drifting window

The second problem has nothing to do with speed. Each OFFSET request recounts from the top of the list. If a row is inserted near the top between two requests, every existing row shifts down by one position, and the first row of the next page is one the client already saw. A deletion does the opposite and silently hides a row. For a feed of newest items, which is the most common thing people paginate, inserts at the top happen constantly.

The keyset idea: remember where you stopped

Instead of telling the database how many rows to skip, tell it the sort key of the last row you returned and ask for the rows that come after it. If the list is ordered by id descending and the last row on the page had id 4812, the next page is simply the first rows with an id smaller than 4812. With an index on id, the database jumps to 4812 in the index and reads forward. The amount of work is the same on page 2 and on page 20,000.

sql
-- first page
SELECT id, title FROM articles
ORDER BY id DESC
LIMIT 20;

-- every later page: pass the last id you returned
SELECT id, title FROM articles
WHERE id < 4812
ORDER BY id DESC
LIMIT 20;

The direction of the comparison follows the direction of the sort. Descending order uses less-than, ascending order uses greater-than. Because the position is anchored to a value rather than a count, a row inserted above the anchor does not push anything into the next page.

Ties need a tiebreaker

Real lists rarely sort on a unique column. A feed sorted by created_at can have many rows with the same timestamp, and if a page boundary lands in the middle of such a group, a filter of created_at < last_value skips the rest of that group entirely. The fix is to make the sort order deterministic by appending a unique column, normally the primary key, to both the ORDER BY and the filter. The PostgreSQL documentation makes the same point for LIMIT in general: without an ORDER BY that forces a unique order, you get an unpredictable subset of rows, and different LIMIT values can produce different plans and different orders.

SQL has a compact way to express comparing two columns as a unit: row values. The condition (created_at, id) < (x, y) is true when created_at is less than x, or when created_at equals x and id is less than y. PostgreSQL compares row constructors element by element from left to right and stops at the first pair that differs, which is exactly the meaning of comes before in a two-column sort.

sql
CREATE INDEX orders_created_id ON orders (created_at, id);

SELECT id, created_at, total
FROM orders
WHERE (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT 21;

PostgreSQL can use that row comparison directly as an index range condition on the two-column index, so the query starts reading at the right entry. Support elsewhere is uneven. Markus Winand's comparison on Use The Index, Luke notes that MySQL evaluates row values correctly but cannot use them to access the index, and that SQL Server lacks row values altogether. On those systems, write the expanded form and repeat the leading column as a plain range condition so the optimizer has something it can seek on:

sql
WHERE created_at <= ?
  AND (created_at < ? OR (created_at = ? AND id < ?))

From position to API cursor

A keyset is several values, not one number, so the API contract changes. Rather than exposing raw column values, most APIs return a cursor: an opaque string the client hands back to get the next page. Slack's engineering team described moving their Web API to this model as their datasets grew from hundreds of records to hundreds of thousands. Their scheme fetches one row more than requested, uses that extra row to decide whether another page exists, and returns an empty next cursor on the final page so clients know when to stop.

A practical cursor design looks like this:

  • Encode the full sort key of the last returned row, for example created_at and id, as JSON and then URL-safe Base64.
  • Treat it as opaque in your documentation so you can change the encoding later without breaking clients.
  • Reject cursors that fail to decode with a clear 400 error rather than a 500.
  • Sign or encrypt the cursor if the sort key leaks something you do not want exposed, such as internal timestamps or sequential ids.
  • Bind the cursor to the filters and sort it was issued for; a cursor from a sort by price is meaningless for a sort by date.
  • Fetch limit plus one rows so you can tell whether a next page exists without running a COUNT query.

A runnable side-by-side demo

The script below uses Python's built-in sqlite3 module, so it runs anywhere Python 3 does with no setup. SQLite has supported row value comparisons since version 3.15. It creates twelve orders with three orders per day, serves the first page with both methods, inserts a new order, and then asks each method for page two.

python
import base64, json, sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, created_at TEXT NOT NULL)")
db.execute("CREATE INDEX orders_created_id ON orders (created_at, id)")
# 12 orders, three per day, so created_at alone is not unique
rows = [(i, f"2026-11-{20 + (i - 1) // 3:02d}") for i in range(1, 13)]
db.executemany("INSERT INTO orders VALUES (?, ?)", rows)

def encode(created_at, row_id):
    raw = json.dumps([created_at, row_id]).encode()
    return base64.urlsafe_b64encode(raw).decode()

def decode(cursor):
    return json.loads(base64.urlsafe_b64decode(cursor))

def offset_page(page, size=4):
    sql = "SELECT id FROM orders ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?"
    return [r[0] for r in db.execute(sql, (size, page * size))]

def keyset_page(cursor=None, size=4):
    if cursor is None:
        sql = "SELECT id, created_at FROM orders ORDER BY created_at DESC, id DESC LIMIT ?"
        got = db.execute(sql, (size + 1,)).fetchall()
    else:
        created_at, row_id = decode(cursor)
        sql = ("SELECT id, created_at FROM orders "
               "WHERE (created_at, id) < (?, ?) "
               "ORDER BY created_at DESC, id DESC LIMIT ?")
        got = db.execute(sql, (created_at, row_id, size + 1)).fetchall()
    page, extra = got[:size], got[size:]
    next_cursor = encode(page[-1][1], page[-1][0]) if extra else None
    return [r[0] for r in page], next_cursor

first_offset = offset_page(0)
first_keyset, cur = keyset_page()
print("page 1        ", first_offset, first_keyset)

# a new order arrives between the two requests
db.execute("INSERT INTO orders VALUES (13, '2026-11-23')")

print("offset page 2 ", offset_page(1))
second_keyset, cur = keyset_page(cur)
print("keyset page 2 ", second_keyset)

Running it prints the same first page for both methods, ids 12, 11, 10 and 9. After order 13 arrives, the offset version returns 9, 8, 7 and 6, so order 9 appears twice. The keyset version returns 8, 7, 6 and 5 because its cursor points at order 9 itself, not at position four. The new order is not lost either: it sits above the cursor and will show up the next time the client loads the first page.

OFFSET vs keyset at a glance

  • Cost of a deep page: OFFSET grows with the number of skipped rows; keyset stays roughly constant with a matching index.
  • Concurrent inserts and deletes: OFFSET can repeat or skip rows; keyset stays anchored to the last row seen.
  • Jump to page 37: OFFSET supports it directly; keyset cannot without walking every page in between.
  • Total page count: natural with OFFSET plus COUNT; keyset usually omits it, which also saves an expensive query.
  • Going backwards: OFFSET just subtracts; keyset needs flipped comparisons and sort direction, then reversing the result.
  • Implementation effort: OFFSET is built into every ORM; keyset needs a cursor format and a deterministic sort.

Common mistakes

  • Sorting on a non-unique column without a tiebreaker, which silently drops rows at page boundaries.
  • Creating an index whose column order or direction does not match the ORDER BY, which forces a full sort on every request.
  • Mixing directions, such as created_at DESC with id ASC, and still using a single row comparison. A row comparison assumes every column moves the same way; mixed directions need the expanded OR form or an index built with matching directions.
  • Paginating on a nullable column. PostgreSQL returns null for a row comparison that reaches a null pair, so rows with nulls vanish from results. Make the column NOT NULL or map nulls with COALESCE consistently in both the index and the query.
  • Letting clients change filters while keeping the old cursor, which produces pages that do not belong to any consistent result.

When OFFSET is still fine

Keyset pagination is not a universal upgrade. A small, slowly changing table, such as a settings list or a back-office report with a few thousand rows, gains nothing from the extra complexity. Interfaces where users genuinely need to jump to an arbitrary page number, like a numbered search results page, fit OFFSET better, and most users never go past the first few pages anyway. A reasonable rule of thumb:

  1. If clients sync entire collections or scroll an infinite feed, use keyset pagination.
  2. If the table is large and changes while users page through it, use keyset pagination.
  3. If the data is small, stable and users need numbered pages, OFFSET is acceptable.
  4. If you need both, offer keyset for API and export traffic and cap OFFSET depth in the user interface.

The underlying lesson is that pagination is a contract about position. OFFSET describes position as a count, which the database must recompute and which changes whenever the data does. Keyset pagination describes position as a value in a sorted index, which the database can seek to directly and which stays put while the rest of the list moves.

Share

Enjoyed this?

Get the next deep dive in your inbox. No spam — just the stories worth reading.

Subscribe to the newsletter

Comments