Skip to content

    System Design

    Pagination: Offset, Cursor and Keyset

    Learn why a deep OFFSET reads every skipped row, how keyset queries and opaque cursors stay fast and stable, and why a sort key needs a tie-breaker.

    By Published 12 min read

    Share

    Standard lessonintermediatePostgreSQL labBackend System Design

    Before this: API Design

    What you'll learn: By the end of this lesson you will be able to explain why OFFSET gets slower the deeper you page, write a keyset query with a row comparison that an index can serve, say how a cursor differs from a keyset, show why the sort key must be unique, and decide what a paginated API promises about totals, page jumps and changing data.

    Picture a library shelf sorted by the date each book arrived, newest first. A reader asks for "the next ten after the first forty thousand". With an offset the librarian must walk past forty thousand books, counting, before handing over ten. With a bookmark ("continue after the book with this call number") the librarian goes straight to that spot. If new books arrive at the front meanwhile, the counted walk lands off; the bookmark does not move.

    That is the whole lesson in one picture. API design fundamentals already says cursors beat offsets and shows the response shape. Here is the dedicated treatment: what the database does for each method, the plans, the tie-breaker that most first versions forget, and what a cursor promises. The client side is the paired lesson Pagination and infinite scroll.

    The core idea

    Offset names a position. Keyset names a row. A cursor is the API's way of handing the client a keyset without letting it look inside.

    • Offset (LIMIT 20 OFFSET 40000): skip a number of rows, then take a page. Simple, allows "jump to page N", and its cost grows with the offset.
    • Keyset (also called seek): WHERE (sort columns) < (last row's values) ORDER BY the same columns LIMIT 20. With a matching index the database starts at the right entry and reads only the page.
    • Cursor: an opaque token the server returns (next_cursor) and the client sends back unchanged. It usually encodes a keyset position, but it is a contract about the API, not about SQL.

    Three illustrations run through the lesson: a minimal example (the lab, 50,000 products), a realistic example (ShopStream's order list and a nightly partner export, in "In practice") and a failure example (ties in the sort key, which silently skip rows).

    What OFFSET costs

    The PostgreSQL manual states the cost plainly: the rows skipped by an OFFSET clause still have to be computed inside the server, so a large OFFSET might be inefficient. It also says LIMIT needs an ORDER BY with a unique order, or the subset is unpredictable.

    An index changes where the work happens, not whether it happens. A B-tree can deliver rows in sorted order, so an ORDER BY with LIMIT can read just the first rows from a matching index. But with an offset the scan must still produce the skipped rows before the page. The lab measures this on 50,000 illustrative products, newest first, 20 per page. "Pages touched" is the shared-buffer hits plus reads that EXPLAIN (ANALYZE, BUFFERS) reports for the plan; "rows below the limit" is the largest row count any plan node produced.

    Expected output, captured from a real run (steps 1 and 2: PGlite 0.6.1, which reports PostgreSQL 19.0, on 2026-12-01):

    1. OFFSET with no index: every page sorts the table, however shallow
    offset     0  plan: Limit (20 rows) > Sort (20 rows) > Seq Scan on products (50000 rows)
                 rows returned: 20   rows below the limit: 50000   pages touched: 416
    offset 40000  plan: Limit (20 rows) > Sort (40020 rows) > Seq Scan on products (50000 rows)
                 rows returned: 20   rows below the limit: 50000   pages touched: 416
    
    2. create index products_feed_idx on products (listed_at desc, id desc)
    OFFSET with the index: the plan is an ordered index scan, and the cost grows with the offset
    offset     0  rows below the limit:    20   pages touched:    22   plan: Limit (20 rows) > Index Scan using products_feed_idx (20 rows)
    offset  1000  rows below the limit:  1020   pages touched:  1025   plan: Limit (20 rows) > Index Scan using products_feed_idx (1020 rows)
    offset 10000  rows below the limit: 10020   pages touched: 10060   plan: Limit (20 rows) > Index Scan using products_feed_idx (10020 rows)
    offset 40000  rows below the limit: 40020   pages touched: 40175   plan: Limit (20 rows) > Index Scan using products_feed_idx (40020 rows)

    Without an index every page reads all 416 table pages and sorts. With the index, page one costs 22 page visits, but the cost tracks the offset: the node under the Limit produces offset + 20 rows, 40,020 at the deep end. This is a property of this data and plan, not a prediction for your table, and the lab prints no timings.

    Keyset: continue after the last row

    A keyset query replaces the position number with the last row's own sort values. The comparison is a row constructor comparison: the manual says that for <, <=, > and >= the elements are compared left to right, stopping at the first pair that is unequal or null. That is exactly the lexicographic order of ORDER BY listed_at DESC, id DESC, so (listed_at, id) < (a, b) means "after row (a, b) in this feed".

    select id, listed_at, name from products
    where (listed_at, id) < ('2026-01-09 16:15:00', 11605)
    order by listed_at desc, id desc
    limit 20

    The index (listed_at desc, id desc) matches both the WHERE and the ORDER BY, so the scan starts at the cursor's entry and stops after 20 rows. Same lab, same index:

    Expected output, captured from a real run (step 3, the same run):

    3. Keyset on the same index: ask for the rows after the last row already shown
    after position     0  rows below the limit:    20   pages touched:    22   same 20 rows as OFFSET 0: true
    after position  1000  rows below the limit:    20   pages touched:    22   same 20 rows as OFFSET 1000: true
    after position 10000  rows below the limit:    20   pages touched:    22   same 20 rows as OFFSET 10000: true
    after position 40000  rows below the limit:    20   pages touched:    22   same 20 rows as OFFSET 40000: true
    plan: Limit (20 rows) > Index Scan using products_feed_idx (20 rows)
    index condition: (ROW(listed_at, id) < ROW('2026-01-02 17:40:00'::timestamp without time zone, 10000))

    The cost is 22 page visits at every position and the rows are the same ones OFFSET returns. The row comparison shows up as an index condition, so the index does the seeking.

    Figure 1. A keyset page request

    A cursor in, a keyset query, an index seek, a cursor outClient to List API (limit, cursor); List API to Feed index (row comparison); Feed index to Table rows (20 entries); List API to Client (items, next_cursor)Client: sends the cursor back unchangedClientsends the cursorback unchangedList API: decode, query, encodeList APIdecode, query,encodeFeed index: listed_at desc, id descFeed indexlisted_at desc,id descTable rows: only the 20 hitTable rowsonly the 20 hitlimit, cursorrow comparison20 entriesitems, next_cursor

    How to read this: the cursor is the only state. The server turns it into a position inside the index, reads one page and returns the position after the last row. Nothing remembers where this client was.

    The sort key must be unique

    Failure example. If many rows share a sort value, WHERE listed_at < last_listed_at is wrong: a page boundary can fall inside a group of equal timestamps, and the rest of the group is skipped. In the lab, four products share each listing minute and the pages hold 30 rows, so boundaries land inside groups. A tie-breaker column (the primary key) makes the order total, and the row comparison compares it too.

    Expected output, captured from a real run (step 6, the same run):

    6. Ties: a keyset on a column that is not unique skips rows
    walking 100 pages of 30 should deliver the first 3000 rows of the feed
      where listed_at < last listed_at          : 186 of those 3000 rows never delivered (first missing ids: 21068 8568 17136 4636 13204 704)
      where (listed_at, id) < (last, last id)   : 3000 rows delivered, 0 rows skipped, same order as the table: true

    No error, no warning, 186 missing rows. This is the pagination bug that survives testing because small test data has no ties. The same manual rule applies to offset: without a unique ORDER BY, the subset is unpredictable.

    Figure 2. Where a boundary can fall

    flowchart TD accTitle: A page boundary inside a group of equal timestamps accDescr: Four products share the same listing minute. Page one ends after the second of them. A query that continues after that timestamp alone skips the other two. A query that also compares the product id continues from the third. G["Four products listed in the same minute
    ids 90, 80, 70, 60 (newest first)"] P1["Page 1 ends after id 80"] N["Naive: listed_at before this minute
    skips ids 70 and 60"] K["Keyset: (listed_at, id) before (this minute, 80)
    continues with id 70"] G --> P1 P1 --> N P1 --> K

    How to read this: the ids are a teaching example. The naive condition compares only the timestamp, so everything that shares it with the last row is treated as already seen.

    The cursor is the contract

    A keyset is SQL; a cursor is what the API exposes. Step 4 of the lab shows one: the server encodes the last row's position as a URL-safe string, the client sends it back, and the server decodes it into the query.

    Expected output, captured from a real run (step 4, the same run):

    4. A cursor is the contract; the keyset is how the database follows it
    page 1 returned ids: 44821 32321 19821 7321 39642 27142 14642 2142 46963 34463 21963 9463 41784 29284 16784 4284 49105 36605 24105 11605
    next_cursor        : eyJ0IjoiMjAyNi0wMS0wOSAxNjoxNTowMCIsImlkIjoxMTYwNX0
    decoded by server  : {"listedAt":"2026-01-09 16:15:00","id":11605}
    next query         : select id, listed_at, name from products where (listed_at, id) < ('2026-01-09 16:15:00', 11605) order by listed_at desc, id desc limit 20

    The lab's encoding is base64 of a small JSON object, so it is opaque to the client by convention only. Google's pagination proposal (AIP-158) says page tokens must be opaque but URL-safe and must not be user-parseable, that an empty next_page_token is the only way to signal the end of a collection, that a changed page_size must be honoured and an over-large one coerced down, and that tokens may expire (about three days as a rule of thumb). A readable token is one clients will build by hand, and then you can never change what it encodes.

    Stripe's list endpoints show the simplest form: limit (1 to 100, default 10), starting_after taking an object id, and a has_more flag.

    Figure 3. Choosing a method

    flowchart TD accTitle: Choosing offset or keyset pagination accDescr: If users must jump to an arbitrary page number on a small, stable list, use offset. Otherwise, if the list is large, changes while it is read, or is consumed by a machine, use keyset with an opaque cursor and a unique sort key backed by an index. A{"Must users jump to
    page N?"} A -->|"yes"| B{"Is the list small
    and stable?"} A -->|"no"| K["Keyset with an opaque cursor"] B -->|"yes"| O["Offset is fine,
    cap the maximum offset"] B -->|"no"| K K --> U["Unique sort key plus an index
    that matches it"]

    How to read this: the question that picks offset is a product question (jumping to a page) and a size question. A machine consumer such as an export or a sync always lands on keyset.

    When rows arrive or leave

    The second reason to leave offset is correctness. An offset is a count of rows, and a count shifts when the list changes. The lab holds page 1, then changes the table in a transaction, asks for page 2 both ways and rolls back, which reproduces a committed change by another session.

    Figure 4. Offset drift

    sequenceDiagram accTitle: Offset pagination repeating and skipping rows accDescr: The reader loads page one. Five new products are listed. The reader asks for offset 20 and receives the last five rows of page one again. In a second case three products from page one are delisted, and offset 20 skips the first three rows of the real page two. A keyset request after the last row of page one returns the right page both times. participant R as Reader participant S as Server R->>S: page 1 (offset 0, limit 20) S-->>R: 20 rows Note over S: 5 new rows at the top R->>S: offset 20 S-->>R: last 5 rows of page 1 again Note over S: or 3 rows of page 1 removed R->>S: offset 20 S-->>R: skips 3 rows, never shown R->>S: keyset after page 1's last row S-->>R: the correct next 20 rows

    How to read this: neither request is wrong from the server's point of view. The count means a different place each time, while the row the keyset names is still where it was.

    Expected output, captured from a real run (step 5, the same run):

    5 new products are listed (ids 50001 to 50005, newest of all) before the reader asks for page 2:
      OFFSET 20 returns : 4284 49105 36605 24105 11605 43926 31426 18926 6426 38747 26247 13747 1247 46068 33568 21068 8568 40889 28389 15889
                          repeated from page 1: 4284 49105 36605 24105 11605 (5 rows)
      keyset after page 1's last row returns: 43926 31426 18926 6426 38747 26247 13747 1247 46068 33568 21068 8568 40889 28389 15889 3389 48210 35710 23210 10710
                          repeated from page 1: 0 rows; same as the unchanged page 2: true
    3 products from page 1 are delisted (ids 44821 32321 19821) before the reader asks for page 2:
      OFFSET 20 returns : 6426 38747 26247 13747 1247 46068 33568 21068 8568 40889 28389 15889 3389 48210 35710 23210 10710 43031 30531 18031
                          never shown to the reader: 43926 31426 18926 (the first 3 rows of the real page 2)
      keyset after page 1's last row returns: 43926 31426 18926 6426 38747 26247 13747 1247 46068 33568 21068 8568 40889 28389 15889 3389 48210 35710 23210 10710
                          same as the unchanged page 2: true

    A client can hide a repeat by merging on id, but nothing the client does recovers a row it was never sent. Use the Index, Luke makes the same point: offset gives duplicates when rows are inserted between two page fetches.

    What keyset cannot do

    • Jump to page N. A keyset needs the previous row. The cursor model has no "page 40"; if users need it, the list is small enough for offset, or you give them search and filters.
    • A total count. count(*) is its own query. In the lab it reads all 416 table pages while a page plus one spare row reads 23. The spare row is the cheap way to know whether there is a next page: ask for 21, show 20.
    • Any order you like. Each sort order needs an index that matches it (the manual notes an index can be scanned backward, and a mixed ASC/DESC order needs an index declared that way). A row comparison applies one direction to every column, so a mixed order needs an expanded OR condition instead.
    • Null sort columns. The manual says a row comparison with a null in a compared pair gives unknown, not true, so keep sort columns NOT NULL or handle nulls explicitly.

    Google's proposal lets an API return a total that may be an estimate, if it says so. (Lab step 7.)

    Trade-offs

    Choice Gain Cost Pick when
    Offset Jump to any page; trivial to write Cost grows with the offset; repeats and skips when data changes Small, stable lists; admin tables
    Keyset Flat cost; stable under inserts and deletes No jump; needs a unique key and a matching index; one index per sort order Feeds, exports, sync, large tables
    Opaque cursor Freedom to change what it encodes Clients cannot build or inspect it Any public or partner API
    Limit plus one row Cheap "has next page" Slightly larger query Almost every list

    Build it

    The lab is examples/postgres-labs/labs/pagination-offset-cursor-keyset. It runs on PGlite, which is real PostgreSQL compiled to WebAssembly, in memory and single user: the planner and EXPLAIN output are PostgreSQL's, but it shows no timings and no second connection (the "rows arrive" steps run inside one session and roll back). This capture reports PostgreSQL 19.0; the course targets 18, so the lesson quotes only what the current manual (also 19) states.

    cd examples/postgres-labs && npm install
    node --test labs/pagination-offset-cursor-keyset/test.mjs
    cd labs/pagination-offset-cursor-keyset && node run.mjs

    The 9 tests passed with Node 26.13.1; the demo can take a minute or more because it scans tens of thousands of rows. The output above is examples/postgres-labs/golden/pagination-offset-cursor-keyset.txt. lab.mjs builds 50,000 products from generate_series with arithmetic only (4 per listing minute, ids scattered against time), so the data never changes.

    Break it (a suggested experiment, not part of the captured run). In lab.mjs, make keysetPage compare listed_at alone, as naiveKeysetPage does: the test that the tie-broken walk equals the table order should fail. Restore the file and re-run.

    In practice: ShopStream's order list and nightly partner export

    NOTE

    This is a realistic scenario, not a case history. It is a composite on the course's running example, ShopStream, an educational reference design. Every number is an illustrative assumption.

    The situation

    Stores see their orders newest first in a dashboard, and a partner accounting tool pulls every order of a store each night. Both use GET /orders?limit=100&offset=N. A busy store has tens of thousands of orders. The nightly job reaches deep offsets and slows the database that also serves checkout, and finance reports a few orders listed twice.

    Starting architecture

    Figure 5. Offset on a growing table

    Starting architecture: offset paging for a dashboard and a nightly exportStore dashboard to Orders API (offset); Partner export to Orders API (offset, deep); Orders API to Orders table (skip N, take 100)Store dashboard: pages 1 to 5Storedashboardpages 1 to 5Partner export: pages 1 to 400Partner exportpages 1 to 400Orders API: limit 100 offset NOrders APIlimit 100 offsetNOrders table: order by placed_at descOrders tableorder byplaced_at descoffsetoffset, deepskip N, take 100

    How to read this: the warning boxes are where cost grows with the offset. The export is the deepest reader, so it is the heaviest user of the slowest path.

    Options considered

    Option Fixes Costs Risk
    Add an index on placed_at only Removes the sort Deep pages still read every skipped row The export is still slow
    Keyset on placed_at Flat cost, no repeats A cursor parameter Ties on placed_at skip rows
    Keyset on (placed_at, id) with a matching index Flat cost, no repeats, no skips A cursor parameter and one index Old clients still call offset

    The decision

    Field Decision record
    Context Offset paging makes the export slow, repeats rows and would skip rows if orders were removed mid-run.
    Decision Add next_cursor to the list response, keyed by (placed_at, id) with an index on both columns, an opaque token, a server maximum page size, and a limit plus one row to decide the end. Keep offset for the dashboard's first five pages only.
    Consequences, good Export cost per page is flat; a re-run sees each order once; the dashboard keeps its page numbers.
    Consequences, bad Two paging styles for a while; one extra index to maintain on a hot table.
    Revisit when The dashboard needs filters on more columns, so each sort order needs its own index.

    Rollout and verification

    1. Add the index first and measure the write cost on a copy of production traffic.
    2. Ship the cursor beside offset, with the export moved first.
    3. Check completeness by comparing the number of rows exported for a closed window with count(*) for the same window.
    4. Cap the offset on the old endpoint so a deep page cannot hit the table.

    The 2 a.m. failure

    After the switch, finance says some stores are short by a handful of orders. A bulk import stamped hundreds of orders with the same placed_at, and the cursor was built from placed_at alone. First three checks: (1) compare the export's row count with count(*) for a window; (2) group by placed_at and look for groups larger than the page size; (3) read the generated query for the tie-breaker. Mitigation: re-run the export with the row comparison on (placed_at, id). Follow-up: a test that pages through a table with many equal timestamps, as step 6 of the lab does.

    Architect's notes

    • Choose the sort key before the cursor. A unique, immutable, indexed key (a timestamp plus the id) is the whole design.
    • Treat the cursor as a versioned format. Opaque tokens let you add a column to the key later without breaking clients.

    Common mistakes

    • Sorting by a non-unique column only, so rows tied with the last row are skipped without an error.
    • Building the index in the wrong order, so the WHERE and ORDER BY do not match it and the planner sorts.
    • Mixing ASC and DESC with a row comparison, which compares every column the same way.

    Key takeaways

    • OFFSET n makes the server produce the n skipped rows: the lab's plans produced 20 rows at offset 0 and 40,020 at offset 40,000.
    • A keyset query continues after the last row's sort values and, with a matching index, costs the same at every depth (22 page visits at each position in the lab).
    • A cursor is the API contract; a keyset is one way to implement it.
    • A sort key with ties skips rows silently. Add the primary key.
    • Offset repeats or skips rows when the list changes; a keyset does not.
    • Keyset gives up page jumping, free totals and any sort order without its own index.

    Practice exercises

    Exercise 1 (20 min). For an admin table of 300 rows, a public activity feed and a nightly export, choose offset or keyset and say why.

    Exercise 2 (1 hour). Run the lab. In step 6 change the page size to 4 and predict how many rows the naive version skips before you run it.

    Exercise 3 (half day). Add a store_id filter and the matching three-column index, then write the keyset query for a backward page and check it returns the same rows in reverse.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments