Offset pagination (OFFSET 1000 ROWS FETCH NEXT 20) becomes slow on deep pages and shows duplicates or skipped rows when data is inserted or deleted between requests. Cursor (keyset) pagination fixes both. Idea Sort by a unique, stable key and ask for rows after the last row the client saw. SELECT TOP (@size) Id, Title, CreatedAt FROM Posts WHERE (CreatedAt < @lastCreatedAt) OR (CreatedAt = @lastCreatedAt AND Id < @lastId) ORDER BY CreatedAt DESC, Id DESC; The Id tie-breaker makes the order unique, so no row is skipped or repeated even when several rows share a timestamp. Index CREATE INDEX IX_Posts_CreatedAt_Id ON Posts (CreatedAt DESC, Id DESC) INCLUDE (Title); The database seeks directly to the position, so page 1 and page 10,000 cost the same. ASP.NET Core and EF Core var query = db.Posts.AsNoTracking().OrderByDescending(p => p.CreatedAt).ThenByDescending(p => p.Id); if (cursor is not null) query = query.Where(p => p.CreatedAt < cursor.CreatedAt || (p.CreatedAt == cursor.CreatedAt && p.Id < cursor.Id)); var items = await query.Take(size + 1).ToListAsync(ct); // fetch one extra to know if more exist - Encode the cursor (last CreatedAt and Id) as an opaque base64 string, and sign or encrypt it if clients must not tamper with it. - Return { items, nextCursor }; nextCursor is null when there are no more rows. - Validate page size with a maximum. - Bind filters into the cursor or validate that they have not changed between requests. Trade-offs - No jumping to an arbitrary page number and no cheap total count — usually fine for feeds, infinite scroll and APIs. - Sorting by user-chosen columns needs a cursor per sort order, always with a unique tie-breaker. - Rows updated so they move in the sort order may appear again or not at all; choose immutable sort keys (creation time, ID) for changing datasets. Libraries such as MR.EntityFrameworkCore.KeysetPagination implement this pattern for EF Core.
Ravindra Wadile · · 0 likes