Skip to content

Lesson 26 of 59API design in depth

List Endpoints That Scale

Build keyset pagination on compound cursors, sign cursors so clients cannot forge them, and design filters and sorts that stay on an index.

22 min read0/5 questions

The admin orders page worked fine at launch. A year later the table has 40 million rows, page 3,000 takes eight seconds, and the finance team's nightly export is missing a few orders every night while containing duplicates of others. None of this shows up in tests, because test databases have a hundred rows and nobody writes to them while a test pages through. In Designing a CRUD API you met the basic offset versus cursor trade-off. This lesson is what a list endpoint needs once the data is big and moving: compound cursors that never skip rows, cursors clients cannot tamper with, honest counts, and filters that stay fast.

The bug in WHERE created_at < :last

Most list endpoints sort by time, newest first. The obvious keyset query uses the last row's timestamp as the cursor: "give me rows older than the last one you saw". That works until two rows share a timestamp, which happens constantly with bulk imports, batch jobs, or a timestamp column with second precision. If the page ends in the middle of a tie, the rows after the boundary that share the timestamp are skipped, because they are not strictly older.

The fix is a compound cursor: the sort column plus a unique tiebreaker, compared as a pair. SQL supports this directly with a row comparison: (created_at, id) < (:ts, :id) means "older, or the same time and a smaller id". Run both versions on seven orders where three share 09:05:

Pythonkeyset_ties.py
import sqlite3 db = sqlite3.connect(":memory:")db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, created_at TEXT NOT NULL)")db.execute("CREATE INDEX ix_orders_created_id ON orders (created_at, id)")rows = [ (1, "09:00"), (2, "09:05"), (3, "09:05"), (4, "09:05"), (5, "09:10"), (6, "09:15"), (7, "09:15"),]db.executemany("INSERT INTO orders VALUES (?, ?)", rows) def walk(where, params_of, limit=2): """Page newest first until the end. Returns every id seen, in order.""" seen, last = [], None while True: sql = "SELECT id, created_at FROM orders" params = () if last is not None: sql += " WHERE " + where params = params_of(last) sql += " ORDER BY created_at DESC, id DESC LIMIT ?" page = db.execute(sql, params + (limit,)).fetchall() if not page: return seen seen += [row[0] for row in page] last = page[-1] broken = walk("created_at < ?", lambda last: (last[1],))keyset = walk("(created_at, id) < (?, ?)", lambda last: (last[1], last[0]))print("created_at only:", broken)print("(created_at, id):", keyset)print("missing:", sorted(set(keyset) - set(broken)))
Output
Press Run (⌘ Enter) to see what happens.
Paging newest first, limit 2, cursor on created_at only
7 09:15
0
6 09:15
1
5 09:10
2
4 09:05
3
3 09:05
4
2 09:05
5
1 09:00
6

Page 1: orders 7, 6. The cursor is 09:15.

1/4
Predict the outputPython

In the code above, the broken walk is run with limit=3 instead. What does it print?

print(walk("created_at < ?", lambda last: (last[1],), limit=3))
Need a nudge? Hints walk you through it.

Keyset in Postgres and SQLAlchemy

The production query looks like this:

SELECT id, status, total_cents, created_at
FROM orders
WHERE status = ANY(:statuses)
  AND (created_at, id) < (:cursor_ts, :cursor_id)
ORDER BY created_at DESC, id DESC
LIMIT :limit_plus_one;

It is only fast with an index that matches the filter and the sort, in that order: CREATE INDEX ON orders (status, created_at, id). Postgres walks the index from the cursor position and stops after limit + 1 entries, so page 3,000 costs the same as page 1. A B-tree can be read backwards, so the same index serves ASC and DESC. Check it with EXPLAIN (ANALYZE, BUFFERS) as in Postgres for Developers: you want an Index Scan (or Index Only Scan) with a small rows figure, and no Sort node.

In SQLAlchemy 2.x the row comparison is tuple_:

app/repositories/orders.py
from sqlalchemy import select, tuple_
 
stmt = (
    select(Order)
    .where(Order.status.in_(filters.status))
    .order_by(Order.created_at.desc(), Order.id.desc())
    .limit(limit + 1)
)
if cursor is not None:
    stmt = stmt.where(tuple_(Order.created_at, Order.id) < (cursor.created_at, cursor.id))

Row comparison has one limit: every column must sort in the same direction. For a mixed sort such as total_cents DESC, id ASC, expand it by hand: total_cents < :t OR (total_cents = :t AND id > :id). That form is harder for the planner to turn into one index range, so mixed sorts are a good reason to say no to a feature request.

Why OFFSET is slow even with an index

OFFSET 400000 does not jump to row 400,000. B-tree pages do not know how many entries come before them, so the database reads and throws away 400,000 index entries (and often the table rows too) before it returns the first one you asked for. The cost grows linearly with depth. Keyset turns "skip N" into "seek to this key", which a B-tree does in O(log n). The trade-off is that you lose random access: no "jump to page 3,000". For admin screens that need it, cap the offset (say 10,000 rows) and offer filters instead, which is what most large sites do.

Opaque, signed cursors

If the cursor is ?after_ts=2026-10-01T09:05:00Z&after_id=4, clients will build it themselves. Then you can never change the sort, the key format or the id type, because someone's code depends on it. Hyrum's law applies to cursors too.

Make the cursor opaque: a single string that clients store and send back without reading. A good design packs four things into it:

  • the key values of the last row, [created_at, id];
  • a fingerprint of the filters and sort it was issued for, so a cursor from status=paid cannot be replayed against status=open (which would silently produce a wrong page);
  • a format version, so after a deploy that changes the sort columns you can reject old cursors with a clear 400 instead of returning garbage;
  • an HMAC signature, so clients cannot edit the key to probe for rows.

Base64 is encoding, not encryption. Anyone can decode the payload, so do not put anything secret in it. The signature stops forgery; it does not hide content.

Pythoncursor.py
import base64, hashlib, hmac, json SECRET = b"load-me-from-settings" # one key per environment, rotated like any secretCURSOR_VERSION = 1 def _b64(data: bytes) -> str: return base64.urlsafe_b64encode(data).rstrip(b"=").decode() def _unb64(text: str) -> bytes: return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)) def query_fingerprint(filters: dict, sort: str) -> str: canonical = json.dumps({"f": filters, "s": sort}, sort_keys=True) return hashlib.sha256(canonical.encode()).hexdigest()[:16] def encode_cursor(last_row: dict, filters: dict, sort: str) -> str: payload = { "v": CURSOR_VERSION, "k": [last_row["created_at"], last_row["id"]], "q": query_fingerprint(filters, sort), } body = json.dumps(payload, separators=(",", ":")).encode() sig = hmac.new(SECRET, body, hashlib.sha256).digest()[:16] return _b64(body) + "." + _b64(sig) class BadCursor(Exception): pass def decode_cursor(cursor: str, filters: dict, sort: str) -> list: try: body_part, sig_part = cursor.split(".") body, sig = _unb64(body_part), _unb64(sig_part) except ValueError: raise BadCursor("malformed") expected = hmac.new(SECRET, body, hashlib.sha256).digest()[:16] if not hmac.compare_digest(sig, expected): raise BadCursor("signature mismatch") payload = json.loads(body) if payload["v"] != CURSOR_VERSION: raise BadCursor("cursor from an older version") if payload["q"] != query_fingerprint(filters, sort): raise BadCursor("cursor was issued for different filters") return payload["k"] filters = {"status": ["paid"]}c = encode_cursor({"created_at": "2026-10-01T09:05:00Z", "id": "ord_3"}, filters, "-created_at")print(c)print(decode_cursor(c, filters, "-created_at")) for label, attempt in [ ("tampered", lambda: decode_cursor("x" + c[1:], filters, "-created_at")), ("other filters", lambda: decode_cursor(c, {"status": ["open"]}, "-created_at")), ("garbage", lambda: decode_cursor("hello", filters, "-created_at")),]: try: attempt() except BadCursor as exc: print(label, "->", exc)
Output
Press Run (⌘ Enter) to see what happens.

hmac.compare_digest compares in constant time, so an attacker cannot learn the signature byte by byte from response timings. In the route, turn BadCursor into a 400 with a clear message (the next lesson, Error Responses Clients Can Rely On, gives it a proper shape).

has_more, going backwards, and the cost of a count

has_more. Fetch limit + 1 rows. If you got the extra one, there is a next page: drop it and build next_cursor from the last row you keep. This costs one extra row and saves a second query.

Backwards. A before cursor flips the comparison and the order ((created_at, id) > (:ts, :id) ORDER BY created_at ASC, id ASC), then you reverse the rows in Python so the page still reads newest first. Return both next_cursor and prev_cursor, and the client never has to know the direction trick.

Counts. Product will ask for "Showing 1-50 of 40,212,118". On Postgres, an exact COUNT(*) with a filter has to visit every matching row (MVCC means there is no stored row count that is correct for your transaction). On a big table that is seconds per request, on every page. Options, cheapest first:

  • Leave it out. "Load more" and infinite scroll do not need it.
  • Return a capped count: SELECT count(*) FROM (SELECT 1 FROM orders WHERE ... LIMIT 1001) t, and show "1,000+".
  • Return an estimate for unfiltered lists from the planner's statistics (SELECT reltuples FROM pg_class WHERE relname = 'orders'), labelled as approximate.
  • Compute exact counts asynchronously and cache them, if someone truly needs them.

One Page model, one shape everywhere

Use a single generic response model so every list endpoint looks the same to clients and in the OpenAPI document:

app/api/pagination.py
from pydantic import BaseModel
 
 
class Page[T](BaseModel):
    items: list[T]
    next_cursor: str | None = None
    prev_cursor: str | None = None
    has_more: bool = False
 
 
@router.get("/orders")
def list_orders() -> Page[OrderOut]:  # filters added in the next section
    ...

FastAPI generates a separate schema per use (Page_OrderOut_), so generated clients get a typed items. The alternative is RFC 8288 Link headers, as GitHub does: Link: <https://api.example.com/orders?cursor=abc>; rel="next". Headers keep the body a bare list, but they are awkward for browser clients (CORS must expose the header) and invisible to people reading JSON. The envelope is the more common choice for new APIs, and it can grow new fields without breaking anyone.

Filters as a typed model

Since FastAPI 0.115 you can declare all query parameters as one Pydantic model. That gives you one place for validation, cross-field rules, and a hard "no unknown parameters" policy:

app/api/orders.py
from datetime import datetime
from typing import Annotated, Literal
 
from fastapi import Query
from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, model_validator
 
SortKey = Literal["-created_at", "created_at", "-total_cents"]
 
 
class OrderFilters(BaseModel):
    model_config = ConfigDict(extra="forbid")
 
    status: list[Literal["open", "paid", "refunded"]] = []
    customer_id: str | None = None
    created_after: AwareDatetime | None = None
    created_before: AwareDatetime | None = None
    sort: SortKey = "-created_at"
    limit: int = Field(50, ge=1, le=200)
    cursor: str | None = None
 
    @model_validator(mode="after")
    def check_range(self):
        if self.created_after and self.created_before and self.created_after >= self.created_before:
            raise ValueError("created_after must be earlier than created_before")
        return self
 
 
@router.get("/orders")
def list_orders(filters: Annotated[OrderFilters, Query()]) -> Page[OrderOut]:
    ...

?status=paid&status=refunded arrives as a list. extra="forbid" turns a typo such as ?stauts=paid into a 422 instead of a silently unfiltered result, which is the kind of bug that leaks data to the wrong screen. Use created_after and created_before (or _gte and _lt) for ranges, with half-open intervals so adjacent ranges never overlap.

Resist a filter language (?filter=status eq 'paid' and total gt 100). Every operator you expose is a query shape you must keep fast forever, and a generic DSL lets clients combine fields no index supports. Offer the filters your screens need, each backed by an index, and add more when someone asks.

Sorting follows the same rule. The SortKey literal is an allow-list, and each value maps to an ordered list of columns that always ends in the unique id. Never pass a client string into order_by by name.

Sparse fieldsets (?fields=id,status) cut payload size for mobile clients, but each combination is a different response shape to test and cache. Most teams add them only when a payload is genuinely too large.

Match the pairs0/5 matched

Match each symptom to its most likely cause.

Choose an item, then its match on the other side.

?q= across customer name, email and order notes is no longer filtering. A LIKE '%smith%' cannot use a B-tree index and scans the table. For a modest need, Postgres full-text search is enough: a generated tsvector column, a GIN index on it, and WHERE search @@ websearch_to_tsquery('english', :q). Reach for a search engine (OpenSearch, Elasticsearch, Typesense, Meilisearch) when you need typo tolerance, relevance tuning, facets across many fields, or search across services. That adds a second store to keep in sync, so do not do it for one search box.

Quick check
A client sends a cursor issued for ?status=paid along with ?status=open. What should the endpoint do?
Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

Order the steps a keyset list endpoint takes for one request.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
Why does the list endpoint fetch limit + 1 rows?
Need a nudge? A hint rules out a wrong answer.
Key terms
keyset pagination
Paging by seeking to the last seen key (WHERE key < :last) instead of skipping rows with OFFSET.
compound cursor
A cursor made of the sort column plus a unique tiebreaker, such as (created_at, id).
row comparison
SQL comparing tuples in order, (a, b) < (x, y), which expresses a compound keyset in one predicate.
opaque cursor
A string clients pass back without reading, so the server can change its contents freely.
HMAC
A keyed hash that proves a value was produced by the holder of the secret and not edited.
capped count
Counting only up to a limit (for example 1,001) and showing 1,000+, to avoid a full scan.
query parameter model
A Pydantic model declared as Annotated[Model, Query()] that holds all of an endpoint's query parameters.