Back to all posts
·8 min read

Keyset pagination: using a cursor instead of OFFSET for large lists

When a list screen is first written, it almost always starts the same way: page and pageSize parameters, with OFFSET and LIMIT underneath. While the table holds a few thousand rows, this approach causes no trouble at all. As the data grows, as the list turns into a constantly updated feed, or as the same endpoint starts feeding the infinite scroll of a mobile app, two complaints show up: later pages get slow, and users see some records twice and others not at all.

In this post I describe the common root of these two problems and the solution I use for them: keyset (cursor-based) pagination. The examples use ASP.NET Core, EF Core and PostgreSQL, but the idea is the same whichever database you use.

Why does OFFSET get slow, and why does it drift?

When you write OFFSET 10000 LIMIT 20, the database produces 10,020 rows in sorted order, throws away the first 10,000 and returns the remaining 20. Even with a suitable index, every skipped row still has to be read. The cost of the query grows linearly with the page number; the first page takes milliseconds while the hundredth is noticeably slower.

The second problem is about correctness. If a new record is added to the top of the list while the user is reading the first page, every row shifts by one when the second page is requested. The last record of the first page shows up again at the top of the second page. Conversely, if a record is deleted, a row disappears in between without ever being shown. OFFSET says "start from row number N"; what the user actually wants is "continue after the last record I saw".

The keyset idea: continue from the last key seen

Keyset pagination expresses position not as a row count, but as a value of the sort key. If the list is sorted from the newest order to the oldest, for the next page we say "give me the orders older than the last order on the previous page":

SELECT id, created_at, customer_id, total
FROM orders
WHERE (created_at, id) < (@last_created_at, @last_id)
ORDER BY created_at DESC, id DESC
LIMIT 21;

With the right index, this query seeks directly to the relevant point in the index and reads only 21 rows from there. There is no meaningful cost difference left between the first page and the thousandth. New records being inserted are not a problem either, because the boundary is a fixed value, not a row number. New records land on the other side of the boundary, and the user does not see rows they have already seen.

LIMIT 21 is a deliberate choice: with a page size of 20, we ask for one extra row and check whether the 21st exists to answer "is there a next page?" without running a separate COUNT query.

The sort key must be unique

The most common keyset mistake is paginating on created_at alone. When two records with the same timestamp fall on a page boundary, the condition created_at < @last skips one of them; with <=, the same record comes back twice instead. The fix is to add a tie-breaker that makes the ordering unique. Usually this is the primary key.

Sorting and comparison must use the same columns in the same direction. If the order is ORDER BY created_at DESC, id DESC, the comparison must be (created_at, id) < (...). An ordering with mixed directions (for example date descending, name ascending) cannot be expressed with a row value comparison; in that case you have to write the condition out explicitly.

The index must also match the query exactly:

CREATE INDEX ix_orders_created_at_id
    ON orders (created_at DESC, id DESC);

If the list has a fixed filter (for example, the orders of a particular customer, or a tenant), the equality filter column goes first in the index: (customer_id, created_at DESC, id DESC). Checking the query plan with EXPLAIN and seeing that there is no separate sort step and the index is used directly is the real verification of this work.

Implementing it with EF Core

On the EF Core side, writing the condition out explicitly is both readable and translates safely to SQL across different providers:

public sealed record OrderCursor(DateTimeOffset CreatedAt, Guid Id);

public async Task<Page<OrderDto>> GetOrdersAsync(
    OrderCursor? after, int pageSize, CancellationToken ct)
{
    var query = db.Orders.AsNoTracking();

    if (after is not null)
    {
        query = query.Where(o =>
            o.CreatedAt < after.CreatedAt ||
            (o.CreatedAt == after.CreatedAt && o.Id.CompareTo(after.Id) < 0));
    }

    var items = await query
        .OrderByDescending(o => o.CreatedAt)
        .ThenByDescending(o => o.Id)
        .Take(pageSize + 1)
        .Select(o => new OrderDto(o.Id, o.CreatedAt, o.CustomerId, o.Total))
        .ToListAsync(ct);

    var hasMore = items.Count > pageSize;
    if (hasMore) items.RemoveAt(items.Count - 1);

    var next = hasMore
        ? new OrderCursor(items[^1].CreatedAt, items[^1].Id)
        : null;

    return new Page<OrderDto>(items, next);
}

The point to watch here is that the cursor is always produced from the last item returned, not from the extra 21st row. Also, if Id is a Guid, keep in mind that the database and .NET may not order GUIDs the same way. As long as the comparison happens entirely in SQL there is no problem; but if you try to re-sort cursor values in memory, inconsistencies can appear. Time-sortable identifiers or integer keys make this simpler.

Moving the cursor into the API contract

Asking the client to send created_at and id separately leaks an internal sorting detail into the contract. When you later want to change the ordering, you affect every client. Instead, I expose the cursor as an opaque string: the server creates it, the client sends it back as is.

public static class CursorCodec
{
    public static string Encode(OrderCursor c) =>
        Base64Url.EncodeToString(JsonSerializer.SerializeToUtf8Bytes(c));

    public static OrderCursor? Decode(string? value)
    {
        if (string.IsNullOrEmpty(value)) return null;
        try
        {
            var bytes = Base64Url.DecodeFromChars(value);
            return JsonSerializer.Deserialize<OrderCursor>(bytes);
        }
        catch (Exception ex) when (ex is FormatException or JsonException)
        {
            throw new InvalidCursorException();
        }
    }
}

The response shape stays simple too: items and nextCursor. If nextCursor is empty, the list has ended. When a malformed or undecodable cursor arrives, returning a 400 is better than silently falling back to the first page; otherwise the client can end up in an endless loop.

Although the cursor is opaque, it is not secret; Base64 is not encryption. Put only the sort values in it. If you want to make sure the filters (for example a status or a search term) are compatible with the cursor, you can add a digest of the filters to the cursor and compare it when the request comes in. Applying an old cursor to a new query after the user changes the filter is the easiest way to silently produce wrong results. From an authorization standpoint, the cursor is only position information; which records the user is allowed to see must be enforced separately on every request.

The cost of keyset: what do you give up?

Keyset is not the right choice for every list. The most obvious loss is jumping to an arbitrary page. "Go to page 47" requires knowing the boundary values of the previous 46 pages. For infinite scroll, a "load more" button, API consumers and export jobs this is not a shortcoming; for an admin panel navigated with numbered pages, it may be. On such screens, deliberately keeping OFFSET for small, well-filtered data sets is a reasonable decision.

The total record count is a separate topic. On large tables an exact COUNT(*) is expensive and can take back what keyset gained. If users do not need an exact number, do not show it; if they do, serving it from a separate endpoint with caching works better.

Navigating backwards is done by reversing the comparison direction and the sort order, then flipping the result back in memory. Most of the time this is not needed; the client is usually already holding the previous pages.

Testing that it works correctly

Keyset bugs rarely show up with normal data; they appear at the edges. That is why, in integration tests against a real database, I specifically try these scenarios:

  • Many records with the same created_at value falling exactly on a page boundary. After walking through all pages, every record must have been seen exactly once.
  • A new record inserted at the top of the list between pages. No previously seen record should come back.
  • The last page containing exactly page-size records. nextCursor must come back empty, and no empty extra page should be requested.
  • Sending a malformed, truncated or other-filter cursor. The response should be a clear 400.

Writing the first scenario as a general test helper, "walk all pages, collect the ids, verify there are no duplicates or gaps", gives you a reusable safeguard for every keyset endpoint added later.

Closing

Keyset pagination is not a new technology; it is the result of expressing position with the right thing: not with a row count, but with the key of the last record the user saw. A unique sort key, an index that matches the query exactly, an opaque cursor and a few tests aimed at the edge cases are enough to make large lists both fast and consistent. Keeping OFFSET where numbered pages are genuinely needed is part of the same decision; what matters is choosing the default by looking at how the list is used, not out of habit.