Covers the SQL and cost of Skip/Take offset paging, building keyset (seek) pagination on a composite (CreatedAt, Id) key in EF Core with a matching index, cursor tokens for the API, and when each approach fits.
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.
"Offset paging with
SkipandTakeis the default everyone writes, and EF Core turns it intoOFFSET ... FETCH NEXT. It's fine for the first few pages, but SQL Server has no way to jump to row 100,000: it walks the index in order and throws away everything before the offset. So the cost grows with the page number. It also has a correctness problem: if new orders arrive while someone pages, rows shift and the user sees duplicates or misses items.Keyset pagination, also called seek paging, fixes both. Instead of a page number, the client sends back the sort key of the last row it saw, and the query asks for rows strictly after it in the same order. For newest-first orders I sort by
CreatedAt DESC, Id DESC. TheIdis the tiebreaker, because two orders can share a timestamp, and without a unique column in the ORDER BY the order isn't deterministic. The predicate is 'created before the last one, or created at the same time with a smaller id', and with an index on(CreatedAt DESC, Id DESC)SQL Server seeks straight to the position and reads 20 rows. Page 1 and page 5,000 cost the same. In the API I return the last key as an opaque, base64 cursor and anextCursorfield, so clients can't build their own and I can change the format later.The mistake I see is building keyset paging on a non-unique column, or adding a filter or sort the index doesn't match, which turns the seek back into a scan. And keyset isn't free: you lose jump-to-page and cheap totals. So I use keyset for feeds, mobile infinite scroll, public APIs and exports, and keep offset for admin grids where nobody goes past page ten."
Offset (Skip/Take) |
Keyset (seek) | |
|---|---|---|
| SQL | OFFSET @n ROWS FETCH NEXT @k ROWS ONLY |
WHERE (sort key) < (last key) ... TOP(@k) |
| Cost per page | Grows with depth | Constant with a matching index |
| Stable under inserts | No: rows shift | Yes |
| Jump to page N | Yes | No |
| Total count | Easy (but costs a COUNT) |
Separate query if needed |
| Best for | Shallow numbered grids | Feeds, APIs, exports, infinite scroll |
| Field | Purpose |
|---|---|
limit (request) |
Page size, capped by the server (e.g. max 100) |
cursor (request) |
Opaque token from the previous response; empty for the first page |
items (response) |
The page |
nextCursor (response) |
Present only if there is another page (fetch limit + 1 to know) |
A mobile activity feed [in a system I worked on] used offset paging over about 20 million rows. Deep pages took 2 to 4 seconds and users saw duplicates when new activity arrived. Switching to keyset on (UserId, CreatedAt DESC, Id DESC) made every page take about 5 ms with around 10 logical reads, and the duplicate reports stopped.
Checks that the candidate understands why offset paging degrades, can write correct keyset paging with a composite key and matching index, and can design the API contract around it.
Green flags
limit + 1 for hasMoreRed flags
OrderBySELECT [o].[Id], [o].[CreatedAt], [o].[Total]
FROM [Orders] AS [o]
WHERE [o].[TenantId] = @tenantId
ORDER BY [o].[CreatedAt] DESC, [o].[Id] DESC
OFFSET @p ROWS FETCH NEXT @p0 ROWS ONLY
index (TenantId, CreatedAt DESC, Id DESC)
[row 1][row 2] ... [row 100,000] [row 100,001 ... 100,020]
\_______ read and discarded _______/ \_____ returned _____/
Even with a perfect index, SQL Server must count its way to the offset. Logical reads grow linearly with depth.
For a descending composite sort (CreatedAt DESC, Id DESC) and the last row (c, i), the next page is every row that sorts after it:
SELECT TOP(@limit) [o].[Id], [o].[CreatedAt], [o].[Total]
FROM [Orders] AS [o]
WHERE [o].[TenantId] = @tenantId
AND ([o].[CreatedAt] < @c OR ([o].[CreatedAt] = @c AND [o].[Id] < @i))
ORDER BY [o].[CreatedAt] DESC, [o].[Id] DESC
SQL Server doesn't support row-value comparison (CreatedAt, Id) < (@c, @i), so the expanded OR form is used. With the index (TenantId, CreatedAt DESC, Id DESC) the optimiser seeks to (tenant, c) and reads forward, usually with one seek plus a residual predicate for the tie.
If you sort only by CreatedAt and two rows share a timestamp across a page boundary, the predicate CreatedAt < @c skips the second one. A unique final column makes the order total, so each row has exactly one position.
Encode the last key as JSON and base64url it. Treat it as opaque: validate on decode and reject bad tokens with 400. If the sort column can change for a row (e.g. sorting by UpdatedAt), a row can move across pages; keyset is stable only for immutable sort keys.
limit + 1 rows; if you got the extra one, there is a next page.MR.EntityFrameworkCore.KeysetPagination generate the predicate, but the hand-written version is short.COUNT(*) over millions of rows costs more than the page itself; show approximate counts or none.SET STATISTICS IO ON.Id tiebreaker, create duplicate timestamps across a page boundary and show a row going missing.Offset and keyset pagination for a newest-first orders list, with an opaque cursor.
namespace Shop.Orders;
using System.Buffers.Text;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
public sealed record OrderRow(int Id, DateTime CreatedAt, decimal Total);
public sealed record Page<T>(IReadOnlyList<T> Items, string? NextCursor);
internal sealed record OrderCursor(DateTime CreatedAt, int Id)
{
public string Encode() => Base64Url.EncodeToString(JsonSerializer.SerializeToUtf8Bytes(this));
public static OrderCursor? Decode(string? token)
{
if (string.IsNullOrEmpty(token)) return null;
try { return JsonSerializer.Deserialize<OrderCursor>(Base64Url.DecodeFromChars(token)); }
catch (Exception ex) when (ex is FormatException or JsonException)
{ throw new ArgumentException("Invalid cursor.", nameof(token), ex); }
}
}
public sealed class OrderPaging(ShopDbContext db)
{
private const int MaxLimit = 100;
// Offset: fine for shallow, numbered admin pages.
public Task<List<OrderRow>> GetOffsetPageAsync(int tenantId, int page, int size, CancellationToken ct) =>
db.Orders
.Where(o => o.TenantId == tenantId)
.OrderByDescending(o => o.CreatedAt).ThenByDescending(o => o.Id) // always order before paging
.Skip((page - 1) * size)
.Take(size)
.Select(o => new OrderRow(o.Id, o.CreatedAt, o.Total))
.ToListAsync(ct);
// Keyset: constant cost per page, stable under inserts.
public async Task<Page<OrderRow>> GetKeysetPageAsync(int tenantId, string? cursor, int limit, CancellationToken ct)
{
limit = Math.Clamp(limit, 1, MaxLimit);
var after = OrderCursor.Decode(cursor);
var query = db.Orders.Where(o => o.TenantId == tenantId);
if (after is not null)
{
// Expanded row comparison: (CreatedAt, Id) < (after.CreatedAt, after.Id) in DESC order.
query = query.Where(o => o.CreatedAt < after.CreatedAt
|| (o.CreatedAt == after.CreatedAt && o.Id < after.Id));
}
var rows = await query
.OrderByDescending(o => o.CreatedAt).ThenByDescending(o => o.Id)
.Take(limit + 1) // one extra row tells us if there is a next page
.Select(o => new OrderRow(o.Id, o.CreatedAt, o.Total))
.ToListAsync(ct);
var hasMore = rows.Count > limit;
if (hasMore) rows.RemoveAt(rows.Count - 1);
var next = hasMore ? new OrderCursor(rows[^1].CreatedAt, rows[^1].Id).Encode() : null;
return new Page<OrderRow>(rows, next);
}
}
// Index that matches the filter and sort (in OrderConfiguration).
b.HasIndex(o => new { o.TenantId, o.CreatedAt, o.Id })
.IsDescending(false, true, true)
.IncludeProperties(o => o.Total);
{ "items": [ { "id": 98123, "createdAt": "2026-11-18T23:10:04Z", "total": 42.50 } ],
"nextCursor": "eyJDcmVhdGVkQXQiOiIyMDI2LTExLTE4VDIzOjEwOjA0WiIsIklkIjo5ODEyM30" }
Skip/Take without OrderBy. Why it is wrong: SQL Server returns rows in no guaranteed order, so pages overlap or skip rows; EF Core logs a warning. Instead: always order by a unique key before paging.TenantId), then the sort columns in the ORDER BY sequence and direction, then INCLUDE the projected columns; check the actual plan shows a seek and no Sort operator. If a selective filter isn't in the index, SQL Server may read many rows to find 20 matches.COUNT(*) for every page. Why it is wrong: the count can cost more than the page on large tables. Instead: return hasMore by fetching limit + 1, or show an approximate total.UpdatedAt. Why it is wrong: rows move between pages while the client pages. Instead: sort by an immutable key, or accept and document the behaviour.(CreatedAt, Id) < (@c, @i) in raw SQL. Why it is wrong: SQL Server and Azure SQL do not support row-value comparisons (PostgreSQL does), so it fails to parse. Instead: use the expanded A < @a OR (A = @a AND B < @b) form, which EF Core generates from the equivalent LINQ.limit on the server.The choice is a product decision as much as a technical one: keyset gives up random access and cheap totals in exchange for constant cost and stability. For any list that can grow without bound and is consumed by machines or infinite scroll, I default to keyset with an opaque cursor; for back-office grids with filters and page numbers, offset with a sensible maximum page is simpler and good enough. I measure with logical reads at different depths, because duration on a warm dev database hides the linear growth.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Offset | Admin grids, shallow pages, jump-to-page | Linear in depth, unstable under inserts | Large tables paged deeply, public APIs |
| Keyset with cursor | Feeds, APIs, exports, mobile | Matching index, more code, no jump | Users need page numbers or arbitrary sort columns |
| Keyset library | Many endpoints with multi-column sorts | Dependency | One or two endpoints |
| Snapshot export (temporal or staging table) | Consistent full exports | Storage | Interactive lists |
Skip(n) becomes OFFSET n ROWS, so SQL Server reads and discards n rows every time; page 5,000 reads 100,000 rows to return 20, and cost grows linearly with depth. Keyset paging remembers the last row's sort key and filters WHERE Price > @lastPrice OR (Price = @lastPrice AND Id > @lastId) with the same ORDER BY Price, Id, which seeks an index and reads only the rows it returns, so every page costs the same. It is also stable when rows are inserted. The trade-off: no jumping to page N, so it suits infinite scroll, APIs and exports, while offset stays fine for shallow, numbered pages in admin screens. The sort key needs a matching index and a unique tiebreaker.
Start from db.Products.AsNoTracking() as an IQueryable<T> and add Where clauses conditionally; each one ANDs into the same SQL WHERE. For OR logic, combine Expression<Func<T,bool>> predicates by rebinding their parameters (or use LinqKit), never Func<T,bool>, which would force in-memory evaluation.
For sorting, map the client's string to a whitelisted dictionary of key-selector expressions and always add ThenBy(x => x.Id) so paging is stable. Cap the page size on the server. Values captured in closures become SQL parameters, so there's no injection risk and plans are reused.
The trade-off: flexible search is easy to compose, but every optional filter combination is a different SQL shape, so index for the common ones and test the translation.
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.
How to tell it (STAR)
**S:** Our [mobile app's] activity feed slowed to several seconds for users who scrolled far, and people reported duplicate items. **T:** I [was asked to / volunteered to] fix both without a big client rewrite. **A:** EF Core logs showed OFFSET paging, and Query Store showed reads growing with the page number. I reproduced the duplicates in a test by inserting rows mid-scroll. I switched to keyset paging on CreatedAt and Id with a matching descending index, returned an opaque cursor, and kept the old parameter for one release so older app versions still worked. **R:** Every page now takes about [5 ms] regardless of depth, database reads for the feed dropped by about [90%], and the duplicate reports stopped.
Last updated 23 Nov 2026.