⚙️ Offset vs Cursor Pagination: Which Approach Works Better for Applications with Millions of Records?

⚙️ Offset vs Cursor Pagination: Which Approach Works Better for Applications with Millions of Records?

A product team launches an activity feed that initially holds a few thousand events. The familiar page controls work well: users click “next,” the API receives page=8, and the database returns another slice.

Then the product grows. The feed holds millions of rows, new events arrive every second, and a user reports seeing the same item twice while scrolling. Another user opens page 5,000 and waits far longer than expected.

Nothing about the feature looks unusual from the interface. Underneath, though, pagination determines how much work the database must do, whether users see a stable sequence, and whether an API can scale predictably.

Offset and cursor pagination solve different navigation problems. Choosing well means understanding the query plan, the data’s ordering rules, and what “next page” really means when records are changing.

🧭 Pagination Is Controlled Access to a Large Result Set

Pagination divides a potentially large query result into smaller responses. Rather than transferring every matching row, an API returns a bounded batch and information needed to request another batch.

This protects response times, memory use, network bandwidth, browser rendering, and database capacity. It also forces a product decision: should people jump directly to an arbitrary page, or should they move efficiently through an ordered stream?

📄 What Offset Pagination Means

Offset pagination tells the database to skip a specified number of matching rows and return the next limit. A conventional SQL query looks like this:

SELECT id, created_at, title
FROM posts
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 1000;

The request might expose page=51&per_page=20, then calculate the offset as (page - 1) × per_page. It is easy to explain because the API resembles numbered pages in a book.

🔖 What Cursor Pagination Means

Cursor pagination uses a marker from the last item already returned. Instead of asking the database to skip 1,000 rows, the client says, in effect, “continue after this position in the sorted sequence.”

SELECT id, created_at, title
FROM posts
WHERE (created_at, id) < ('2025-03-08T10:15:00Z', 8421)
ORDER BY created_at DESC, id DESC
LIMIT 20;

The marker is commonly encoded into an opaque cursor such as eyJjcmVhdGVkQXQiOiIuLi4iLCJpZCI6ODQyMX0. Clients should treat it as a token, not as a value to construct or edit.

📚 The Book Shelf Analogy

Imagine a shelf sorted by publication time. Offset pagination asks a librarian to start at the beginning, count past 10,000 books, and hand you the next 20. Cursor pagination gives the librarian the identifier of the last book you held and asks for the next 20 after it.

Real database engines are more sophisticated than a person counting books, but the analogy captures the core cost difference. Deep offsets often require work proportional to the rows skipped, while a well-indexed cursor query can seek near the boundary and continue from there.

⏱️ Why Deep Offsets Become Expensive

An OFFSET does not mean the database can usually teleport to result number 1,000,001. It must still identify and discard preceding qualifying rows, even if it returns only 20 rows to the application.

Sorting, filtering, joins, row visibility checks, and fetching non-indexed columns can add to that work. Query planners and storage engines differ, so developers should inspect actual execution plans rather than assume a precise cost model. Still, latency commonly grows as the offset gets deeper.

🗂️ Indexes Make or Break Both Designs

Pagination is not merely an API-format decision. The database needs an index that supports the filter and the requested order. For a feed scoped to one account and sorted newest first, an index conceptually beginning with account_id, then created_at, then id is often relevant.

The exact definition depends on the database and query. A cursor predicate that cannot use a suitable index may still scan or sort a large set, losing much of cursor pagination’s performance advantage.

🧷 A Cursor Needs a Deterministic Order

A cursor identifies a position only when the result order is stable and unambiguous. Sorting solely by created_at is risky because many records can share the same timestamp resolution.

Add a unique tie-breaker, usually the primary key:

ORDER BY created_at DESC, id DESC

The cursor must include both values, and its comparison must match both directions. This turns “after the last item” into a precise boundary rather than a vague timestamp range.

🔄 Inserts Create Offset Pagination Drift

Suppose a user receives page one of a newest-first feed, then ten newer records arrive before they request page two. The original items have shifted down. Offset page two may now include records that were already at the bottom of page one.

Conversely, deletes can pull items upward and cause a later offset page to skip records. This is not necessarily a database bug; it is the natural result of applying an absolute position to a collection that changes between requests.

🧭 Cursors Handle Forward Movement More Gracefully

With a cursor based on the last item in page one, newly inserted records that sort before that boundary do not normally interfere with fetching items after it. The user can continue through the older portion of the sequence without offset drift.

That consistency has limits. Updates to the ordering field, changing filters, deletions, and different transaction snapshots can still affect what appears. Cursor pagination improves a common case; it is not a universal guarantee of an immutable view.

🧊 Snapshot Consistency Is a Separate Requirement

Some workflows require a repeatable, frozen traversal: exports, financial reconciliation, audits, or batch processing. Ordinary cursors usually do not provide this by themselves, because each request may observe the database at a different moment.

Possible designs include querying a versioned snapshot, recording a cutoff value, materializing the selected IDs, or running the export asynchronously. The right choice depends on correctness requirements, retention rules, and the cost of holding or recreating a snapshot.

🔢 The Main Advantage of Offset: Random Access

Offset pagination naturally supports requests such as “show page 427.” That matters for administrative tables, searchable catalogs, printed-style reports, and interfaces where users deliberately jump among numbered pages.

A cursor cannot efficiently answer “go to page 427” unless the application stores checkpoints or walks through prior pages. If direct positioning is a core product requirement, offset may be the clearer and more honest choice despite its scaling limits.

📱 The Main Advantage of Cursors: Continuous Browsing

Infinite scroll, event timelines, chat history, logs, notifications, and API feeds are fundamentally sequential experiences. Users usually want more results after what they have just seen, not a mathematically exact page number.

Cursor pagination aligns with that behavior. It gives the server a boundary it can often seek from efficiently, and it avoids pretending that a changing feed has permanently meaningful page numbers.

↔️ Previous Pages Need Deliberate Design

Forward cursor pagination is straightforward. Backward navigation needs a reverse query: locate records before the first item currently displayed, order them in the reverse direction for efficient retrieval, then reverse the returned rows before sending them to the client.

For a descending feed, this may mean using a greater-than predicate and ascending database order internally. Test this carefully; “previous” bugs often come from reversing only the comparison or only the result list.

🎯 Filters Are Part of Cursor Identity

A cursor produced for “open tickets assigned to Maya, newest first” is not valid for “all tickets” or “priority first.” The cursor position only has meaning within one exact query shape.

Servers can either reject mismatched cursors or bind cursor state to filter and sort parameters. At minimum, preserve the same filters, tenant scope, permissions, and ordering while clients follow a cursor chain.

🧪 A Practical API Response Shape

Cursor APIs usually return data plus navigation metadata. They do not need to expose database implementation details.

{
  "data": [ ... ],
  "page": {
    "nextCursor": "opaque-token",
    "previousCursor": null,
    "hasNextPage": true
  }
}

For offset APIs, return the current page and limit, and include a total only when it is genuinely useful and affordable. A total count can be much more expensive than retrieving one small indexed page on very large filtered datasets.

🔐 Opaque Tokens Protect the Contract

A cursor may encode sort values, an ID, direction, a query version, or an expiry time. Encoding is not encryption, so do not put secrets in it merely because it is Base64-like.

Opaque tokens let the server evolve its schema and prevent clients from coupling to internal fields. Signing a token can detect tampering, while server-side cursor state can support richer workflows at the cost of storage and expiration management.

🧰 Offset Parameters Need Guardrails Too

Simple inputs invite unbounded requests. Validate that page and limit are positive integers, set a maximum page size, and define behavior for excessive offsets.

A maximum offset, a switch to cursor-only traversal beyond a threshold, or an asynchronous export may be more responsible than allowing a single request to consume disproportionate database resources. Rate limits and authorization checks still apply regardless of pagination style.

📊 Counting Rows Is Not Free Metadata

Users often ask for “Page 1 of 9,438,” but exact totals can require scanning or aggregating a large filtered result set. Caching, estimates, precomputed summaries, or an omitted total may be better trade-offs.

Cursor pagination usually favors signals such as hasNextPage. Fetching one extra row beyond the requested limit is a common way to calculate that signal: return the requested number, and use the extra row only to determine whether more data exists.

🧱 Compound Sorts Require Compound Cursors

Applications frequently sort by more than time: priority descending, due date ascending, then ID ascending, for example. The cursor must retain every sort component needed to continue after the boundary.

Lexicographic conditions can become verbose in SQL, especially where tuple comparisons are unavailable or null ordering is involved. Treat cursor logic as tested query infrastructure, not an ad hoc string concatenation exercise.

🌫️ Null Values and Collation Can Surprise You

Sorting text depends on collation rules, and databases differ in how they order null values unless explicitly instructed. If a cursor stores a human-readable name, a collation change or inconsistent comparison setting can invalidate positions.

Prefer stable, indexed fields for high-volume keyset pagination. When nulls are allowed, specify null placement in the order and model it in the cursor predicate. Test accented text, equal values, and missing values—not just tidy sample data.

✏️ Mutable Sort Keys Can Move Records

A ticket sorted by updated_at moves when someone edits it. A product sorted by inventory moves when stock changes. If the record crosses a cursor boundary between requests, a user may encounter it twice or not at all.

For a live feed, that may be acceptable. For strict traversal, use an immutable ordering key such as creation sequence, establish a cutoff, or record the target set before paging through it.

⚖️ Comparing the Trade-Offs

Concern Offset pagination Cursor pagination
Deep navigation Often becomes progressively costly Usually efficient with supporting indexes
Jump to page N Natural Not naturally supported
Changing ordered data Can produce duplicates or gaps Usually steadier during forward traversal
API simplicity Easy to explain and debug Needs token and ordering design
Total count display Common, but may be expensive Usually replaced by continuation signals
Typical fit Small tables and random-access UIs Large feeds and sequential APIs

“Usually” matters in this comparison. A cursor query with poor indexing can disappoint, and a shallow offset query over a modest, stable table can be perfectly appropriate.

🏗️ Database-Specific Behavior Still Matters

PostgreSQL, MySQL, SQL Server, Oracle, and managed search systems expose different syntax, planner behavior, isolation models, and index capabilities. ORMs may also generate queries that differ from the SQL a developer expected.

Use the platform’s plan inspection tools with realistic filters and data distributions. Measure the first page and deep traversal, then examine rows scanned, sort operations, index use, and latency under representative concurrency.

🔍 Search Results Add Another Layer

Full-text and relevance-ranked search can have ties, score changes, index refresh delays, and query-time ranking behavior. Cursor-like mechanisms are still common, but the cursor may need to include score and a unique ID, or use a search engine’s dedicated continuation feature.

Do not assume a relational database cursor design transfers unchanged to a search service. Read the engine’s consistency and pagination semantics, especially when relevance scores are recalculated.

🧑‍💻 ORM Helpers Are Useful, Not a Substitute for Understanding

Frameworks often provide methods named paginate, simplePaginate, cursorPaginate, or similar. These reduce boilerplate but cannot choose a correct ordering field, create the right index, or decide whether an exact count is worth its cost.

Inspect generated SQL for critical endpoints. Confirm that the helper handles tied values, reverse traversal, nulls, and user-supplied sorting safely. A convenience method is only as reliable as the query assumptions behind it.

🚫 Common Cursor Pagination Mistakes

  • Using only a non-unique timestamp: tied rows can vanish or repeat.
  • Using an offset behind a cursor-shaped API: a token does not improve performance if it merely stores a page number.
  • Allowing arbitrary sort fields: this can defeat indexes and create unsafe query construction.
  • Changing the order mid-chain: the cursor boundary no longer describes the result set.
  • Forgetting tenant and permission scope: cursor reuse must never reveal records outside the current authorization context.

These failures tend to appear only after data volume, write frequency, or permission complexity rises—exactly when correcting an API contract is most disruptive.

🧯 Common Offset Pagination Mistakes

  • Using offset for a high-traffic endless feed: deep requests can impose increasing work on the database.
  • Promising stable pages over rapidly changing data: page numbers are positions, not snapshots.
  • Running an exact count on every request: count work may dominate the endpoint.
  • Leaving page size uncapped: one client can request an impractical response.
  • Ignoring an explicit order: without ORDER BY, result order is not a reliable contract.

🧭 Choosing for an Admin Table

Consider a back-office customer directory where staff search, sort, inspect, and jump to a specific numbered page. The dataset may be large, but random access and a visible total can be valuable interaction features.

Offset pagination can be a sensible default here, especially with selective filters and reasonable depth limits. For expensive broad searches, consider narrowing filters, offering cursor-based export, or replacing page-number navigation with search and bounded result views.

📡 Choosing for Feeds, Logs, and Events

Consider a monitoring interface listing application events newest first. New rows constantly arrive, operators typically scroll backward through history, and the table can become enormous. This is a strong cursor-pagination use case.

Use an immutable or carefully defined ordering key, include a unique tie-breaker, index it with the relevant scope columns, and communicate that newly arriving events appear on refresh rather than being inserted unpredictably into an already viewed sequence.

🪜 Migration Can Be Incremental

You do not need to convert every endpoint at once. Start with endpoints that show deep-page latency, handle high write rates, or power continuous scrolling. Add cursor parameters and metadata while temporarily supporting the existing page-based contract.

Versioning or a clearly documented opt-in avoids surprising clients. Instrument usage, test the new behavior with realistic data, and set a retirement plan for the older interface only after consumers have moved.

✅ A Decision Checklist

Before implementing pagination, answer these questions:

  • Do users need to jump to an arbitrary page, or mainly continue forward and backward?
  • How large can the result set become, and how deep do users actually navigate?
  • How frequently are rows inserted, deleted, or reordered?
  • What deterministic order, including tie-breakers, defines the result?
  • Which index supports that order alongside required filters?
  • Is an exact total a product requirement, or would “more results” be enough?
  • Does the workflow need a consistent snapshot rather than a live view?

The answers often make the choice clearer than a generic rule such as “cursors are always faster.”

🏁 The Core Principle: Match Navigation to Data Behavior

Offset pagination is a useful tool for bounded, page-oriented, random-access experiences. Its limitations become visible when users repeatedly request deep positions in a large, changing ordered set.

Cursor pagination is built for sequential movement through that kind of set, provided its order is deterministic and properly indexed. It trades page-number convenience for efficient continuation and generally more stable forward browsing.

The best implementation is not the trendiest one. It is the one whose navigation model, consistency expectations, indexes, and API contract honestly match the application’s data.

Choose offset when page positions are the feature; choose cursors when efficient movement through a large ordered stream is the feature. Test the actual queries, document the guarantees, and let the product’s behavior—not a default framework setting—make the final decision. ⚙️📚🚀