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

📚 Interview question

Show how you would implement offset and keyset pagination in EF Core for an orders list sorted newest first. Why does Skip/Take get slower on deep pages, how do you build keyset paging on a composite key with a stable order, and what does the API contract look like?

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.

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

🎯 Key points

  • Skip/Take -> OFFSET @p ROWS FETCH NEXT @q ROWS ONLY; skipped rows are still read
  • Offset cost grows with page depth; rows shift when data is inserted
  • Keyset: WHERE (CreatedAt < @c) OR (CreatedAt = @c AND Id < @id) with the same ORDER BY
  • A unique tiebreaker (Id) makes the order total and stable
  • Index matching the sort: (CreatedAt DESC, Id DESC), plus any equality filter first
  • Expose an opaque cursor (base64 of the last key), not raw page numbers
  • Keyset has no jump to page N; offset is fine for shallow admin grids
  • Always order before paging; EF Core warns about Skip/Take without OrderBy

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"Offset paging with Skip and Take is the default everyone writes, and EF Core turns it into OFFSET ... 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. The Id is 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 a nextCursor field, 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 vs keyset

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

The API contract

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)

Production example

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.

🔍 What the interviewer is checking

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

  • Explains that OFFSET reads and discards rows and that results shift under inserts
  • Uses a unique tiebreaker and the expanded OR predicate
  • Names the matching composite index with sort directions
  • Proposes an opaque cursor and limit + 1 for hasMore
  • Knows when offset is still the right choice

Red flags

  • Pages without OrderBy
  • Keyset on a non-unique column only
  • Believes an index alone makes deep OFFSET pages cheap

📚 Learn in depth

1. What OFFSET actually does

SELECT [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.

2. The keyset predicate

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.

3. Why a tiebreaker is required

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.

4. Cursors

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.

5. Variations

  • Previous page: reverse the comparison and the ORDER BY, then reverse the results in memory.
  • Has next page: fetch limit + 1 rows; if you got the extra one, there is a next page.
  • Libraries: EF Core has no built-in keyset API in EF Core 10; community packages such as MR.EntityFrameworkCore.KeysetPagination generate the predicate, but the hand-written version is short.
  • Totals: a COUNT(*) over millions of rows costs more than the page itself; show approximate counts or none.

Try it yourself

  1. Seed 2 million orders and time pages 1, 1,000 and 50,000 with offset paging, recording logical reads with SET STATISTICS IO ON.
  2. Implement the keyset version and repeat; plot reads against page depth for both.
  3. Remove the Id tiebreaker, create duplicate timestamps across a page boundary and show a row going missing.
  4. Drop the matching index and compare the keyset plan (scan plus sort) with the seek.
  5. Write an integration test that pages through all rows with cursors and asserts every id appears exactly once while inserts happen.

💻 Code

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" }

⚠ Common mistakes

  • Mistake: Using 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.
  • Mistake: Keyset on a non-unique sort column alone. Why it is wrong: rows with equal values at a page boundary are skipped or repeated. Instead: add the primary key as a tiebreaker in both the ORDER BY and the predicate.
  • Mistake: No index matching the filter and sort. Why it is wrong: SQL Server scans and sorts the whole filtered set, so keyset is no faster than offset. Instead: design the index from the whole query: equality filters first (e.g. 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.
  • Mistake: Exposing raw keys or page numbers as the contract for an API that will grow. Why it is wrong: clients depend on the format and you cannot change the strategy later. Instead: return an opaque cursor.
  • Mistake: Running a 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.
  • Mistake: Keyset over a mutable sort column such as 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.
  • Mistake: Writing (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.
  • Mistake: Not capping the page size. Why it is wrong: a client asking for 100,000 rows defeats paging. Instead: clamp limit on the server.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate explains why deep offset pages are slow Why: Checks the short version of the offset vs keyset trade-off and when offset still fits
    How to answer

    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.

  2. When: Candidate mentions client-chosen sort columns Why: Checks they can build dynamic, translatable queries with safe sorting and paging
    How to answer

    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.

  3. When: Candidate mentions that keyset only moves forward Why: Checks they can reverse the predicate and order, then restore the display order
    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.

🛠 Real-world problems: how you handle them

Activity feed slowing down on deep pages and showing duplicates
Situation
A mobile app's activity feed backed by ASP.NET Core and EF Core on Azure SQL, with [about 20 million] activity rows and infinite scroll used by [about 100,000] daily users.
Signals
Feed requests beyond page 200 took 2 to 4 seconds; Azure SQL logical reads per call grew with page number in Query Store; users reported seeing the same items twice when scrolling during busy periods.
Investigation
Captured the SQL with EF Core logging and saw `OFFSET @p ROWS FETCH NEXT 20 ROWS ONLY`. Query Store showed reads rising linearly with the offset parameter. Reproduced the duplicates by inserting rows while paging in an integration test. Checked the index: `(UserId, CreatedAt DESC)` with no tiebreaker.
Resolution
Immediately: capped scroll depth on the client. Then replaced offset paging with keyset on `(UserId, CreatedAt DESC, Id DESC)`, added the matching index online through a migration, and changed the API to return an opaque `nextCursor` while keeping the old parameter working for one release.
Prevention
An integration test that pages through all rows during concurrent inserts and asserts no duplicates or gaps; an API guideline that unbounded lists use cursor paging; a Query Store alert on logical reads per execution.

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.

↩ Usually asked after

More in EF Core Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me