Large APIs often expose millions of rows. If you naïvely return all of them, the client stalls, the network blows up, and the database has to scan the entire table for each request. Pagination is the first line of defense, but the way you paginate can make the difference between a snappy feed and a slow, inconsistent one.
TL;DR
- OFFSET is easy but becomes slow and flaky as the offset grows.
- CURSOR pagination keeps queries fast, preserves order, and handles concurrent changes.
- Use OFFSET for small, read‑only views; use CURSOR for production APIs, feeds, and high‑traffic endpoints.
- In Prisma, OFFSET is
skip/take; CURSOR usescursor+take+orderBywith a unique key.
Why Pagination Matters
Large result sets can overwhelm both the client and the server.
- Memory pressure: loading thousands of rows into memory can trigger GC pauses.
- Network latency: a single HTTP response can become huge, leading to timeouts.
- UX degradation: users expect instant feedback; slow pages frustrate them.
Even when you paginate, the strategy you choose can introduce duplicate or missing records. A careless implementation can produce a “jittery” list where items appear or disappear as the user scrolls, breaking the illusion of a stable feed.
Offset Pagination: The Familiar but Flawed Approach
Simplicity in SQL
OFFSET works by telling the database to skip a given number of rows and then return the next set. In Prisma this maps to skip and take:
const posts = await prisma.post.findMany({
skip: page * pageSize,
take: pageSize,
orderBy: { createdAt: 'desc' },
});
The query is straightforward and maps directly to the SQL LIMIT/OFFSET clause.
The Cost of Skipping
For small offsets, the database can satisfy the request quickly. However, as the offset grows, the engine still has to scan and discard the preceding rows. In a table with 10 million posts, a request for page 500 (offset = 10 000) forces the engine to read and skip 10 000 rows before it can deliver the next 20. The cost is linear with the offset, so latency can double or triple as users scroll deeper.
Data Shifts Between Pages
Because OFFSET does not anchor itself to any stable value, inserting or deleting rows between requests changes the shape of the result set. Imagine a user on page 3; an admin inserts a new post before page 3, pushing every row one slot down. The next request for page 3 will now return a different set, and the user may see a duplicate of the last item from page 2 or a missing item altogether. This “jumpiness” is especially problematic for feeds where consistency matters.
Cursor Pagination: The Robust Alternative
A Stable Reference Point
Cursor pagination replaces the numeric offset with a cursor: a value that identifies the last item returned in the previous page. The next request uses this cursor to fetch the next slice:
const posts = await prisma.post.findMany({
cursor: { id: lastSeenId },
skip: 1, // skip the cursor row itself
take: pageSize,
orderBy: { id: 'asc' },
});
Here, the cursor is the primary key (id). The database can use an index on id to jump directly to the desired row, and the cost of the query stays constant regardless of how many rows precede the cursor.
Consistency Under Concurrency
Because the cursor is anchored to a specific row, inserting or deleting rows after the cursor does not affect the slice you receive next. The only change that can affect the next page is the addition or removal of rows after the cursor. This guarantees that the user sees a stable sequence of items even when the underlying data changes rapidly.
Ordering Matters
Cursor pagination relies on a deterministic order. Typically you order by a unique, monotonically increasing key (e.g., createdAt + id, or just id). If you order by a non‑unique field, you risk returning duplicate rows or missing items. Always pair the cursor field with the primary key to enforce uniqueness.
When to Pick Which
| Scenario | Preferred Strategy | Why |
|---|---|---|
| Small, static datasets (e.g., admin tables) | OFFSET | Simple, no need for a cursor; performance is acceptable. |
| High‑traffic public APIs (e.g., social feeds) | CURSOR | Keeps latency low, handles concurrent writes, and provides a consistent user experience. |
| Legacy systems with no unique sortable field | OFFSET (with caution) | Cursor requires a stable key; if none exists, offset is the only option until you add one. |
| Pagination with “load more” UI that never goes back | CURSOR | No need for previous page; cursor works naturally with “infinite scroll.” |
Performance & Consistency Trade‑offs
- Latency: Cursor queries stay near-constant latency because the engine can jump directly to the cursor position. OFFSET latency grows linearly with the offset.
- Complexity: Cursor queries require a unique key and careful ordering. OFFSET is a one‑liner.
- Data Model Requirements: Cursor needs a stable, unique, and monotonically increasing key. If your data lacks this, you must add one (e.g., a surrogate
idor a composite ofcreatedAt+id). - Client State: With OFFSET, the client only needs the page number. With CURSOR, the client must store the last seen cursor value, which can be a stringified ID or a base64‑encoded composite key.
Real‑World Code Example (TypeScript + Prisma)
Below is a minimal PostsService that exposes both pagination strategies for a posts table. The table schema is:
model Post {
id Int @id @default(autoincrement())
title String
body String
createdAt DateTime @default(now())
}
Offset Pagination
// posts.service.ts
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export interface PaginatedResult<T> {
items: T[];
hasMore: boolean;
nextPage?: number;
}
export class PostsService {
async getPostsOffset(page: number, pageSize: number): Promise<PaginatedResult<Post>> {
const skip = (page - 1) * pageSize;
const posts = await prisma.post.findMany({
skip,
take: pageSize + 1, // fetch one extra to determine hasMore
orderBy: { createdAt: 'desc', id: 'desc' },
});
const hasMore = posts.length > pageSize;
if (hasMore) posts.pop(); // remove the extra row
return {
items: posts,
hasMore,
nextPage: hasMore ? page + 1 : undefined,
};
}
}
Explanation
- We fetch
pageSize + 1rows to know whether a next page exists. - The
orderByclause includesidto break ties when two posts share the samecreatedAt. - The client receives the next page number or
undefinedif the list ends.
Cursor Pagination
export interface CursorPagination<T> {
items: T[];
nextCursor?: string; // encoded cursor value
}
export class PostsService {
async getPostsCursor(cursor?: string, pageSize: number = 20): Promise<CursorPagination<Post>> {
const cursorObj = cursor ? { id: Number(cursor) } : undefined;
const posts = await prisma.post.findMany({
cursor: cursorObj,
skip: cursor ? 1 : 0, // skip the cursor row itself
take: pageSize + 1,
orderBy: { id: 'asc' }, // stable ordering on unique key
});
const hasMore = posts.length > pageSize;
if (hasMore) posts.pop();
return {
items: posts,
nextCursor: hasMore ? String(posts[posts.length - 1].id) : undefined,
};
}
}
Explanation
- The cursor is the
idof the last item returned. skip: 1ensures we do not include the cursor row again.take: pageSize + 1lets us detect if there are more items.- The client stores the
nextCursorand passes it back on the next request.
Error Handling & Edge Cases
- Invalid Cursor: If the cursor does not correspond to an existing record, Prisma will throw an error. Wrap the call in a try/catch and return a 400 Bad Request.
- Deleted Rows: If a row after the cursor is deleted, the next page will simply skip it; the user will not see it. This is acceptable because the cursor points to a specific row, not a position.
- Sorting on Multiple Fields: If you need to order by
createdAtthenid, you can use:
orderBy: [
{ createdAt: 'desc' },
{ id: 'desc' },
],
and adjust the cursor accordingly (e.g., composite cursor of both fields). Prisma supports composite cursors by passing an object with both fields.
Common Mistakes & Trade‑offs
| Mistake | Why it hurts | Fix |
|---|---|---|
| Using OFFSET on a table without an index on the order column | The engine scans the whole table for each offset | Add an index on the orderBy column; still, OFFSET will grow slower but not constant |
Relying on a non‑unique cursor key (e.g., only createdAt) |
Duplicate rows or missing rows when timestamps collide | Combine with id or another unique field |
Forgetting to skip: 1 when using a cursor |
The cursor row is returned again, causing duplicates | Always skip the cursor row itself |
Using a cursor that changes over time (e.g., a mutable status field) |
The cursor may point to a row that later becomes irrelevant | Use immutable fields or surrogate keys |
| Choosing a timestamp with gaps as cursor | Gaps can lead to missing items if the cursor lands on a non‑existent value | Use an auto‑incrementing primary key or composite key |
Key takeaways
- OFFSET is simple but its cost grows with the offset; it also suffers from data volatility.
- CURSOR pagination keeps queries fast, provides consistent ordering, and handles concurrent inserts/deletes gracefully.
- In Prisma, OFFSET maps to
skip/take; CURSOR usescursor,skip,take, and a stableorderBy. - Choose OFFSET for low‑traffic, static views; choose CURSOR for production APIs, feeds, and any scenario where latency and consistency matter.
- Always back cursors with a unique, monotonically increasing key; otherwise you’ll encounter duplicates or missing records.
FAQ
Why does OFFSET become slow for large offsets?
Because the database must scan and discard all preceding rows, so latency grows linearly with the offset. For example, page 500 with an offset of 10,000 rows forces the engine to read and skip 10,000 rows before delivering the next 20.
How does cursor pagination maintain consistency?
It anchors on a specific row key, so inserts or deletes before the cursor do not shift the slice; only changes after the cursor affect subsequent pages.
What ordering is required for cursor pagination?
A deterministic order using a unique, monotonically increasing key (e.g., id or createdAt + id) to avoid duplicates or missing rows.
When is OFFSET still acceptable?
For small, static datasets like admin tables where performance is fine and consistency is less critical.