QA Interview Hub · Knowledge base · Quizzes · Українська

API › API design: resources, pagination, versioning, GraphQL

Pagination: offset vs cursor

Offset pagination names a position from the start of the list, while cursor pagination names the place after a page's last item. Offset is simple and allows jumping to any page, but it is slow on large offsets, and inserts or deletes shift records and cause duplicates or gaps. Cursor is more stable, but cannot jump to an arbitrary page and needs a unique key in the sort.

API · API design

A user scrolls the payment history: one payment is on two pages, another vanished. Is it a bug?

On a “Transaction history” screen the client taps “more” and the same transfer appears twice. Someone added a record between the two requests and the pages shifted. The server answered both requests “correctly”; the paging scheme itself broke. When a list is not returned whole, the contract gets one more part: how to read the second, the third and the last page.

Below: the two approaches (offset and cursor), why they behave differently, how to test a walk through all pages and what to do with the boundaries.

How it works and why it is designed so

Thousands of records in one response hurt both the server (memory, response time) and the client (parsing, rendering), so collections are returned in portions. There are two main ways to say “which portion”.

Offset pagination: GET /transactions?limit=20&offset=40 or ?page=3&size=20. The client names a position. It is simple to implement, you can jump to any page and show “page 3 of 50”. The price: the database has to walk past all the skipped rows, so a large offset is slow; and the position is counted from the start of the list, so any insert or delete shifts everything after it.

Cursor pagination: GET /transactions?limit=20&cursor=eyJpZCI6MTAyNH0. The server returns nextCursor pointing to the last element of the page, and the next page starts after it. The cursor is usually opaque to the client (often an encoded id plus the sort value), and the client must not parse or invent it. The request becomes “everything after id 1021”, so an index jumps straight there, and inserts before the cursor shift nothing.

offset:  SELECT * FROM tx ORDER BY id DESC LIMIT 20 OFFSET 100000
         -- the database walks past 100000 rows and throws them away
cursor:  SELECT * FROM tx WHERE id < 1021 ORDER BY id DESC LIMIT 20
         -- an index jumps straight to id 1021

What happens if a record is added between the requests

Offset

Sorted newest first. Page 1 (offset=0&limit=3): E, D, C. F is added. Page 2 (offset=3): C, B, A. Record C is shown twice, and the client never saw F.

Cursor

Page 1: E, D, C, cursor “after C”. F is added. Page 2: everything older than C: B, A. No duplicates. F shows up on the next refresh of the first page.

Figure 1. Both approaches are legitimate, but offset does not guarantee a consistent walk over a changing collection. Cursor does, if the order is unambiguous.

A cursor works only with an unambiguous order. If the sort is by createdAt and several records share the same time, the server does not know where it stopped. So a unique key is added to the order: ORDER BY createdAt DESC, id DESC. Without it, records with equal time can get lost on a page boundary.

The shape of the response is also part of the contract. Common variants: a wrapper with items and nextCursor, or a Link header with rel="next" (RFC 8288), where the server returns a ready URL of the next page:

HTTP/1.1 200 OK
Link: <https://api.bank.test/v1/transactions?cursor=eyJpZCI6MTAyMX0>; rel="next"

Check the shape that this API's specification describes, not the one you know from another project.

GET /v1/transactions?limit=3&cursor=eyJpZCI6MTAyNH0 HTTP/1.1
Host: api.bank.test
Authorization: Bearer eyJhbGciOi...

HTTP/1.1 200 OK
Content-Type: application/json

{
  "items": [{ "id": 1023 }, { "id": 1022 }, { "id": 1021 }],
  "nextCursor": "eyJpZCI6MTAyMX0",
  "limit": 3
}

Example: from “the first page works” to a walk over the whole list

Before: the test takes one page and counts the items. It is green even if the third page returns duplicates or nextCursor never becomes empty.

// before: checks one page only
test('transactions: first page', async ({ request }) => {
  const res = await request.get('/v1/transactions?limit=20');
  expect(res.status()).toBe(200);
  expect((await res.json()).items).toHaveLength(20);
});

After: the test walks all pages to the end, collects the ids and compares them with an independent source (a counter, a separate request, or test data the test created itself). The iteration cap is needed so that a “cursor never ends” bug gives an error, not an endless test.

import { expect, type APIRequestContext } from '@playwright/test';

async function walkAll(request: APIRequestContext, path: string) {
  const ids: number[] = [];
  let cursor: string | undefined;
  for (let page = 0; page < 500; page++) {
    const q = new URLSearchParams({ limit: '20' });
    if (cursor) q.set('cursor', cursor);
    const res = await request.get(path + '?' + q);
    expect(res.status()).toBe(200);
    const body = await res.json();
    ids.push(...body.items.map((i: { id: number }) => i.id));
    cursor = body.nextCursor ?? undefined;
    if (!cursor) return ids;
  }
  throw new Error('pagination never ends: nextCursor does not become empty');
}

test('walk all pages: no duplicates, count matches', async ({ request }) => {
  const ids = await walkAll(request, '/v1/transactions');
  expect(new Set(ids).size).toBe(ids.length); // no duplicates
  const total = (await (await request.get('/v1/transactions/count')).json()).total;
  expect(ids).toHaveLength(total); // no gaps
});

The second test reproduces the scenario from the beginning of the article: after the first page we create a record and read the second. For cursor there must be no duplicates. For offset this test will show a duplicate, and that is a documented property of the approach, not a bug: then the test only checks that the server does not fail and returns the documented behaviour.

test('insert between pages does not shift the next page', async ({ request }) => {
  const first = await (await request.get('/v1/transactions?limit=3')).json();
  await request.post('/v1/transactions', { data: { amount: 10, currency: 'UAH' } });
  const second = await (
    await request.get('/v1/transactions?limit=3&cursor=' + first.nextCursor)
  ).json();
  const seen = new Set(first.items.map((i: { id: number }) => i.id));
  for (const item of second.items) expect(seen.has(item.id)).toBe(false);
});

Limits and boundary values

The pagination parameters need negative cases themselves. A quick run:

for q in "limit=0" "limit=-1" "limit=abc" "limit=100000" "cursor=garbage"; do
  echo "== $q"
  curl -s -o /dev/null -w "%{http_code}\n" \
    -H "Authorization: Bearer $TOKEN" "$BASE/v1/transactions?$q"
done
  • limit=0, negative, non-numeric: usually 400 (or 422, depending on the API's distinction), not 500 and not an empty success.
  • limit above the maximum: either 400 or the server silently lowers it to the maximum. Both are legitimate if documented, but the response must say which limit was applied.
  • limit not given: the default applies, not “everything”.
  • The last page: an empty or absent nextCursor (null), not an error. An empty list after the last page gives 200 with an empty array.
  • A forged, corrupted or expired cursor: 400 with a clear reason. A cursor taken from another request (different filter or sort) must not return foreign data. A cursor must not be a way around authorization: the server checks permissions on every request.
  • A filter together with pagination: the cursor is tied to the filter, and changing the filter mid-walk must either reset the walk or give 400.

Limits and alternatives

  • Cursor cannot “jump to page 50” and does not make counting pages easy. If the product needs page numbers (admin panels, tables), offset stays justified, especially for small, almost static lists.
  • total in the response needs a separate COUNT, which is expensive on a large table. That is why some APIs do not return it, or return it approximately. Do not demand an exact total if the contract does not promise it.
  • Keyset (seek) pagination, which cursor is built on, is fast only with an index on the sort fields. Sorting by an arbitrary unindexed field is slow again.
  • In GraphQL the common standard is Relay connections (edges, pageInfo, endCursor); the idea is the same.

Common mistakes

  • Checking only the first page. Duplicates, gaps and an endless cursor are visible only on a walk to the end.
  • Not fixing the data. If other tests or users change the list in parallel, a duplicate can be a real coincidence. Test on a collection the test created itself.
  • Parsing the cursor in the test. It is a private detail of the server, and after an encoding change the test breaks while the contract is intact.
  • Expecting total where it is not promised, and the reverse: not checking that total equals the real count where it exists.

Check yourself

A test takes limit=20, checks 200 and 20 items. Why is that not enough for pagination?

Answer

It sees only the first page. Duplicates between pages, missing records, a cursor that never ends and an error on the last page are visible only on a walk to the end that compares ids with a known set.

Between the first and second page requests someone created a record. Why does offset show a duplicate and cursor does not?

Answer

Offset counts the position from the start of the list, so an insert at the top shifts every element by one, and the last element of page one becomes the first on page two. Cursor says “after this element”, so an insert before the cursor shifts nothing.

The sort is by createdAt and two records have equal time on a page boundary. What can go wrong and how to fix it?

Answer

The server cannot tell whether the second of the two was already returned, so it may skip it or return it twice. The fix: add a unique key to the order, for example createdAt DESC, id DESC, and build the cursor from both fields.

In an interview. Junior: Offset is simple and allows a jump to any page, but it is slow on large offsets and duplicates or skips records on inserts. Cursor is stable and fast, but cannot jump to an arbitrary page. I check the limit boundaries, the last page and the absence of duplicates. Middle/Senior: I walk all pages in an automated test on a collection the test created, compare ids with a known set and cap the iterations so that a cursor that never ends fails the test. For cursor I check an unambiguous order (a unique key in the sort), the reaction to a forged cursor and that the cursor does not bypass authorization.

More articles in this chapter