Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ Folder names are category-prefixed (e.g. `ui-`, `data-`, `app-settings-`, `chat-
| `audio-bundled-sfx` | How do I ship and play short sound effects from my client, dealing with the autoplay policy and Vite asset bundling? | — | — |
| `chat-trigger-respond` | How do I make my app respond to user chat messages? | `server-messages` | `apps/leveling-leaderboard` |
| `data-batch-prefetch` | How do I batch-prefetch related data (e.g. 50 user profiles for a list of activities) in one call instead of N+1 from the client? | `server-database`, `networking-app-services` | — |
| `data-paginated-list` | How do I paginate a server-side list with cursor-based queries and accumulate pages on the client? | `server-database`, `networking-app-services` | `apps/leveling-leaderboard` |
| `data-paginated-list` | How do I paginate a server-side list with cursor-based queries, accumulate pages on the client, and search it without breaking the paging? | `server-database`, `networking-app-services` | `apps/leveling-leaderboard` |
| `error-rpc-exceptions` | How do I propagate domain-specific error codes from server to client and let the client branch on them? | `networking-app-services`, `server-key-value-store` | `apps/suggestion-box` |
| `external-http-fetch` | How do I call an external HTTP API from my server with timeouts and typed error handling? | `networking-app-services` | `apps/github-release-watcher` |
| `per-user-cooldown` | How do I rate-limit a per-user action so it can only happen once per N seconds, atomically? | `server-database`, `networking-app-services` | `apps/leveling-leaderboard` |
Expand Down
45 changes: 39 additions & 6 deletions recipes/data-paginated-list/AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
kind: recipe
category: data
question: How do I paginate a server-side list with cursor-based queries and accumulate pages on the client?
question: How do I paginate a server-side list with cursor-based queries, accumulate pages on the client, and search it without breaking the paging?
composes:
- server-database
- networking-app-services
Expand All @@ -10,9 +10,9 @@ exemplified_by: leveling-leaderboard

# Recipe: Cursor-Based Pagination

> *"How do I paginate a server-side list with cursor-based queries and accumulate pages on the client?"*
> *"How do I paginate a server-side list with cursor-based queries, accumulate pages on the client, and search it without breaking the paging?"*

A SQLite-backed list of records, exposed via an RPC that returns one page at a time. The client accumulates pages with a "Load more" button. When the server returns an empty `next_cursor`, the list is exhausted.
A SQLite-backed list of records, exposed via an RPC that returns one page at a time. The client accumulates pages with a "Load more" button. When the server returns an empty `next_cursor`, the list is exhausted. A search box filters the list **on the server**, because a paginated response is a window and filtering it on the client searches the window instead of the list.

The seeded data — 100 rows labelled `Record 1`…`Record 100` — is **placeholder**. Fork the recipe and replace the schema (and the seed in [`server/src/db.ts`](server/src/db.ts)) with whatever your real list shape is: audit log entries, posts, items in a queue, etc. The pagination mechanic is independent of row contents.

Expand All @@ -31,6 +31,11 @@ click "Load more"
append again

…eventually the server returns next_cursor: "" — done.

type "wid" in the search box (debounced 300ms)
→ listRecords({ cursor: "", search: "wid" }) ► SELECT … WHERE id < MAX AND LOWER(label) LIKE '%wid%' LIMIT 20
◄─────── { records: [matches], next_cursor: "<opaque, carries "wid">" }
REPLACE local state — this is a new query, not more of the old one
```

## Why cursor, not offset
Expand All @@ -51,6 +56,22 @@ If the client decodes a malformed cursor, the server falls back to "first page"

The server detects end-of-list precisely by querying `pageSize + 1` rows and trimming the extra. If the trim happened, there's at least one more row → return a cursor. If it didn't (we got `pageSize` or fewer rows), there's nothing past this page → return empty cursor. The cost is one extra row of work per page; the win is the last user-facing page already knows it's the last. A cheaper variant — ask for exactly `pageSize` and infer end from "got fewer than asked" — sacrifices precision: the last full page returns a non-empty cursor that yields `[]` on the next call, making the user click "Load more" once for nothing. The extra-row variant is the canonical choice for user-facing pagination.

## Why the server filters, and the client never does

The client holds the pages it has fetched. Filtering that array answers "which of the rows I already have match?", which is not the question the user asked. On a list of 40 with a page size of 20, a client-side filter searches half the data and looks completely correct.

The failure has no symptom. There is no error, no empty state, and no wrong-looking output — matches that exist are simply not returned, and the behaviour degrades continuously as the table grows. It also cannot be caught by running the app: seed and fixture data are almost always smaller than one page, so during development every row is in the first page and the filter appears to work perfectly.

So `search` goes in the request. The filter and the seek live in the same SQL, which means paging walks the matching rows rather than walking every row and discarding non-matches.

## Why the cursor carries the search term

A cursor means "the last id you saw" — but only within the query that produced it. Pair a cursor from an unfiltered listing with `search: "wid"` and the server seeks past every match above that id and returns a page that is missing rows for no visible reason.

The cursor payload therefore carries the term it was issued under, and the server restarts from the first page when the term differs. This is the payoff of the opaque-cursor decision above: the payload gained a field and no client had to change.

A well-behaved client also resets its own pagination when the term changes, which the client here does. Both halves are worth having — the client reset is the mechanism, the server check is what makes a client bug produce a correct-if-slower answer instead of a silently short list.

## Composes

| api-sample | What it teaches | What this recipe uses it for |
Expand Down Expand Up @@ -112,15 +133,27 @@ Initial load fires on mount; subsequent loads on button click. Same `fetchPage`

For an infinite-scroll variant: replace the button with an `IntersectionObserver` watching a sentinel at the bottom of the list. The observer's callback calls `fetchPage(cursor)`. Same state, different trigger.

## Does NOT cover
## Not covered here — safe to go elsewhere

Nothing below is a trap. Each is a genuinely separate concern; build it where it belongs.

| Concern | Lives in |
|---|---|
| **Live updates** — inserting new rows visible in already-loaded pages | A separate recipe (deferred until streaming-subscription test infrastructure lands) |
| **Filtering and search** — paginating a filtered subset | Independent concern; the cursor encoding extends naturally to carry the filter, but multi-axis pagination has its own design space |
| **Virtualized rendering** — only paint visible rows for very long lists | Independent of pagination mechanics; a real app uses `react-window` or similar regardless of how data is fetched |
| **Pull-to-refresh** — re-fetching the latest page from the top | Adjacent feature with its own state-machine wrinkles (overlap with already-loaded rows, dedup) |
| **Stable ordering across columns** — pagination over `ORDER BY total_xp DESC` with ties | The cursor extends to a tuple `(total_xp, id)` and the query becomes `WHERE (total_xp, id) < (?, ?)`. Same shape, more parameters. |

## Not covered here — and the obvious approach is wrong

These are extensions this recipe does not implement, where the naive version is silently broken rather than merely incomplete. Read the trap before you build one.

| Extension | The trap | The shape that works |
|---|---|---|
| **Multi-field or multi-axis filtering** — filter by status *and* author *and* date | Adding filters client-side once one filter already lives on the server. The two disagree the moment the data exceeds a page, and the server-filtered subset makes the client-filtered result look plausible. | Every filter goes in the request, and all of them go into the cursor payload's fingerprint. One query, one cursor, one source of truth. |
| **Stable ordering across columns** — paging over `ORDER BY total_xp DESC` with ties | Seeking on the sort column alone. Rows with equal `total_xp` straddle the page boundary, so some are served twice and others never. | The cursor becomes a tuple `(total_xp, id)` and the query becomes `WHERE (total_xp, id) < (?, ?)` — the id breaks ties. Same shape, more parameters. |
| **Sorting chosen by the user** — a column-header click that reorders the list | Keeping the cursor across a sort change. It describes a position in the old ordering, so the new listing starts from an arbitrary point. | Treat a sort change exactly like a term change: it is a new query. Reset pagination, and put the sort key in the cursor payload so a mismatched pair restarts instead of seeking. |

**The pattern behind all three:** a cursor is a position inside one specific query. Anything that changes the query — a filter, a term, an ordering — invalidates it. Encode enough of the query in the cursor that the server can tell, because the alternative is a page that is quietly missing rows.

## Test-only files in this recipe

Expand Down
119 changes: 87 additions & 32 deletions recipes/data-paginated-list/client/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,47 @@
//
// State machine for accumulating pages:
//
// - records[] — every record fetched so far, in order
// - cursor — the cursor for the NEXT call (empty string on first load)
// - loading — request in flight; disable the button to prevent double-fire
// - done — server returned an empty next_cursor; no more pages
// - error — last error message, if any (display + recover by retrying)
// - records[] — every record fetched so far, in order
// - cursor — the cursor for the NEXT call (empty string on first load)
// - loading — request in flight; disable the button to prevent double-fire
// - done — server returned an empty next_cursor; no more pages
// - error — last error message, if any (display + recover by retrying)
// - search — what the user has typed, updated on every keystroke
// - appliedSearch — the debounced term actually sent to the server
//
// Initial load happens on mount via useEffect; subsequent loads are user-driven
// via the "Load more" button. Same fetchPage function for both — the only
// difference is whether the user clicked something.
// The client does NOT filter `records`. The server does the filtering, because
// `records` only holds the pages fetched so far — filtering it locally would
// search the window instead of the list, and would never find a match beyond
// the pages already pulled. That bug is invisible while the seed data fits in
// one page, which is exactly why it survives review.
//
// A term change resets pagination: records cleared, cursor cleared, first page
// re-fetched. Keeping the old cursor would seek into a result set that no
// longer exists.
//
// Why the first page REPLACES and later pages APPEND: it makes the first fetch
// idempotent, so React.StrictMode's deliberate double-invocation of effects in
// dev is harmless. An earlier version of this recipe appended on every page and
// needed a useRef latch to stop the mount effect duplicating records 100…81.
// Designing the operation to be repeatable beats latching around a repeat.
//
// Why we don't auto-load all pages: the recipe's lesson is the explicit pull
// pattern (each page is a deliberate fetch). Real apps often replace the
// button with an IntersectionObserver-driven infinite scroll, but the
// underlying state machine is the same — replace the click handler with the
// observer callback. We use a button here because it's the simplest visible
// demonstration of "another page is available."
// observer callback.
//
// If you take the infinite-scroll route, note that it interacts badly with a
// client-side filter, which is a second reason not to write one: filtering the
// accumulated pages shrinks the rendered list, which can lift the sentinel out
// of the viewport, so the observer never fires and the list never grows to
// contain what the user is looking for. Searching then prevents its own results
// from loading. With the filter on the server this cannot happen — each term is
// its own query, starting from its own first page.
//
// ============================================================================

import React, { useEffect, useRef, useState } from "react";
import React, { useEffect, useState } from "react";
import { listServiceClient } from "@datapaginatedlist/gen-client";
import { Record as RecordMessage } from "@datapaginatedlist/gen-shared";

Expand All @@ -36,21 +57,28 @@ export const App: React.FC = () => {
const [loading, setLoading] = useState<boolean>(false);
const [done, setDone] = useState<boolean>(false);
const [error, setError] = useState<string | undefined>(undefined);
// Latch for the initial-load effect — see useEffect comment below.
const initialFetchRef = useRef(false);

const fetchPage = async (currentCursor: string): Promise<void> => {
const [search, setSearch] = useState<string>("");
const [appliedSearch, setAppliedSearch] = useState<string>("");

const fetchPage = async (
currentCursor: string,
term: string,
mode: "replace" | "append",
): Promise<void> => {
setLoading(true);
setError(undefined);
try {
const r = await listServiceClient.listRecords({
pageSize: PAGE_SIZE,
cursor: currentCursor,
search: term,
});
// Append, don't replace. The previous-page records stay; the new page
// gets concatenated. This is what makes the "load more" pattern feel
// continuous to the user instead of paging in/out.
setRecords((prev) => [...prev, ...r.records]);
// Later pages append so "load more" feels continuous; the first page of
// any query replaces, which both clears the previous term's results and
// makes the call safe to repeat.
setRecords((prev) =>
mode === "replace" ? r.records : [...prev, ...r.records],
);
setCursor(r.nextCursor);
// Empty next_cursor = end of list. Flip done=true so the button
// disables itself and we render the end-of-list message.
Expand All @@ -62,26 +90,38 @@ export const App: React.FC = () => {
}
};

// Initial load on mount, once. React.StrictMode in dev intentionally
// double-invokes effects to surface impure side-effect bugs — without a
// guard, fetchPage("") fires twice and the appending setRecords produces
// visible duplicates of records 100…81. The useRef latch is the canonical
// pattern: refs survive the StrictMode unmount/remount, so the second
// invocation no-ops. (Production builds don't double-invoke effects, but
// devhost is the canonical local-run path for this recipe, so the dev-mode
// duplication would be the first thing a learner sees and questions.)
// Debounce the input so a search costs one request per pause rather than one
// per keystroke. Clients are rate-limited to 10 app RPCs per second, and a
// fast typist exceeds that on a single word without this.
useEffect(() => {
if (initialFetchRef.current) return;
initialFetchRef.current = true;
void fetchPage("");
const timer = setTimeout(() => setAppliedSearch(search.trim()), 300);
return () => clearTimeout(timer);
}, [search]);

// One effect covers both the initial load and every term change: appliedSearch
// starts as "" so the mount case is simply the first query. Clearing the
// cursor here is what stops a stale cursor being paired with a new term.
useEffect(() => {
setCursor("");
setDone(false);
void fetchPage("", appliedSearch, "replace");
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}, [appliedSearch]);

return (
<main style={pageStyle}>
<h1 style={{ fontSize: 24, margin: 0 }}>Cursor-Based Pagination</h1>
<input
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder="Search labels"
aria-label="Search labels"
style={inputStyle}
/>

<p style={metaStyle}>
Loaded {records.length} record{records.length === 1 ? "" : "s"}
{appliedSearch ? ` matching ${JSON.stringify(appliedSearch)}` : ""}
{done ? " (end of list)" : ""}
</p>

Expand All @@ -98,7 +138,7 @@ export const App: React.FC = () => {

{!done && (
<button
onClick={() => void fetchPage(cursor)}
onClick={() => void fetchPage(cursor, appliedSearch, "append")}
disabled={loading}
style={buttonStyle}
>
Expand All @@ -108,6 +148,9 @@ export const App: React.FC = () => {
{done && records.length > 0 && (
<p style={endStyle}>You've reached the end.</p>
)}
{done && records.length === 0 && appliedSearch !== "" && (
<p style={endStyle}>Nothing matches {JSON.stringify(appliedSearch)}.</p>
)}
</main>
);
};
Expand Down Expand Up @@ -150,6 +193,18 @@ const timestampStyle: React.CSSProperties = {
marginLeft: 8,
};

const inputStyle: React.CSSProperties = {
width: "100%",
boxSizing: "border-box",
marginTop: 16,
padding: "10px 12px",
borderRadius: 8,
border: "1px solid var(--rootsdk-border)",
background: "var(--rootsdk-background-secondary)",
color: "var(--rootsdk-text-primary)",
fontSize: 14,
};

const buttonStyle: React.CSSProperties = {
padding: "10px 16px",
borderRadius: 8,
Expand Down
16 changes: 14 additions & 2 deletions recipes/data-paginated-list/networking/src/list_service.proto
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,23 @@ package datapaginatedlist;
// next_cursor field. Empty string means "first page". Clients never
// inspect or construct cursors — they round-trip the value the server
// gave them. Server owns the encoding (this recipe uses base64-encoded
// JSON of the last seen id), and is free to change it without breaking
// clients.
// JSON of the last seen id AND the search term it was issued under), and
// is free to change it without breaking clients. A cursor is only meaningful
// within the query that produced it: pairing one with a different `search`
// seeks into the middle of a result set it never described, so the server
// detects the mismatch and starts over.
//
// search — optional case-insensitive substring filter, applied by the SERVER
// against the record label. This field exists because the alternative is a
// silent bug: a client that fetches a page and filters it locally can only
// ever find matches inside the page it happens to hold, and there is no
// error, no empty state, and no symptom until the list outgrows one page.
// A filtered list is still paginated — the filter narrows what is paged
// over, it does not replace paging.
message ListRecordsRequest {
uint32 page_size = 1;
string cursor = 2;
string search = 3;
}

// Page response.
Expand Down
Loading