Full answer
Every list endpoint needs a limit; returning 200,000 attendance rows in one response hurts the database, the network and the client.
Offset pagination
- Parameters:
limitandoffset, orpageandsize. - SQL:
ORDER BY id LIMIT 20 OFFSET 400. - Pros: simple, supports "go to page 37", easy totals for page numbers.
- Cons: the database still reads and discards the first 400 rows, so deep pages get slow on large tables. If rows are inserted or deleted between requests, items shift: users can see duplicates or miss rows.
COUNT(*)for totals is also expensive on big tables.
Cursor (keyset) pagination
- The response includes
next_cursor, usually the last item's sort key encoded as an opaque string (base64 of{"id": 420}). - Next query:
WHERE id > 420 ORDER BY id LIMIT 20, which uses the index directly. - Pros: consistent speed at any depth, stable under inserts.
- Cons: no jumping to arbitrary pages; ordering must be on a unique, indexed key (use a tie-breaker like
(created_at, id)for non-unique sort columns). - Good for feeds, logs, infinite scroll and public APIs with large data.
Implementation tips:
- Put parameters in a dependency (or a Pydantic model with
Query()), with a default and a hard maximum (le=100). - Return an envelope:
{"items": [...], "next_cursor": "...", "has_more": true}. Fetchlimit + 1rows to know if more exist without counting. - Keep cursors opaque so you can change their format later. Sign them if clients must not tamper with them.
- Libraries such as
fastapi-paginationimplement both styles if you prefer not to build your own.
python
import base64
import json
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, Query
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
ROWS = [{"id": i, "roll_no": f"R{i:03d}"} for i in range(1, 8)] # stands in for a table ordered by id
class Page(BaseModel):
items: list[dict]
next_cursor: str | None
has_more: bool
def encode(last_id: int) -> str:
return base64.urlsafe_b64encode(json.dumps({"id": last_id}).encode()).decode()
def decode(cursor: str) -> int:
try:
return json.loads(base64.urlsafe_b64decode(cursor.encode()))["id"]
except Exception:
raise HTTPException(status_code=400, detail="Invalid cursor")
def cursor_params(limit: Annotated[int, Query(ge=1, le=100)] = 3, cursor: str | None = None):
return {"limit": limit, "after_id": decode(cursor) if cursor else 0}
@app.get("/attendance", response_model=Page)
def list_attendance(p: Annotated[dict, Depends(cursor_params)]):
# SQL: SELECT ... WHERE id > :after_id ORDER BY id LIMIT :limit + 1
rows = [r for r in ROWS if r["id"] > p["after_id"]][: p["limit"] + 1]
has_more = len(rows) > p["limit"]
items = rows[: p["limit"]]
return Page(items=items, next_cursor=encode(items[-1]["id"]) if has_more else None, has_more=has_more)
@app.get("/attendance-offset")
def list_offset(limit: Annotated[int, Query(ge=1, le=100)] = 3, offset: Annotated[int, Query(ge=0)] = 0):
return ROWS[offset: offset + limit]
c = TestClient(app)
page = c.get("/attendance").json()
seen = [r["roll_no"] for r in page["items"]]
while page["has_more"]:
page = c.get("/attendance", params={"cursor": page["next_cursor"]}).json()
seen += [r["roll_no"] for r in page["items"]]
print("cursor pages:", seen)
first = [r["roll_no"] for r in c.get("/attendance-offset").json()]
ROWS.insert(0, {"id": 0, "roll_no": "R000"}) # a new row arrives at the top
second = [r["roll_no"] for r in c.get("/attendance-offset?offset=3").json()]
print("offset pages after an insert:", first, second, "<- R003 repeated")
print(c.get("/attendance?limit=500").status_code, c.get("/attendance?cursor=bad!").status_code)
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. A Python list stands in for the table; comments show the equivalent SQL. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): cursor pages: ['R001', 'R002', 'R003', 'R004', 'R005', 'R006', 'R007'] offset pages after an insert: ['R001', 'R002', 'R003'] ['R003', 'R004', 'R005'] <- R003 repeated 422 400
Key points
- Every list endpoint needs a limit with a maximum
- Offset is simple but slow deep and unstable under changes
- Cursor uses WHERE key > last and stays fast and stable
- Fetch limit + 1 to compute has_more without COUNT
- Make cursors opaque; use unique, indexed sort keys
Common mistakes
- Shipping list endpoints with no limit or no maximum
- Using OFFSET deep into tables with millions of rows
- Cursor pagination on a non-unique sort key without a tie-breaker
- Running COUNT(*) on every request just to show a total
Follow-ups
- How would you paginate by created_at when timestamps can repeat?
- How do you show 'page 3 of 40' with cursor pagination, or should you?
- How would you sign cursors so clients cannot tamper with them?
Tips
- Compare the two styles on speed and consistency
- Explain the limit + 1 trick
- Make the parameters a reusable dependency