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.
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.
"There are two main approaches. Offset pagination says 'skip 200, take 50'. It's easy to build with
SkipandTakein EF Core, clients understand page numbers, and you can jump to page 9. But on SQL ServerOFFSET 200000 ROWSstill 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, sayCreatedAtandId, into an opaque cursor, and the next query isWHERE (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 anextlink or anextCursor, plushasMore. 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 unboundedpageSize=100000is 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-inincludeTotal=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 (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 |
{
"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..." }
}
| 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 |
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.
Checks that the candidate understands the performance and correctness trade-offs of pagination and can design a stable, bounded API contract.
Green flags
Red flags
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.
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.
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).
{ "v":1, "c":"2026-11-19T22:14:03Z", "i":981 }. Clients treat it as a token.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 |
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.
OFFSET 10 ROWS and OFFSET 4000000 ROWS with SET STATISTICS IO, TIME ON, and compare logical reads.Id tie-breaker, insert duplicate timestamps, and reproduce a missing row across pages.limit + 1 fetching to compute hasMore without a count.COUNT(*) for a selective and a non-selective filter in Query Store.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);
Id.pageSize=1000000 loads the table into memory and is an easy denial of service. Instead: Default 25, maximum 100, validated with a ProblemDetails 400.COUNT(*) is a second query that can be slower than the page. Instead: Fetch limit + 1 for hasMore; make totals opt-in or estimated.?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.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.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.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.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.
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.
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.
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.
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.
Last updated 23 Nov 2026.