📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you design pagination for a REST API? Compare offset and cursor (keyset) pagination, describe the response shape you would return (items, next link or cursor, page size limits), explain what returning a total count really costs, and how you keep pages stable while data changes.

API contract for pagination: offset vs cursor, opaque cursors, next links, page size limits, the cost of total counts on SQL Server, and stability under concurrent inserts and deletes.

Mid-Level Coding Intermediate api-design ef-core keyset-pagination pagination sql-server web-api

🎯 Key points

  • Offset (page/pageSize, skip/take) vs cursor/keyset (after a sort key)
  • Offset cost grows with depth (SQL Server reads and discards skipped rows); keyset is an index seek
  • Offset pages shift on insert/delete, causing duplicates and gaps; keyset is stable
  • Cursor is generated by the server and opaque (base64url of last sort key plus id); clients never build it
  • Deterministic sort with a unique tie-breaker (e.g. CreatedAt DESC, Id DESC)
  • Enforce default and maximum page size (e.g. 25 default, 100 max); invalid cursor or limit returns 400 ProblemDetails
  • COUNT(*) on a large filtered set is a second full query; make totals optional or estimated
  • Response shape: items plus one standard way to continue (nextCursor, or a next link built from it), no total by default

⏱ 30-second answer

Offset pagination (?page=3&pageSize=50) is simple and allows jumping to page N, but SQL Server still reads and discards every skipped row, so deep pages get slower, and inserts or deletes shift rows between pages, giving duplicates and gaps.

Cursor (keyset) pagination (?after=eyJ...) remembers the last row's sort key and seeks past it, so every page costs the same and pages stay stable while data changes. The cursor should be opaque and the sort must end in a unique tie-breaker.

I return items plus a next link or nextCursor, enforce a maximum page size, and make total counts optional, because COUNT(*) over a large filtered set is a second query that can cost more than the page itself. The trade-off: cursors can't jump to an arbitrary page.

🗣 Full answer (senior)

How I would answer this in an interview

"There are two main approaches. Offset pagination says 'skip 200, take 50'. It's easy to build with Skip and Take in EF Core, clients understand page numbers, and you can jump to page 9. But on SQL Server OFFSET 200000 ROWS still has to read and throw away 200,000 rows, so page 4,000 is much slower than page 1. And if a row is inserted at the top while someone is paging, everything shifts by one, so they see a duplicate; delete one and they miss a row. Cursor or keyset pagination says 'give me 50 rows after this one'. The server encodes the last row's sort key, say CreatedAt and Id, into an opaque cursor, and the next query is WHERE (CreatedAt, Id) < (@c, @id) ORDER BY CreatedAt DESC, Id DESC, which is an index seek. Every page costs the same and concurrent inserts don't shift anything.

For the contract I return a small envelope: the items, and either a next link or a nextCursor, plus hasMore. The cursor is base64-encoded JSON or similar, so clients don't build it themselves and I can change its contents later. I enforce a default page size, like 25, and a hard maximum, like 100, because an unbounded pageSize=100000 is a denial-of-service vector. And I don't return a total count by default. On a big filtered table, COUNT(*) is a second query that scans the same rows, and I've seen the count take longer than the page itself. If the UI needs it, it's an opt-in includeTotal=true, or an estimate.

The mistake I see is offset pagination on an API that feeds a sync job or infinite scroll. That's exactly where you need cursors: the client walks the whole set, deep pages are guaranteed, and data changes during the walk. My rule is offset for small admin grids where people jump to a page, cursor for everything else."


Offset vs cursor

Offset (page, pageSize) Cursor / keyset (after, limit)
Query ORDER BY ... OFFSET @skip ROWS FETCH NEXT @take ROWS ONLY WHERE (key) < (@last) ORDER BY key FETCH NEXT @take
Cost of page N Grows with N (reads skipped rows) Constant (index seek)
Stable under inserts/deletes No: duplicates and gaps Yes
Jump to page N Yes No (only next/previous)
Total count Usually expected Usually omitted
Fits Small admin grids, reports with page numbers Feeds, sync, exports, infinite scroll, large tables

Response shape

{
  "items": [ { "id": 981, "createdAt": "2026-11-19T22:14:03+00:00", "total": { "amount": 120.50, "currency": "AUD" } } ],
  "nextCursor": "eyJjIjoiMjAyNi0xMS0xOVQyMjoxNDowMyswMDowMCIsImkiOjk4MX0",
  "hasMore": true,
  "links": { "next": "/v1/orders?limit=25&after=eyJjIjoi..." }
}

Rules I standardise

Rule Value
Default page size 25
Maximum page size 100 (400 with ProblemDetails above it, or clamp and document)
Sort Allow-listed fields, always ending with a unique id
Cursor Opaque, versioned, optionally signed; tied to the sort and filter it was issued for
Totals Opt-in, or estimated for very large sets

Production example

An orders list on Azure SQL with [40 million] rows used offset paging. Page 1 took 30 ms; a partner sync walking to page 8,000 took 4.2 s per page and timed out. Moving to keyset pagination on an index (CustomerId, CreatedAt DESC, Id DESC) made every page about 25 ms, and dropping the default COUNT(*) halved DTU usage on the endpoint.

🔍 What the interviewer is checking

Checks that the candidate understands the performance and correctness trade-offs of pagination and can design a stable, bounded API contract.

Green flags

  • Explains why OFFSET degrades and keyset seeks
  • Insists on a unique tie-breaker and a matching index
  • Uses opaque cursors and enforces page size limits
  • Treats total counts as a cost, not a default

Red flags

  • Pages in memory after loading everything
  • No maximum page size
  • Unaware of duplicates and gaps with offset paging under writes
  • Exposes raw database ids as the paging contract without thinking

📚 Learn in depth

1. Why OFFSET gets slower

SQL Server has no way to jump to row 200,001 of an ordered result. It walks the index (or sorts) and counts rows until it has skipped @skip, then returns @take.

index (CreatedAt DESC, Id DESC)
[row 1][row 2] ... [row 200,000][row 200,001 ... 200,050]
 └──────── read and discarded ───────┘└── returned ──┘

Logical reads grow linearly with the offset. With SET STATISTICS IO ON you'll see page 1 do a handful of reads and page 4,000 do thousands.

2. Keyset seek

Keyset pagination turns "skip N" into "start after this key". With a composite key the predicate is:

WHERE CreatedAt < @c OR (CreatedAt = @c AND Id < @id)
ORDER BY CreatedAt DESC, Id DESC
OFFSET 0 ROWS FETCH NEXT @take ROWS ONLY;

With an index on (CreatedAt DESC, Id DESC) (or the filter column first, e.g. CustomerId), SQL Server seeks straight to the boundary. SQL Server doesn't support row-value comparisons like (a, b) < (x, y), so you write the expanded OR form; EF Core translates it fine from LINQ.

The tie-breaker matters. If you sort only by CreatedAt and two rows share a timestamp, a page boundary between them loses or repeats a row. Always end the sort with a unique column.

3. Stability under change

Offset, page size 3. Rows: A B C | D E F
Client reads page 1 → A B C
New row Z inserted at top: Z A B | C D E
Client reads page 2 → C D E   (C duplicated)

Keyset: page 1 → A B C, cursor = C
Z inserted at top
page 2 → after C → D E F     (no duplicate)

Keyset isn't a snapshot: rows inserted behind the cursor are simply not seen in this walk. For sync APIs that need completeness, pair keyset with a change feed (updatedAfter with a high-water mark, or SQL Server change tracking).

4. Designing the cursor

  • Opaque: base64url of a small JSON { "v":1, "c":"2026-11-19T22:14:03Z", "i":981 }. Clients treat it as a token.
  • Versioned so you can change sort columns later.
  • Bound to the query: include a hash of filter and sort, and return 400 if a client reuses a cursor with different filters.
  • Optionally signed (HMAC or the Data Protection API) if you don't want clients tampering with it. It's not a security boundary: authorisation still applies on every query.

5. What totals cost

COUNT(*) with the same WHERE must touch every qualifying row (or index entry). For "orders for this customer" with an index that's cheap; for "all orders where Status = 'Open' and text contains 'x'" it's a scan. Options:

Option Cost Accuracy
No total, hasMore only (fetch limit + 1) Free Enough for infinite scroll
Opt-in includeTotal One extra query when asked Exact
Estimate from sys.dm_db_partition_stats or cached counts Very cheap Approximate
Cap: "1,000+" Count with TOP 1001 Exact up to the cap

6. Previous page

Keyset can go backwards by reversing the comparison and the sort, then reversing the results in memory. Many APIs simply don't offer prev; infinite scroll rarely needs it.

Try it yourself

  1. Load 5 million rows into a table, run OFFSET 10 ROWS and OFFSET 4000000 ROWS with SET STATISTICS IO, TIME ON, and compare logical reads.
  2. Write the keyset equivalent and check the plan shows an Index Seek.
  3. Remove the Id tie-breaker, insert duplicate timestamps, and reproduce a missing row across pages.
  4. Implement limit + 1 fetching to compute hasMore without a count.
  5. Time COUNT(*) for a selective and a non-selective filter in Query Store.

💻 Code

Cursor-paginated endpoint with an opaque cursor, page size limits and an index-friendly keyset query (EF Core 10).

// Orders/ListOrders.cs
using System.Buffers.Text;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;

namespace Shop.Api.Orders;

public sealed record OrderSummary(int Id, DateTimeOffset CreatedAt, decimal Total);
public sealed record Page<T>(IReadOnlyList<T> Items, string? NextCursor, bool HasMore);

// Opaque, versioned cursor. Clients never parse it.
internal sealed record OrderCursor(int V, DateTimeOffset C, int I)
{
    public string Encode() => Base64Url.EncodeToString(JsonSerializer.SerializeToUtf8Bytes(this));

    public static bool TryDecode(string? value, out OrderCursor? cursor)
    {
        cursor = null;
        if (string.IsNullOrEmpty(value)) return true;           // first page
        try
        {
            cursor = JsonSerializer.Deserialize<OrderCursor>(Base64Url.DecodeFromChars(value));
            return cursor is { V: 1 };
        }
        catch (Exception e) when (e is FormatException or JsonException) { return false; }
    }
}

public static class ListOrdersEndpoint
{
    private const int DefaultLimit = 25, MaxLimit = 100;

    public static async Task<IResult> Handle(
        int customerId, string? after, int? limit, ShopDb db, CancellationToken ct)
    {
        var take = limit ?? DefaultLimit;
        if (take is < 1 or > MaxLimit)
            return TypedResults.ValidationProblem(new Dictionary<string, string[]>
            { ["limit"] = [$"limit must be between 1 and {MaxLimit}."] });

        if (!OrderCursor.TryDecode(after, out var cursor))
            return TypedResults.ValidationProblem(new Dictionary<string, string[]>
            { ["after"] = ["The cursor is invalid or expired."] });

        var query = db.Orders.AsNoTracking().Where(o => o.CustomerId == customerId);

        if (cursor is not null)
            // Expanded row-value comparison: SQL Server has no (a, b) < (x, y).
            query = query.Where(o => o.CreatedAt < cursor.C
                                  || (o.CreatedAt == cursor.C && o.Id < cursor.I));

        var rows = await query
            .OrderByDescending(o => o.CreatedAt).ThenByDescending(o => o.Id) // unique tie-breaker
            .Take(take + 1)                                                   // +1 tells us hasMore, no COUNT(*)
            .Select(o => new OrderSummary(o.Id, o.CreatedAt, o.Total))
            .ToListAsync(ct);

        var hasMore = rows.Count > take;
        if (hasMore) rows.RemoveAt(rows.Count - 1);

        var next = hasMore ? new OrderCursor(1, rows[^1].CreatedAt, rows[^1].Id).Encode() : null;
        return TypedResults.Ok(new Page<OrderSummary>(rows, next, hasMore));
    }
}
-- The index that makes every page a seek.
CREATE INDEX IX_Orders_Customer_Created_Id
    ON dbo.Orders (CustomerId, CreatedAt DESC, Id DESC)
    INCLUDE (Total);

⚠ Common mistakes

  • Mistake: Offset pagination for sync jobs, exports or infinite scroll. Why it is wrong: Deep pages get linearly slower and inserts cause duplicates and gaps. Instead: Use keyset pagination with a cursor.
  • Mistake: Sorting by a non-unique column only. Why it is wrong: Rows with equal keys at a page boundary are lost or repeated. Instead: Always append a unique tie-breaker such as Id.
  • Mistake: No maximum page size. Why it is wrong: pageSize=1000000 loads the table into memory and is an easy denial of service. Instead: Default 25, maximum 100, validated with a ProblemDetails 400.
  • Mistake: Returning a total count on every request. Why it is wrong: COUNT(*) is a second query that can be slower than the page. Instead: Fetch limit + 1 for hasMore; make totals opt-in or estimated.
  • Mistake: Exposing raw keys as the cursor (?afterId=981) or letting clients construct cursors. Why it is wrong: Clients couple to your sort columns and you can't change them later. Instead: The server generates opaque, versioned base64url cursors; clients only echo them back.
  • Mistake: Throwing a 500 when a cursor can't be decoded. Why it is wrong: A malformed, tampered or stale cursor (issued before a sort change, or for different filters) is a client error, and a 500 pages your on-call. Instead: Return 400 ValidationProblem for the after parameter with a clear message to restart from the first page; include a version and a filter hash in the cursor so you can detect mismatches.
  • Mistake: Returning both a next link and a nextCursor that can disagree, with no documented rule. Why it is wrong: Clients don't know which to trust. Instead: Pick one primary mechanism in your API guidelines; if you return a link, build it from the cursor so they're always consistent.
  • Mistake: Paging in memory after ToListAsync(). Why it is wrong: The whole result set is loaded before slicing. Instead: Apply Where, OrderBy and Take on IQueryable so they run in SQL.
  • Mistake: Keyset pagination without a matching index. Why it is wrong: The predicate can't seek, so you get a scan plus sort on every page. Instead: Index the filter column then the sort columns in the same direction.

🏛 Senior insight: trade-offs

Pagination is a contract decision you make once and live with. Switching a public API from offset to cursor later is a breaking change, so I default to cursors for anything that could grow or be walked by a machine, and keep offset for small human-facing grids. The thing that surprises teams is the count: product asks for "showing 1-25 of 3,482,119" and nobody notices it doubles database load until the DTU graph does.

Option When it fits Cost When not to
Offset + total Admin grids under ~100k rows, jump-to-page UX Deep pages slow; shifting rows Feeds, sync, exports
Keyset cursor, no total Feeds, partner sync, mobile infinite scroll No random access; cursor design Users need page numbers
Keyset + opt-in total Large lists with occasional "how many?" Extra query when requested Totals over expensive filters on every call
Change feed (updatedSince + high-water mark) Incremental sync of a whole dataset Needs reliable modified timestamps or change tracking Interactive browsing

I measure with Query Store (duration and logical reads per page) and with Application Insights dependency timings for the count query.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions implementing keyset pagination in EF Core Why: Checks the EF Core implementation detail: composite keys, stable order and the generated SQL.
    How to answer

    Skip(n).Take(20) becomes OFFSET n ROWS FETCH NEXT 20 ROWS ONLY. SQL Server still reads and discards the n skipped rows, so page 5,000 reads about 100,000 rows to return 20, and rows shift when new data arrives. Keyset pagination remembers the last row's sort key and asks for rows after it: WHERE CreatedAt < @lastCreatedAt OR (CreatedAt = @lastCreatedAt AND Id < @lastId) with ORDER BY CreatedAt DESC, Id DESC. With an index on (CreatedAt DESC, Id DESC) that is a seek reading only 20 rows, so every page costs the same. The API returns an opaque cursor instead of a page number. The trade-off: keyset can't jump to page N or show a total cheaply, so it suits feeds, APIs and exports, while offset stays fine for shallow, numbered admin grids.

  2. When: Candidate says cursors can only go forward Why: Checks the candidate can implement previous-page navigation with keyset paging.
    How to answer

    Return two cursors per page: prevCursor from the first row's key and nextCursor from the last. For the previous page, flip the comparison to rows before the first key (CreatedAt > @c OR (CreatedAt = @c AND Id > @i) for a newest-first list), flip the ORDER BY to ascending, Take(limit + 1) to know whether an earlier page exists, then reverse the rows in memory so they display newest first. Duplicate sort values are handled by the unique tiebreaker (Id) in both the predicate and the ORDER BY; without it, rows sharing a timestamp at the page edge are skipped or repeated. The same (CreatedAt DESC, Id DESC) index serves both directions because SQL Server can scan a B-tree backwards, so each page is still one seek plus limit + 1 rows.

  3. When: Candidate discusses filters and sort parameters in the query string Why: Checks query string design for filters, arrays and encoding alongside paging.
    How to answer

    The query string shapes a collection: filters, sorting, paging and field selection, while the path holds identity. Pick conventions and apply them everywhere: repeated keys for arrays (?status=open&status=held, which ASP.NET Core binds to string[] natively), explicit range names (createdFrom, createdTo) with ISO 8601 values, and allow-listed sort and filter fields so nothing raw reaches SQL.

    Values must be percent-encoded, and URLs have practical limits: Kestrel caps the request line at 8 KB, IIS defaults maxQueryString to 2,048 characters, and proxies vary. URLs are logged everywhere, so never put personal data or secrets in them. When criteria get large, complex or sensitive, use POST /orders/search with a body. The trade-off: GET is cacheable and bookmarkable; POST handles big or private criteria but loses caching.

🛠 Real-world problems: how you handle them

Partner sync timing out on deep offset pages
Situation
A B2B orders API on Azure SQL (Australia East) with [40 million] orders. A partner's nightly job walked `GET /orders?page=N&pageSize=500` from page 1 to the end to sync everything.
Signals
Application Insights showed request duration climbing with the page number, from 40 ms to over 30 s, then 504s from Front Door after page [6,000]. Azure SQL DTU hit 100% every night between 01:00 and 03:00. The partner reported missing and duplicate orders in their system.
Investigation
Query Store showed one query with logical reads growing linearly; the execution plan had a Clustered Index Scan plus Sort, with OFFSET applied after. A second query, `COUNT(*)` for the total, ran on every page and cost as much as the page. Comparing the partner's data with ours showed duplicates matched orders created during the sync window.
Resolution
Immediate: removed the per-page count (made it opt-in) and added an index on `(CreatedAt DESC, Id DESC)`, which halved the load. Real fix: added a cursor endpoint `GET /v1/orders?after=&limit=` with an opaque cursor plus an `updatedSince` change feed for incremental sync, and moved the partner to it.
Prevention
API guidelines now require cursor pagination for collections that can exceed [10,000] items, a maximum page size of 100, and no default totals. A load test walks 10,000 pages and asserts flat latency; Query Store regressions alert on logical reads.

How to tell it (STAR)

**S:** A partner's nightly sync paged through [40 million] orders with page numbers; by page six thousand each call took 30 seconds and timed out, and they had duplicate orders. **T:** I was asked to make the sync reliable without breaking other clients. **A:** I used Query Store to show the offset scan and the count query doubling the work, made totals opt-in, added a covering index, then designed a cursor endpoint with an opaque cursor and an `updatedSince` feed and worked with the partner to switch over. **R:** Page latency went flat at about [25 ms], the sync dropped from [3 hours] to [12 minutes], DTU peaks fell by [60]%, and duplicates stopped.

↩ Usually asked after

More in API Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me