Home / Articles / Web Development
Web Development

Fast Pagination API: When Does OFFSET Become a Problem?

Pagination seems simple until the amount of data grows and the next page starts to feel slow. Understand the limits of OFFSET, how to use keyset pagination, and practical steps to make your PHP and MySQL API more stable...

Pagination API yang Tetap Cepat: Kapan OFFSET Mulai Jadi Masalah?

Pagination almost always appears when a website displays a list of articles, transactions, products, or users. Initially, the LIMIT and OFFSET pattern feels sufficient: retrieve 20 records, then skip a number of records according to the page number.

The problem is, this method can become costly when users request pages that are far back. MySQL still needs to skip many rows before returning the requested results. At the same time, new incoming data or deleted old data can cause the content of the page to shift, resulting in repeated or missed items.

This means that pagination is not just about presentation. It touches on API design, database indexing, order consistency, and user experience.

Understanding the Issues with OFFSET

A classic pagination example usually looks like this:

SELECT id, title, created_at
FROM articles
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 10000;

This query requests 20 articles after the first 10,000 rows. Conceptually, it is easy to understand, but the database cannot simply β€œjump” to row 10,000 without reading or skipping the previous rows.

MySQL can optimize queries with LIMIT, especially if the order of data is supported by an index. However, MySQL documentation also explains that the order can become non-deterministic if the columns in ORDER BY have the same values. Therefore, use an additional unique column, such as id, as a tie-breaker or final order determiner. This detail is often overlooked and becomes a source of inconsistent pagination results.

OFFSET does not always need to be avoided. For initial pages, small data sets, or pages that are rarely accessed, this approach is still practical. Problems usually arise when the table grows, page numbers can be very far, or the endpoint is called repeatedly by the application.

Alternatively: Keyset Pagination

Keyset pagination, often referred to as cursor pagination, does not require the database to skip a number of rows. Instead, the API sends a marker from the last item that has been received.

For example, a list of articles is sorted by created_at and id. After receiving the last item with the timestamp 2026-01-15 10:30:00 and ID 245, the next request can use the condition:

SELECT id, title, created_at
FROM articles
WHERE (created_at, id) < ('2026-01-15 10:30:00', 245)
ORDER BY created_at DESC, id DESC
LIMIT 20;

With this pattern, the database searches for data after a certain position based on the index, rather than counting from the beginning each time. For ascending order, the operator is usually adjusted to >.

In practice, the cursor does not have to contain two raw values like date and ID. The API can package it into a token, then encode it before sending it to the client. The goal is not to make the token secret, but to maintain the internal format without being overly dependent on the database structure.

Ensure Stable Order

Cursor pagination can only be relied upon if the order is clear. Do not just write:

ORDER BY created_at DESC

If many rows have the same creation time, the database is free to determine the order among those rows. Use a unique column as a tie-breaker:

ORDER BY created_at DESC, id DESC

The index should also follow the query pattern. For the example above, a composite index like the following can be a starting point:

CREATE INDEX idx_articles_created_id
ON articles (created_at, id);

This does not automatically guarantee that the query will always be optimal. Data distribution, WHERE conditions, the number of columns retrieved, and the execution plan still need to be checked with EXPLAIN. MySQL provides EXPLAIN to help see how the optimizer executes the query.

Example PHP Endpoint with PDO

Here is a simple example of an endpoint that receives a cursor containing the timestamp and ID of the last item. In a real application, the cursor should be validated, formatted consistently, and signed to prevent easy tampering.

$limit = min((int) ($_GET['limit'] ?? 20), 100);
$cursorDate = $_GET['cursor_date'] ?? null;
$cursorId = isset($_GET['cursor_id']) ? (int) $_GET['cursor_id'] : null;

$sql = 'SELECT id, title, created_at
        FROM articles';
$params = [];

if ($cursorDate !== null && $cursorId !== null) {
    $sql .= ' WHERE (created_at, id) < (:cursor_date, :cursor_id)';
    $params['cursor_date'] = $cursorDate;
    $params['cursor_id'] = $cursorId;
}

$sql .= ' ORDER BY created_at DESC, id DESC LIMIT :limit';

$stmt = $pdo->prepare($sql);
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);

foreach ($params as $key => $value) {
    $stmt->bindValue(':' . $key, $value);
}

$stmt->execute();
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);

It is important to note that not all parts of the query can be treated as PDO parameters. Values like the row limit must be handled as integers, while column names or sort directions should be selected from an allowed list, rather than directly accepting user input.

Do Not Always Count Total Pages

Page number-based pagination usually requires information like β€œhow many pages are there?”. To obtain this, applications often run COUNT(*). On large tables or complex filters, this total calculation can become an additional burden.

For interfaces like feeds, notification lists, or activity logs, users often do not need the total page count. Responses like has_next or the next cursor are sufficient.

If the total data is indeed important, consider when the calculation is performed. Do not make the total count a requirement for every list request if that information is not truly used by the user.

OFFSET or Cursor? Choose Based on Needs

  • Use OFFSET if the data is not large, users need to jump to a specific page, and a simple implementation is more important.
  • Use Cursor for feeds, infinite scroll, logs, transactions, or lists that change frequently.
  • Use Stable Order with primary and unique columns, such as created_at, id.
  • Add Appropriate Indexes, then check the results with EXPLAIN.
  • Limit Page Size so that a single request does not return too much data.
  • Avoid Counting Totals if the interface only needs information on whether there is more data available.

What You Can Do Now

Take one of the most frequently called list endpoints, then note the SQL query, table size, largest page number, and response time. Test the first page, middle pages, and pages that are far back with EXPLAIN.

If OFFSET is still fast and the product needs page numbers, there is no reason to change it just to follow trends. However, if far pages start to slow down or results frequently change when new data comes in, keyset pagination is worth considering.

A good decision is not about choosing the most sophisticated technique, but about selecting pagination that aligns with how users read data and how the database stores it.

Sources & Further Reading

– Rio Yotto @rioyotto