Skip to content

10.7 — Pagination, Filtering and Sorting Conventions

← Roadmap · Section: 10. Web API Design and REST Prev: 10.6 API versioning · Next: 10.8 ProblemDetails

Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —


TL;DR

Pagination is returning a collection in chunks so one request cannot pull a million rows.

  • Offset pagination (?page=2&pageSize=20) — simple, jumpable, but slow on deep pages and skips or duplicates rows when the data changes underneath.
  • Cursor pagination (?after=<token>) — stable and fast at any depth, but no "jump to page 47".
  • Always cap the page size server-side. ?pageSize=1000000 must not be a denial-of-service vector.

Definitions

Term What it is What it means
Pagination a technique Returning a large collection in chunks.
Offset pagination a strategy Skip N rows, take M. Skip() / Take() in LINQ.
Cursor pagination a strategy "Give me the rows after this marker." Also called keyset pagination.
Cursor / continuation token an opaque string Encodes where the previous page ended.
Page size a parameter How many items per page. Must be capped.
Envelope a response shape An object wrapping the items plus metadata.
Link header an HTTP header (RFC 8288) Next/prev/first/last page URLs, outside the body.
IQueryable<T> an interface A query not yet executed — so filters compose into one SQL statement.
Deferred execution a LINQ behaviour The query runs when enumerated, not when built.
Stable sort a requirement A total ordering, so equal values never reshuffle between pages.

The concept

GET /orders on a table with two million rows is a problem for everyone: the database scans, the server buffers, the network carries megabytes, and the client parses data it will never show.

Pagination bounds the damage. The interesting part is which pagination, because the two strategies fail in different ways.

The analogy

Offset pagination is telling a librarian "skip the first 40 books and give me the next 20". If someone shelves a new book while you read page 2, everything shifts by one — and the book that was first on page 3 is now last on page 2. You never see it.

Cursor pagination is a bookmark: "start from the book after this one". Insertions elsewhere do not move your place.

⚠️ That skipped-row problem is not theoretical. On any actively-written table — orders, events, messages — offset pagination silently drops and duplicates rows for anyone paging through it. Most teams never notice because nobody audits it, and it is precisely the kind of thing an interviewer is probing for.


How it works

Offset pagination

GET /api/orders?page=2&pageSize=20
var items = await query
    .OrderByDescending(o => o.CreatedUtc)
    .Skip((page - 1) * pageSize)
    .Take(pageSize)
    .ToListAsync(ct);
✅ ⚠️
Trivial to implement Deep pages are slow — the database still walks the skipped rows
Jump to any page Rows shift when data changes between requests
Total count available COUNT(*) is a second query, and it is expensive

⚠️ OFFSET 100000 genuinely reads 100,020 rows and throws 100,000 away. Page 1 is instant and page 5000 times out — the classic "our API is fast except for that one report" bug.

Cursor pagination

GET /api/orders?first=20
GET /api/orders?first=20&after=eyJjIjoiMjAyNi0wMy0wMSIsImkiOjQyfQ
// "Everything ordered after this exact point" — an index seek, not a scan
var items = await query
    .Where(o => o.CreatedUtc < cursor.CreatedUtc
             || (o.CreatedUtc == cursor.CreatedUtc && o.Id < cursor.Id))
    .OrderByDescending(o => o.CreatedUtc)
    .ThenByDescending(o => o.Id)
    .Take(pageSize + 1)              // +1 to detect whether there is another page
    .ToListAsync(ct);
✅ ⚠️
Constant time at any depth — index seek No page numbers. Cannot jump to page 47
Stable — no skips or duplicates Total count usually not offered
Ideal for infinite scroll and feeds The sort column must be part of the cursor

The tie-breaker in the Where clause is the part people get wrong. CreatedUtc alone is not unique — two orders in the same millisecond would either both be skipped or both repeat. Including Id makes the ordering total, which is what a cursor requires.

Choosing

Situation Strategy
Admin table with page numbers Offset
Infinite scroll / feed Cursor
Data changes constantly Cursor
Millions of rows, deep paging Cursor
Small stable dataset Offset — do not over-engineer
Public API for unknown clients Offset, capped, with cursor as an option

⚠️ "Cursor is better" is not the right answer. For an admin screen showing 200 audit records, offset is simpler and users genuinely want page numbers. The answer that lands is why you would switch: the data is hot, or the pages get deep.

The response shape

Envelope — metadata in the body:

{
  "items": [ … ],
  "page": 2,
  "pageSize": 20,
  "totalCount": 4823,
  "totalPages": 242
}

Headers — body stays a clean array:

X-Total-Count: 4823
Link: </api/orders?page=3&pageSize=20>; rel="next",
      </api/orders?page=242&pageSize=20>; rel="last"

⚠️ Pick one and use it everywhere. Mixing shapes across endpoints is the actual problem; either is defensible on its own. The envelope is easier for JavaScript clients (no header parsing, and CORS hides custom headers unless you set Access-Control-Expose-Headers (10.10)). The Link header is more RESTful and keeps the body a plain array.

⚠️ Adding an envelope to an existing array-returning endpoint is a breaking change — clients doing response[0] break (10.6).

The deeper detail — filtering and sorting

GET /api/orders?status=pending&minTotal=100&createdAfter=2026-01-01&sort=-createdUtc,customerName

The - prefix for descending is a common convention: sort=-createdUtc is descending, sort=customerName ascending.

⚠️ Sorting by a client-supplied column name is an injection risk if done naively. Never interpolate it into SQL, and never pass it to a dynamic-LINQ library unchecked. Allowlist it:

private static readonly Dictionary<string, Expression<Func<Order, object>>> Sortable = new()
{
    ["createdUtc"]   = o => o.CreatedUtc,
    ["total"]        = o => o.Total,
    ["customerName"] = o => o.Customer.Name,
    ["status"]       = o => o.Status
};
// Anything not in this dictionary is rejected with 400. No exceptions.

⚠️ Allowing arbitrary sort columns is also a performance problem even when it is safe — sorting by an unindexed column turns every page into a full table sort (14.2).

⚠️ And an unstable sort corrupts pagination. Sorting only by Status — where thousands of rows share a value — lets the database return them in any order it likes, differently on each query. Rows appear on two pages and others vanish. Always append a unique tie-breaker, usually the primary key.

⚠️ Filters must compose on IQueryable, not on a materialised list. Calling ToListAsync() before filtering pulls the whole table into memory first — the query looks correct and the server falls over (13.10).


Code

The request model, with the cap enforced in the type itself:

public sealed record OrderQuery
{
    [Range(1, int.MaxValue)]
    public int Page { get; init; } = 1;

    private const int MaxPageSize = 100;
    private int _pageSize = 20;

    public int PageSize
    {
        get => _pageSize;
        // ⚠️ Clamped in the setter, not merely validated. Even a caller that
        // constructs this object directly cannot exceed the cap.
        init => _pageSize = Math.Clamp(value, 1, MaxPageSize);
    }

    public string? Status { get; init; }
    public decimal? MinTotal { get; init; }
    public DateTime? CreatedAfter { get; init; }
    public string Sort { get; init; } = "-createdUtc";
}

The service:

public async Task<PagedResult<OrderSummaryDto>> SearchAsync(OrderQuery q, CancellationToken ct)
{
    // IQueryable — nothing has hit the database yet
    IQueryable<Order> query = _db.Orders.AsNoTracking();

    // Each filter appends to the SAME SQL statement, applied only if supplied
    if (!string.IsNullOrWhiteSpace(q.Status))
        query = query.Where(o => o.Status == q.Status);

    if (q.MinTotal is { } min)
        query = query.Where(o => o.Total >= min);

    if (q.CreatedAfter is { } after)
        query = query.Where(o => o.CreatedUtc >= after);

    // ⚠️ COUNT before Skip/Take, and it is a SECOND round trip.
    // On a big table this is often slower than the page query itself.
    var totalCount = await query.CountAsync(ct);

    query = ApplySort(query, q.Sort);

    var items = await query
        .Skip((q.Page - 1) * q.PageSize)
        .Take(q.PageSize)
        .Select(o => new OrderSummaryDto      // project in SQL — never load full entities
        {
            Id           = o.Id,
            Reference    = o.Reference,
            CustomerName = o.Customer.Name,
            Total        = o.Total,
            CreatedUtc   = o.CreatedUtc
        })
        .ToListAsync(ct);

    return new PagedResult<OrderSummaryDto>(items, q.Page, q.PageSize, totalCount);
}

private static IQueryable<Order> ApplySort(IQueryable<Order> query, string sort)
{
    var descending = sort.StartsWith('-');
    var field = descending ? sort[1..] : sort;

    // Allowlist. An unknown field is a 400, never a dynamic expression.
    query = field switch
    {
        "createdUtc"   => descending ? query.OrderByDescending(o => o.CreatedUtc)
                                     : query.OrderBy(o => o.CreatedUtc),
        "total"        => descending ? query.OrderByDescending(o => o.Total)
                                     : query.OrderBy(o => o.Total),
        "customerName" => descending ? query.OrderByDescending(o => o.Customer.Name)
                                     : query.OrderBy(o => o.Customer.Name),
        _ => throw new ValidationException($"Cannot sort by '{field}'.")
    };

    // ⚠️ The tie-breaker. Without it, equal values order arbitrarily and rows
    // appear on two pages while others are never returned at all.
    return ((IOrderedQueryable<Order>)query).ThenByDescending(o => o.Id);
}

Cursor pagination, with the encoding:

public sealed record Cursor(DateTime CreatedUtc, int Id)
{
    // Base64 so it reads as opaque. ⚠️ This is ENCODING, not encryption —
    // anyone can decode it. Never put anything sensitive in a cursor.
    public string Encode() =>
        Convert.ToBase64String(JsonSerializer.SerializeToUtf8Bytes(this));

    public static Cursor? Decode(string? token)
    {
        if (string.IsNullOrEmpty(token)) return null;
        try
        {
            return JsonSerializer.Deserialize<Cursor>(Convert.FromBase64String(token));
        }
        catch
        {
            // A malformed cursor is client error, not a 500
            throw new ValidationException("Invalid cursor.");
        }
    }
}

public async Task<CursorPage<OrderSummaryDto>> ListAsync(
    string? after, int first, CancellationToken ct)
{
    first = Math.Clamp(first, 1, 100);
    var cursor = Cursor.Decode(after);

    IQueryable<Order> query = _db.Orders.AsNoTracking();

    if (cursor is not null)
    {
        // The composite comparison — the tie-breaker is what makes this exact
        query = query.Where(o =>
            o.CreatedUtc < cursor.CreatedUtc ||
            (o.CreatedUtc == cursor.CreatedUtc && o.Id < cursor.Id));
    }

    // Fetch one extra to learn whether another page exists — no COUNT needed
    var rows = await query
        .OrderByDescending(o => o.CreatedUtc)
        .ThenByDescending(o => o.Id)
        .Take(first + 1)
        .Select(o => new { o.Id, o.Reference, o.Total, o.CreatedUtc, Customer = o.Customer.Name })
        .ToListAsync(ct);

    var hasMore = rows.Count > first;
    var page = rows.Take(first).ToList();

    var next = hasMore && page.Count > 0
        ? new Cursor(page[^1].CreatedUtc, page[^1].Id).Encode()
        : null;

    return new CursorPage<OrderSummaryDto>(
        page.Select(r => new OrderSummaryDto { /* … */ }).ToList(), next);
}

⚠️ The COUNT query deserves its own note. On a large filtered table it is frequently the slowest part of the request. Options: omit totalCount entirely (cursor style), return an approximation from table statistics, or cap it — SELECT COUNT(*) FROM (SELECT TOP 1001 …) gives you "1000+" cheaply, which is what search engines do.


Interview questions

Q: What is the difference between offset and cursor pagination?

Offset skips N rows and takes M — simple, and it gives you page numbers and a total count. Its two problems are that deep pages are slow, because the database still walks every skipped row before discarding it, and that it is unstable: if rows are inserted or deleted between requests everything shifts, so you silently skip some rows and see others twice. Cursor pagination passes a marker saying where the last page ended and asks for everything after it, which is an index seek and so is constant time at any depth, and it is stable under concurrent writes. The cost is that you lose page numbers and usually the total count.

Q: Which would you use?

It depends on the access pattern. For an admin screen where users want to jump to page 12 and see "4,823 results", offset is right and simpler. For an infinite-scroll feed, or any hot table where people page deeply, cursor. I would not reach for cursor by default — on a small, stable dataset it is over-engineering. The signals that make me switch are deep paging performance and correctness under concurrent writes.

Q: What is the trap with sorting?

Two. First, if the sort column comes from the client you must allowlist it — never interpolate it into SQL or hand it to a dynamic-LINQ helper — and allowing arbitrary columns also means sorting by unindexed ones, which turns every page into a full table sort. Second, the sort has to be total. If you sort only by status and thousands of rows share a value, the database can return them in any order, and a different order on each query, so rows land on two pages while others never appear. Appending the primary key as a tie-breaker fixes it, and it is required for cursor pagination to work at all.

Q: How do you stop a client requesting a huge page?

Cap it server-side and clamp rather than reject — I usually put the clamp in the request model's setter so it holds even for code paths that construct the object directly, not just for bound requests. Without a cap, ?pageSize=1000000 is a denial-of-service vector that costs the caller one request and costs you a full table load plus the serialization. It is worth returning the effective page size in the response so a client that asked for more can tell it did not get it.


Traps ⚠️

  • No page size cap — ?pageSize=1000000 is a DoS vector.
  • Deep offsets are slow — OFFSET 100000 reads and discards 100,000 rows.
  • Offset pagination skips and duplicates rows when data changes mid-paging.
  • Unstable sort corrupts pages. Always add a unique tie-breaker.
  • Client-supplied sort columns without an allowlist — injection and unindexed scans.
  • COUNT(*) is a second query and often the slowest part of the request.
  • Filtering after ToListAsync() loads the whole table into memory.
  • Adding an envelope to an array-returning endpoint is breaking.
  • Custom headers are hidden from browsers without Access-Control-Expose-Headers.
  • A cursor is Base64, not encrypted. Anyone can read it.
  • Page numbers below 1 — Skip(-20) throws.
  • Mixing envelope and header styles across endpoints.


Sources