Foundations · L1API pagination and filtering

API pagination and filtering

Offset and cursor pagination, stable sort orders, filters and page sizes, and why deep offsets get slow on big tables.

L1 Must-knowFoundations17 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 23 Oct 2026 · How we check content
Section 1 of 8

What broke

A made-up story to show a common failure. Not about a real company.

A shop has an admin page for orders. It calls GET /orders?page=1&per_page=50, and the server runs OFFSET (page - 1) * 50. In the first year, the table holds 20,000 orders, and every page loads fast.

Two years later, the table holds 30 million orders. A finance tool walks through all orders every night, page by page. The first pages take a few milliseconds. Page 100,000 takes seconds, and the whole job never ends before morning.

The support team reports a second problem. During a sale, they scroll the list of new orders. Some orders appear twice, and some never appear at all. New orders arrive every second and push the rest down.

The team moves to a cursor that remembers the last order seen. Every page is now fast, and nothing repeats. This story is made up. Slack, however, left offsets for the same two reasons. 4

Section 2 of 8

The idea in simple words

You never return a whole list in one answer. You return it in pages. The REST API lesson explains why to add paging from day one. This lesson is about how to do it well.

There are two main ways.

  • Offset pagination says "skip 40 rows, then give me 20". The client counts positions.
  • Keyset pagination, also called the seek method, says "give me 20 rows after the last one I saw". 2 Most APIs hide the "last one I saw" inside a token called a cursor.

The key idea. An offset remembers a position, and positions move when data changes. A cursor remembers a row, and a row stays where it is.

Section 3 of 8

How it works

Step through two pages of a list, with a new row between them. Use Next and Back, or the ← and → keys.

A new row arrives between page 1 and page 2: offset repeats a row, a cursor does notA · Offset: ?offset=3&limit=3 B · Cursor: ?after=7&limit=3 987654page 1 = 9, 8, 7 · next: offset=3 987654page 1 = 9, 8, 7 · next: after 7 10987654new row 10 goes on top 10987654new row 10 goes on top 765skip 3 rows,take the next 37 is shown twice 654rows olderthan 7✓ no duplicate SeniorPath
  1. Both apps show the newest orders first, 3 per page. Page 1 is orders 9, 8 and 7. A remembers a position: skip 3 next time. B remembers the last order it saw: 7.
  2. Before the user scrolls, a new order, 10, is saved. It goes to the top of the list, so every older order moves down one place.
  3. A asks for rows 4 to 6 by position. Order 7 is now in place 4, so the user sees 7 a second time.
  4. B asks for orders that come after 7 in the sort order. It gets 6, 5 and 4. The new row does not move anything B depends on.
Step 1 of 4

Offset, and why deep pages get slow. In SQL, LIMIT 20 OFFSET 40 skips 40 rows and returns the next 20. PostgreSQL's docs say the skipped rows "still have to be computed inside the server", so a large offset can be slow. 1 Markus Winand shows the same thing. The database must count all rows from the start until it reaches the page, so later pages take longer. 2 Page 1 is cheap. Page 100,000 reads millions of rows to throw them away.

Offsets also drift. When a row is inserted above the reader's position, the next page starts one row too early and repeats a row. When a row is deleted, the next page starts one row too late and skips one. Slack's example: you read 10 messages, 10 new ones arrive, and page two shows the same messages again. 4

Keyset pagination. Instead of a position, send the sort values of the last row. If the list is sorted by created_at DESC, id DESC, the next page is:

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

The (created_at, id) < ($1, $2) part is a row value comparison. With an index on (created_at, id), the database jumps straight to the right place. 2 Deep pages stay fast, while offset pages get slower the further you go. New rows do not move your place, so results stay stable. 2

The cost: you cannot jump to page 7. You can only go next or back, and going back means you reverse the comparison and the sort. 2 There is also no total page count. 4

A stable sort needs a tie-breaker. Many orders share the same created_at. PostgreSQL warns that without an ORDER BY that gives a unique order, you get an unpredictable subset of rows. Different LIMIT and OFFSET values can even give inconsistent results. 1 So always end the sort with a unique column, usually the primary key. Winand's advice is the same: add a unique column and extend the index. 2 This applies to offsets and cursors alike.

Opaque cursors. Do not ask clients to build the cursor from raw fields. Encode it, and say in the docs that clients must not read it. Slack's cursors are Base64 text. One decodes to user:W07QCRPA4, which means "start after this user". 4 Slack also shows how one cursor could hold a position for each shard when data is spread over shards. 4 Clients never read the cursor, so they would not see that change. Google's AIP-158 says page tokens must be opaque and must not be user-parseable. Plain Base64 is not enough to hide what is inside, so Google says to do more than that. It also says a token only marks where to continue. It never grants access, so check permissions on every request. 9

Cursors can expire. Slack tells clients not to keep cursors for hours or days. 5 Google says tokens may expire after a reasonable time and suggests about three days. 9

Filtering and sorting. Filters and sort order are query parameters, for example GET /orders?status=paid&sort=-created_at. Our advice: only allow sorts that have an index. Without one, each page may need to sort the whole table. Google says the other parameters must stay the same while a client follows page tokens, and the API should return an error if they change. Only the page size may change. 9 Put the filter and sort inside the cursor too, so the server can check them.

Page size limits. Always cap the page size. Google says the page size must be optional. If it is too large, the API should lower it to the maximum, and a negative size is an error. 9 Stripe's limit goes from 1 to 100, with a default of 10. 6 Slack recommends 100 to 200 results and allows at most 1,000. 5 A page can hold fewer items than the limit and still have more after it. So clients must check the "more" signal, not the item count. 5 9

Total counts are expensive. "Page 3 of 912" needs an exact count. In PostgreSQL, count(*) must walk through all rows to check which ones the current transaction can see. Estimates are much faster. 3 Google makes total_size optional, and allows an estimate if the API documents it. 9 GitHub search returns at most 1,000 results per search, at most 100 per page. 8 Ask product: does the screen need "912 pages", or just "more"?

How well-known APIs name things.

  • Stripe: limit, starting_after and ending_before. The answer has data and has_more. The cursor is just an object ID, and lists are newest first. 6
  • GitHub REST: per_page and page, with up to 100 per page on most endpoints. The Link header gives next, prev, first and last URLs. Some endpoints use before and after instead. 7
  • Slack: cursor and limit. The answer has response_metadata.next_cursor, which is empty at the end. 5
  • Google: page_size, page_token and next_page_token. 9

GraphQL. The Relay cursor connections spec is the common pattern. A connection has edges and pageInfo. Each edge has a node and a cursor. You page forward with first and after, and back with last and before. pageInfo has hasNextPage, hasPreviousPage, startCursor and endCursor, and clients should treat cursors as opaque. 10 The spec has no total count. Add totalCount yourself only if you can afford it.

Section 4 of 8

Trade-offs

OptionSpeed on deep pagesStable while rows change?Jump to page 7?Use it when
Offset and limitNo Gets slower as the offset grows. 1No Rows can repeat or be skipped. 4Yes Small admin tables, or lists that rarely change.
Keyset or cursorYes Stays fast on deep pages, with the right index. 2Yes 2No Only next and back.Feeds, logs, exports, public APIs, any large list.
Exact total countNo Must walk the rows. 3Not applicable.Not applicable.Small tables, or when the screen truly needs it.
Estimated or no countYes 3Not applicable.Not applicable.Large tables. Show "more" instead of "page 3 of 912".

Simple rule: use opaque cursors over a unique, indexed sort. Cap the page size. Skip exact counts unless a user really needs them.

Section 5 of 8

At work: how a senior uses this

  • Ask: "How big will this list be in two years?" Design for that size, not for today's.
  • Check every list query with EXPLAIN. Look for a sort that uses an index, not a sort over the whole table.
  • Make sure every sort ends with a unique column. Ask: "What happens when two rows have the same value?"
  • Keep cursors opaque from version one. You can then change what is inside them, for example after sharding.
  • Test with inserts and deletes between page requests. Then count duplicates and gaps.
  • Push back on "page X of Y" for big tables. Offer "load more", or an estimate.
  • For big exports, do not use the public paging API at all. Use a background job or a database snapshot.
Section 6 of 8

With AI

What to ask the agent

"Change this offset-based /orders endpoint to keyset pagination. Sort by created_at DESC, id DESC. Return an opaque cursor that also holds the filters. Add an index for it."

"Write a test that inserts and deletes rows between page 1 and page 2, then checks that no order is repeated or missed."

"Design a Relay connection for orders in GraphQL, with first, after, last and before. Explain how the cursor is built and checked."

What to check yourself

  • The sort ends with a unique column, and the cursor holds every sort column, not only the id.
  • The WHERE comparison matches the sort direction. One flipped < repeats or skips rows.
  • An index matches the filter and sort. Run EXPLAIN on a big table.
  • The server caps the page size, and rejects negative values.
  • The server checks permissions on every page. A cursor is not a key to the data.
  • Agents often add COUNT(*) to every list call. Remove it unless the screen needs it.
Section 7 of 8

Check yourself

1. Your list endpoint uses ORDER BY created_at with OFFSET and LIMIT. Many rows share the same created_at. What can go wrong?

Show answer

Rows with the same time can come back in a different order, so pages can repeat or skip them. Add a unique column like id to the sort. PostgreSQL says LIMIT needs an ORDER BY that gives a unique order, or you get an unpredictable subset of rows.

2. Why does ?offset=500000&limit=20 get slow on a big table?

Show answer

The database still has to produce the 500,000 skipped rows before it returns 20. PostgreSQL's docs say rows skipped by OFFSET still have to be computed inside the server.

3. Why should a cursor be opaque, instead of a plain id the client builds?

Show answer

You can change what is inside it later without breaking clients, because they never read it. Google AIP-158 says tokens must not be user-parseable, and the Relay spec says clients should treat cursors as opaque. Slack shows how one cursor could hold a position for each shard.

4. In the Relay spec, which fields must a connection type have?

Show answer

edges and pageInfo The spec says connection types must have fields named edges and pageInfo. data and has_more are Stripe's names.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 10 sources and related lessons
  1. PostgreSQL documentation, section 7.6: LIMIT and OFFSET (opens in a new tab)
    Why LIMIT needs a unique ORDER BY, and why rows skipped by OFFSET still cost work.
  2. Markus Winand, “Paging Through Results”, Use The Index, Luke! (opens in a new tab)
    The seek method with row values, the index it needs, and its limits.
  3. PostgreSQL wiki, “Slow Counting” (opens in a new tab)
    Why an exact count(*) must walk through the rows, and that estimates are much faster.
  4. Michael Hahn, “Evolving API Pagination at Slack”, Slack Engineering, 2017 (opens in a new tab)
    Why Slack left offsets, what its Base64 cursors hold, and what cursors cannot do.
  5. Slack developer docs, “Pagination” (opens in a new tab)
    The cursor and limit parameters, next_cursor, page size advice, and cursor expiry.
  6. Stripe API reference: Pagination (opens in a new tab)
    limit, starting_after, ending_before and has_more, with object IDs as cursors.
  7. GitHub REST API docs, “Using pagination in the REST API” (opens in a new tab)
    The Link header, per_page and page, and before and after on some endpoints.
  8. Google, AIP-158: Pagination (opens in a new tab)
    Opaque page tokens, page size limits, optional total_size, and keeping the other parameters the same between pages.
  9. GraphQL Cursor Connections Specification (Relay) (opens in a new tab)
    Connections with edges, node, cursor and pageInfo, and the first, after, last and before arguments.

Related: REST API design · B-tree vs LSM-tree · Search systems and inverted indexes · Scaling reads · Sharding and consistent hashing · GraphQL and backend-for-frontend (coming soon)

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper