Skip to content

Cursor Patterns

A cursor is an opaque continuation token. The handler encodes it; Repl passes it back on the next call. This page is a dense reference — for the conceptual background, see Result-Flow Paging.


PatternWhen to useCursor encodingRepl helper
Offset / indexSmall or static datasets, admin tables, bounded lists"42" — decimal row offsetFromOffset
Keyset / seekLarge, mutable databases with a stable sort columnbase64 of (lastSortKey, tieBreakerId)paging.CreateSource(...)
External page tokenWrapping a paginated API (Azure SDK, etc.)Opaque token from the API responsepaging.CreateSource(...)
nextLink / URLOData, Microsoft Graph, REST APIs with @nextLinkFull URL string — validate originpaging.CreateSource(...)
SnapshotConsistent views over changing data(snapshotId, offset) as base64-JSONpaging.CreateSource(...)
Range / windowTime-series and log scans: one time window, paged by countbase64 of (lastTimestamp, lastId, windowEnd)paging.CreateSource(...)
Page 1 A B C D E no cursor returns A B C D E; then N is inserted after B Page 2, offset cursor A B N C D E F G H I cursor "5" skips 5 rows of the changed table: E comes back a second time, and N is never shown Page 2, keyset cursor F G H I J cursor base64(E) seeks past E; N, inserted before it, is never shown either Page 2, snapshot cursor A B C D E F G H I J cursor base64(snapshot, 5) reads the copy taken for page 1, where N does not exist returned on this page read, then not returned
What the second page returns when a row is inserted between two requests, with an offset, a keyset and a snapshot cursor.

Simplest pattern. Reliable on static or append-only data. Degrades on mutable rows (inserts shift subsequent pages).

public ReplPage<Row> Query(IReplPagingContext paging)
{
var offset = paging.AllRequested ? 0 : ParseOffset(paging.Cursor);
var items = _store.Skip(offset).Take(paging.SuggestedPageSize).ToList();
var next = offset + items.Count < _store.Count
? (offset + items.Count).ToString(CultureInfo.InvariantCulture)
: null;
return paging.Page(items, nextCursor: next, totalCount: _store.Count);
}
private static int ParseOffset(string? cursor) =>
cursor is null ? 0
: int.TryParse(cursor, NumberStyles.None, CultureInfo.InvariantCulture, out var v) ? v
: throw new ArgumentException("Invalid continuation cursor.");

Or use the built-in helper:

ReplPageSource.FromOffset<Row>(
(offset, take, ct) => store.QueryAsync(offset, take, ct),
totalCount: store.Count)

Best for large tables with frequent inserts or deletes. Encodes the sort key + tie-breaker of the last row seen. Pages are stable even as the underlying data changes.

Offset cursor, FromOffset cursor "10" the store reads and skips 10 rows first; the cost grows with every page Keyset cursor cursor base64({ LastCreatedAt, LastId }) with an index on (CreatedAt, Id), the store seeks past the last key; the cost does not grow returned on this page read, then not returned read to detect a next page
What the store touches to serve page 3, with an offset cursor and with a keyset cursor.
app.Map("orders", async (IReplPagingContext paging, OrderStore store, CancellationToken ct) =>
paging.CreateSource<Order>(async (req, innerCt) =>
{
var (afterDate, afterId) = ParseKeysetCursor(req.Cursor);
var items = await store.SeekAsync(afterDate, afterId, req.PageSize, innerCt);
return new ReplPage<Order>(
items,
nextCursor: items.Count == req.PageSize
? EncodeKeysetCursor(items[^1].CreatedAt, items[^1].Id)
: null);
}));
private static (DateTimeOffset? after, int? id) ParseKeysetCursor(string? cursor)
{
if (cursor is null) return (null, null);
try
{
var json = JsonSerializer.Deserialize<KeysetCursor>(Convert.FromBase64String(cursor))
?? throw new ArgumentException("Invalid continuation cursor.");
return (json.LastCreatedAt, json.LastId);
}
catch (Exception ex) when (ex is FormatException or JsonException)
{
// A cursor that does not decode is refused, never read as "start over".
throw new ArgumentException("Invalid continuation cursor.", ex);
}
}
private static string EncodeKeysetCursor(DateTimeOffset at, int id) =>
Convert.ToBase64String(JsonSerializer.SerializeToUtf8Bytes(new KeysetCursor(at, id)));
private sealed record KeysetCursor(DateTimeOffset LastCreatedAt, int LastId);

Forward the API’s opaque token as-is. A caller can send any string back as the cursor, so the API must treat the token as untrusted; if it does not, keep the token server-side and hand out an opaque key instead.

Handler paging.CreateSource Messages API external service GetMessagesAsync(pageToken: null, 20) request 20 messages, NextPageToken "CiAKGjBi..." response GetMessagesAsync(pageToken: "CiAKGjBi...", 20) request 7 messages, NextPageToken null response
The handler forwards the API's NextPageToken unchanged as the next cursor; a null token ends the paging.
app.Map("messages", async (IReplPagingContext paging, MessageApiClient client, CancellationToken ct) =>
paging.CreateSource<Message>(async (req, innerCt) =>
{
var response = await client.GetMessagesAsync(req.Cursor, req.PageSize, innerCt);
return new ReplPage<Message>(
response.Messages,
nextCursor: response.NextPageToken);
}));

Used by OData and Microsoft Graph. The next-page URL is the cursor, and your client sends it with its own credentials, so a caller who edits it can reach any URL those credentials allow. Check the scheme, the host, the port and the collection path, not only a prefix. When the client holds a service identity rather than the caller’s, keep the nextLink server-side behind an opaque key, or sign it.

app.Map("items", async (IReplPagingContext paging, GraphClient client, CancellationToken ct) =>
paging.CreateSource<Item>(async (req, innerCt) =>
{
// Accept only a nextLink for this collection on this API, not any URL on the host.
if (req.Cursor is not null
&& !(Uri.TryCreate(req.Cursor, UriKind.Absolute, out var next)
&& next.Scheme == Uri.UriSchemeHttps
&& next.IdnHost == "graph.example.com"
&& next.IsDefaultPort
&& next.AbsolutePath == "/v1.0/items"))
{
throw new ArgumentException("Invalid continuation cursor.");
}
var response = req.Cursor is null
? await client.GetItemsAsync(req.PageSize, innerCt)
: await client.GetItemsFromUrlAsync(req.Cursor, innerCt);
return new ReplPage<Item>(
response.Value,
nextCursor: response.OdataNextLink);
}));

Creates an immutable snapshot on the first page request and pages through it. The view is consistent even if the underlying table changes between pages.

app.Map("audit", async (IReplPagingContext paging, AuditStore store, ICurrentUser user, CancellationToken ct) =>
paging.CreateSource<AuditRow>(async (req, innerCt) =>
{
var (snapshotId, offset) = ParseSnapshotCursor(req.Cursor);
// First page: create a snapshot owned by the caller; later pages: reuse it.
// Snapshot ids must be unguessable, and reads are scoped to their owner.
snapshotId ??= await store.CreateSnapshotAsync(user.Id, innerCt);
var items = await store.ReadSnapshotAsync(user.Id, snapshotId, offset, req.PageSize, innerCt);
var nextOffset = offset + items.Count;
var hasMore = items.Count == req.PageSize;
return new ReplPage<AuditRow>(
items,
nextCursor: hasMore ? EncodeSnapshotCursor(snapshotId, nextOffset) : null);
}));
private static (string? id, int offset) ParseSnapshotCursor(string? cursor)
{
if (cursor is null) return (null, 0);
try
{
var snap = JsonSerializer.Deserialize<SnapshotCursor>(Convert.FromBase64String(cursor));
return snap is { Id: not null, Offset: >= 0 }
? (snap.Id, snap.Offset)
: throw new ArgumentException("Invalid continuation cursor.");
}
catch (Exception ex) when (ex is FormatException or JsonException)
{
throw new ArgumentException("Invalid continuation cursor.", ex);
}
}
private static string EncodeSnapshotCursor(string id, int offset) =>
Convert.ToBase64String(JsonSerializer.SerializeToUtf8Bytes(new SnapshotCursor(id, offset)));
private sealed record SnapshotCursor(string Id, int Offset);

For time-series or log data: the caller picks one time window, and pages hold a fixed number of events inside it. The cursor names the last event returned, by timestamp and id, so the next page starts strictly after it even when several events share a timestamp.

from 08:00 to 09:00 page 1 next: after 08:18 page 2 next: after 08:41 page 3 next: none
One window from 08:00 to 09:00, cut into 3 pages of up to 4 events.
app.Map("metrics", async (IReplPagingContext paging, MetricStore store, string? from, string? to, CancellationToken ct) =>
paging.CreateSource<MetricRow>(async (req, innerCt) =>
{
var (afterTime, afterId, windowEnd) = ParseWindowCursor(req.Cursor, from, to);
// Events strictly after (afterTime, afterId) and before windowEnd, ordered by (Timestamp, Id).
var items = await store.QueryWindowAsync(afterTime, afterId, windowEnd, req.PageSize, innerCt);
var next = items.Count == req.PageSize
? EncodeWindowCursor(items[^1].Timestamp, items[^1].Id, windowEnd)
: null;
return new ReplPage<MetricRow>(items, nextCursor: next);
}));

Incoming cursor --result:cursor_replCursor (MCP) Repl checks not emptyat most 512 charactersdoes not start with -no whitespaceno control characters otherwise refused Your handler checks decodes or decrypts itchecks its signatureowner and tenant matchnot expirednextLink: host and path otherwise refused Query the store req.Cursor
Repl checks the shape of every cursor a caller passes back; the handler makes the checks that depend on what its cursor carries.
  • Length — Repl enforces ≤ 512 characters. Keep your encoded cursors well under this.
  • Encoding — Prefer base64 for structured data. Avoid raw JSON or strings with spaces (Repl rejects whitespace in cursors). The interactive pager passes your nextCursor back without Repl’s checks, so a cursor that fails them still works there, then fails when a script or an agent passes it back.
  • Refusal — A cursor your handler cannot decode is an error, not a request for the first page: falling back silently hands a script or an agent rows it already has. Inside CreateSource, throwing is the way to refuse; the run ends as a handler error, and an MCP agent sees a failed call.
  • Ownership — Scope every query by the authenticated caller, never by an id read from the cursor. A cursor that must carry tenant, filter or internal ids needs authenticated protection, an HMAC or authenticated encryption such as ASP.NET Core Data Protection, with the owner inside the protected payload to compare with the caller. Data Protection’s string output is base64url and can start with -, which Repl refuses; protect bytes and use standard base64 instead.
  • Expiry — Consider adding a timestamp to snapshot or session-bound cursors and rejecting expired ones.
  • Leakage — Cursors that contain database internals (table names, raw SQL fragments, internal IDs) expose schema. Use opaque tokens or encrypt the payload.