Last quarter, a multi-tenant billing table I maintain crossed two million rows. Response times jumped from 14ms to 480ms whenever finance teams paged past page 400. Because each request ran LIMIT 25 OFFSET 150000, InnoDB scanned and discarded 150,000 rows every time. Switching that endpoint to MySQL keyset pagination dropped p95 latency back to 11ms across every page.
Most blog posts stop right after a single-table (created_at, id) < (?, ?) snippet. However, shipping cursor pagination in a real PHP backend exposes four ugly gaps. For example, naive guides skip multi-tenant index prefixes, unsigned base64 cursors, PDO’s HY093 native-prepare crash, and backward navigation. Here’s the exact PHP PDO and MySQL 8.4 blueprint I run in production.
Why MySQL Keyset Pagination Beats OFFSET on Large Tables
OFFSET looks harmless on staging data with 500 rows. That shortcut breaks under load. Even with a covering index, MySQL still walks every skipped row sequentially. As a result, query cost climbs linearly with page depth.
In addition, concurrent writes corrupt offset windows while users paginate. For example, suppose a Stripe webhook inserts three new invoices while someone clicks to page 3. The rows shift downward, so the user sees duplicate records. Instead, seeking from the last seen tuple anchors the window to one fixed B-tree spot.
Because MySQL jumps straight to the cursor via an index range scan, page 6,000 matches page 1. You’ll also watch replica CPU flatten out. InnoDB stops churning buffer pool pages just to discard skipped offsets.
Multi-Tenant Composite Index Order for MySQL Keyset Pagination
Index column order makes or breaks cursor queries. First, put equality filters like tenant_id on the far left of your composite index. That lets InnoDB narrow the B-tree to one tenant slice before running any range scan. Second, place your sort column and unique tie-breaker next in matching sort directions.
MySQL hates mixed sort directions here. Unless both tuple columns match the index direction, the optimizer skips row-constructor range scans. You can check the optimizer rules in the official MySQL 8.4 range optimization reference. Therefore, declare a descending composite index on (tenant_id, created_at DESC, id DESC) and keep both columns NOT NULL.
CREATE TABLE tenant_invoices (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
tenant_id INT UNSIGNED NOT NULL,
invoice_number VARCHAR(32) NOT NULL,
amount_cents INT UNSIGNED NOT NULL,
status ENUM('open', 'paid', 'void') NOT NULL DEFAULT 'open',
created_at DATETIME(6) NOT NULL,
PRIMARY KEY (id),
KEY idx_invoices_tenant_created_id (tenant_id, created_at DESC, id DESC)
) ENGINE=InnoDB;
-- Verify constant-time index range seek (0 filesort, ~26 rows examined)
EXPLAIN ANALYZE
SELECT id, invoice_number, amount_cents, status, created_at
FROM tenant_invoices
WHERE tenant_id = 42
AND (created_at, id) < ('2026-10-14 09:22:18.410200', 1849201)
ORDER BY created_at DESC, id DESC
LIMIT 26;
I tested this schema locally on PHP 8.4 and MySQL 8.4 inside my ServBay local development environment. While the old OFFSET 150000 query scanned 150,025 index entries, the tuple seek read just 26 rows. The difference wasn’t subtle.
Production PHP PDO Blueprint for Signed Cursor Pagination
Don’t trust raw base64 cursors. Because base64 is encoding rather than security, anyone can decode or tamper with your cursor JSON. Bad inputs can leak internal timestamps or trigger SQL warnings. Instead, I sign every cursor with hash_hmac() and validate it before opening a query.
1. Build an HMAC-Signed Cursor Codec
First, keep cursor encoding and signature verification inside a small value class. Also, include tenant_id inside the signed payload. Otherwise, a cursor issued for Tenant A could get replayed against Tenant B’s endpoint:
<?php
declare(strict_types=1);
final readonly class InvoiceCursor
{
public function __construct(
public int $tenantId,
public string $createdAt,
public int $id,
public string $direction = 'next',
) {}
}
final class InvoiceCursorCodec
{
public function __construct(private readonly string $hmacSecret) {}
public function encode(InvoiceCursor $cursor): string
{
$payload = json_encode([
't' => $cursor->tenantId,
'c' => $cursor->createdAt,
'i' => $cursor->id,
'd' => $cursor->direction,
], JSON_THROW_ON_ERROR);
$encoded = rtrim(strtr(base64_encode($payload), '+/', '-_'), '=');
$sig = hash_hmac('sha256', $encoded, $this->hmacSecret);
return $encoded . '.' . substr($sig, 0, 24);
}
public function decode(string $token, int $expectedTenantId): InvoiceCursor
{
$parts = explode('.', $token, 2);
if (count($parts) !== 2) {
throw new InvalidArgumentException('Malformed pagination cursor.');
}
[$encoded, $providedSig] = $parts;
$expectedSig = substr(hash_hmac('sha256', $encoded, $this->hmacSecret), 0, 24);
if (!hash_equals($expectedSig, $providedSig)) {
throw new InvalidArgumentException('Invalid cursor signature.');
}
$padded = strtr($encoded, '-_', '+/') . str_repeat('=', (4 - strlen($encoded) % 4) % 4);
$raw = base64_decode($padded, true);
if ($raw === false) {
throw new InvalidArgumentException('Corrupted cursor encoding.');
}
$data = json_decode($raw, true, 4, JSON_THROW_ON_ERROR);
if (
!is_array($data)
|| ($data['t'] ?? null) !== $expectedTenantId
|| !isset($data['c'], $data['i'], $data['d'])
|| !in_array($data['d'], ['next', 'prev'], true)
) {
throw new InvalidArgumentException('Cursor tenant or payload mismatch.');
}
return new InvoiceCursor(
tenantId: (int) $data['t'],
createdAt: (string) $data['c'],
id: (int) $data['i'],
direction: (string) $data['d'],
);
}
}
2. Run the Row-Constructor Query With Native PDO Prepares
Here’s a subtle PHP trap I’ve debugged twice on client audits. By default, pdo_mysql runs emulated prepares, which quote bound values client-side. However, production code should disable emulation via PDO::ATTR_EMULATE_PREPARES => false per the PHP PDO::setAttribute manual. Once you enable native prepares, repeating :created_at inside an expanded OR clause immediately throws SQLSTATE[HY093].
Using row-constructor syntax (created_at, id) < (:cursor_created_at, :cursor_id) avoids that crash because each placeholder appears once. Meanwhile, fetching $limit + 1 rows detects another page without running an expensive SELECT COUNT(*) query:
<?php
declare(strict_types=1);
final class InvoiceLedgerRepository
{
public function __construct(
private readonly PDO $pdo,
private readonly InvoiceCursorCodec $codec,
) {
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
/**
* @return array{items: list<array<string, mixed>>, nextCursor: ?string, prevCursor: ?string}
*/
public function paginate(int $tenantId, ?string $rawCursor, int $limit = 25): array
{
$pageSize = max(1, min($limit, 100));
$cursor = $rawCursor !== null ? $this->codec->decode($rawCursor, $tenantId) : null;
$isPrev = $cursor !== null && $cursor->direction === 'prev';
$orderClause = $isPrev ? 'ORDER BY created_at ASC, id ASC' : 'ORDER BY created_at DESC, id DESC';
$comparator = $isPrev ? '>' : '<';
if ($cursor !== null) {
$sql = "SELECT id, invoice_number, amount_cents, status, created_at
FROM tenant_invoices
WHERE tenant_id = :tenant_id
AND (created_at, id) {$comparator} (:cursor_created_at, :cursor_id)
{$orderClause}
LIMIT :fetch_limit";
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(':cursor_created_at', $cursor->createdAt, PDO::PARAM_STR);
$stmt->bindValue(':cursor_id', $cursor->id, PDO::PARAM_INT);
} else {
$sql = "SELECT id, invoice_number, amount_cents, status, created_at
FROM tenant_invoices
WHERE tenant_id = :tenant_id
{$orderClause}
LIMIT :fetch_limit";
$stmt = $this->pdo->prepare($sql);
}
$stmt->bindValue(':tenant_id', $tenantId, PDO::PARAM_INT);
$stmt->bindValue(':fetch_limit', $pageSize + 1, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll();
$hasMoreInDirection = count($rows) > $pageSize;
if ($hasMoreInDirection) {
array_pop($rows);
}
if ($isPrev) {
$rows = array_reverse($rows);
}
if ($rows === []) {
return ['items' => [], 'nextCursor' => null, 'prevCursor' => null];
}
$first = $rows[0];
$last = $rows[count($rows) - 1];
$hasNext = $isPrev ? true : $hasMoreInDirection;
$hasPrev = $isPrev ? $hasMoreInDirection : ($cursor !== null);
return [
'items' => $rows,
'nextCursor' => $hasNext
? $this->codec->encode(new InvoiceCursor($tenantId, $last['created_at'], (int) $last['id'], 'next'))
: null,
'prevCursor' => $hasPrev
? $this->codec->encode(new InvoiceCursor($tenantId, $first['created_at'], (int) $first['id'], 'prev'))
: null,
];
}
}
That response contract also keeps frontend code simple. For example, passing opaque nextCursor and prevCursor tokens works cleanly with the Angular 22 Resource API for async data fetching. Your UI never leaks database primary keys as editable query parameters.
MySQL Keyset Pagination vs. OFFSET: Production Benchmark Matrix
Even though I default to cursors on high-growth ledgers, I don’t rewrite tiny admin screens blindly. Instead, compare both strategies on a two-million-row InnoDB table before picking one:
| Metric / Requirement | OFFSET Pagination (LIMIT 25 OFFSET N) | MySQL Keyset Pagination (Composite Index) |
|---|---|---|
| Page 1 Query Latency (2M rows) | ~12ms (25 rows examined) | ~10ms (26 rows examined) |
| Page 6,000 Latency (OFFSET 150,000) | ~480ms (150,025 rows scanned & discarded) | ~11ms (26 rows examined via B-tree seek) |
| Concurrent Insert Consistency | Duplicates or skipped records when new rows arrive | Stable window anchored to exact tuple |
| Random Page Jumping (e.g. Page 48) | Supported natively | Not supported (sequential Next / Prev only) |
| Required Index Shape | Single sort index helps ordering, not skipping | (equality_col, sort_col DESC, id DESC) |
3 Edge Cases I Hit With Bidirectional Cursors and NULLs
Before shipping MySQL keyset pagination across production endpoints, guard against three subtle traps I hit in testing:
- First, never paginate on a nullable column: SQL evaluates
(paid_at, id) < (?, ?)asUNKNOWNwheneverpaid_atisNULL, so unpaid invoices vanish silently. Always sort on aNOT NULLtimestamp likecreated_atinstead. - Second, preserve fractional second precision: If your column uses
DATETIME(6)while PHP strips microseconds, rows inside the same second get skipped. Always keep exactDATETIME(6)strings straight from MySQL. - Third, never drop the unique tie-breaker: Sorting on
created_atalone breaks when batch jobs insert 500 rows in one millisecond. Becauseidis unique, pairing(created_at, id)guarantees strict ordering.
Frequently Asked Questions on Cursor Pagination
Why did my MySQL keyset pagination query ignore the composite index?
Usually, your index order or sort direction doesn’t match the query. First, place equality filters like tenant_id ahead of range columns. Second, align both tuple columns as DESC, DESC in the index. Finally, disable PDO emulated prepares so MySQL doesn’t coerce datetime or integer bindings during range optimization.
Can you build a Previous Page button with keyset pagination?
Yes, because you can flip both the tuple comparator and sort order for backward requests. Instead of < with ORDER BY created_at DESC, id DESC, query with > and ORDER BY created_at ASC, id ASC from the first visible row. Fetch limit + 1 rows, then call array_reverse() in PHP before returning JSON.
In short, keep OFFSET only for small internal screens that genuinely need random page numbers. For every multi-tenant feed, audit trail, or webhook log, MySQL keyset pagination keeps database latency flat. Pair it with HMAC-signed cursors and native PHP PDO prepares, and your queries won’t slow down as tables grow.

