Cursor or page number: stable pagination for an article feed
Compare OFFSET and keyset under one ordering contract in MySQL 8.4: inserts and deletions between requests, equal timestamps, signed cursors, and traversal without a shared snapshot.
A reader opens an article feed, finishes the first page, and clicks Next. In the meantime, an editor publishes another article. If the next request simply skips the number of rows already shown, a familiar card can appear again. Deleting a record creates a different problem: an unread card can fall between the pages.
For this list, define what continues: a position in the current result set or movement after the last record shown. These are different contracts. Continue one article_demo on Symfony 8.1 and PHP 8.4+ with synthetic data in MySQL 8.4/InnoDB through native PDO; the pagination endpoint is added alongside earlier routes.
Start with an order that can be continued
Imagine a public feed for one site and one locale. It contains only published articles, newest first. The published_at field stores an integer time value. The exercise uses synthetic values that are easy to compare:
| ID | published_at | Title |
|---|---|---|
| 60 | 6000 | North |
| 50 | 5000 | River |
| 41 | 4000 | Bridge |
| 40 | 4000 | Garden |
| 30 | 3000 | Hill |
| 20 | 2000 | Forest |
Time alone is insufficient: Bridge and Garden have the same value. The order is therefore published_at DESC, id DESC. The unique ID breaks the tie. MySQL's ORDER BY documentation explains sorting and index use. Here, the unique key pair defines a total order rather than relying on an incidental order among rows with equal times.
In this schema, neither field permits NULL, and the ID is unique and positive. These conditions matter for the comparison we chose. If a product sorts by rating, text, or a nullable field, its contract needs a fresh definition: direction, tie-breaking rules, handling of missing values, and whether the key can change.
What the second page means
With a page size of 2, the first response contains 60, 50. A page number becomes an offset: skip = (page - 1) * limit. The next request skips the first rows of the current ordered result set:
SELECT id, title, published_at
FROM article
WHERE site = :site AND locale = :locale AND published = 1
ORDER BY published_at DESC, id DESC
LIMIT :take OFFSET :skip
In this example, take is the page size plus one: the extra row is used only to detect whether more data exists. skip and take are bound as integer parameters through PDOStatement::bindValue, rather than interpolated into SQL from the query string.
Now article 70 appears ahead of the older records. The second offset page returns 50, 41: River repeats, even though the query correctly carried out the instruction to skip the beginning of the current list. If 60 is deleted instead, the second page becomes 40, 30, skipping Bridge. The arithmetic is not wrong. The position no longer denotes the same boundary.
Page numbers remain useful for an interface that jumps to an arbitrary part of a small list. A link to the second page simply describes a new request for current data, rather than a preserved selection seen by an earlier reader.
A boundary instead of a count of skipped rows
Keyset pagination remembers the pair belonging to the last article returned. After River, that means this card's time and ID. When moving in descending order, the next query selects smaller pairs:
SELECT id, title, published_at
FROM article
WHERE site = :site AND locale = :locale AND published = 1
AND (published_at, id) < (:after_time, :after_id)
ORDER BY published_at DESC, id DESC
LIMIT :take
MySQL comparison operators support comparisons of value pairs. For our non-NULL fields, the condition means an earlier time, or an equal time with a smaller ID. The latter clause lets traversal continue after Bridge and still include Garden.
After a new record is inserted ahead of the feed, the River boundary remains unchanged, so the expected continuation is 41, 40. Even deleting River itself does not remove the values stored in the cursor; there is no need to look up the deleted row. This is a property of this particular pair-based contract. A cursor containing only an ID and looking up its time again would behave differently.
The first page uses the same filters and order, but no boundary condition. The next cursor is built from the last row actually returned to the client. The extra row used for has_more must not accidentally become the boundary: that would make it disappear between responses.
A cursor belongs to a particular query
The client receives next_cursor and sends it back without parsing it. AIP-158 requires opaque tokens and separately warns that a page token is not authorization. The teaching format below is deliberately inspectable to expose the boundary; it does not implement AIP's structural-obfuscation requirement. In this exercise, site and locale are always applied again in the SQL filter.
The teaching token contains a format version, site, locale, order name, and boundary pair. JSON is encoded as base64url and accompanied by an HMAC. The code uses hash_hmac and hash_equals. This protects integrity; it does not encrypt the readable values. The example uses a publicly known synthetic key and is not intended for public deployment.
Validation rejects an incorrect signature, a different scope, an unknown version, extra fields, invalid types, and ambiguous JSON representations. The page size may change within its bounds because it does not change the continuation pair. Changing a filter or sort order, however, starts a new traversal. A restricted API must authorize data access separately on every request; a signed cursor grants no such permission.
Where stability ends
A newer article inserted ahead of the current boundary will not appear while continuing the old traversal. Readers can see it by refreshing the beginning of the feed. This is an expected property of reading onward, not a record lost from the database.
A backdated insertion beyond the boundary, however, can appear on the next page. If an unread article's published_at changes so that it jumps ahead of the cursor, traversal can miss it. If an already read record moves behind the cursor, it can appear a second time. Deletion and withdrawal from publication also change the response's membership.
A pair of values does not freeze data. InnoDB consistent reads define data visibility within a transaction; the independent HTTP requests in this exercise do not share one continuing read transaction. Even REPEATABLE READ does not create a shared snapshot across separate requests. Exporting a fixed set requires a separate contract, such as a stored selection or a versioned snapshot. A simple upper time bound will not protect against every subsequent change to older records.
Response boundaries are part of the contract
The teaching endpoint accepts a size from 1 to 50, and OFFSET pages from 1 to 1000. A cursor is limited to 1024 bytes. An array instead of a string, an unknown parameter, page combined with a cursor, or an invalid number produces an error. These are the example's own strict rules, not universal values for every API.
The response, built with Symfony JsonResponse, contains cards, has_more, and the appropriate continuation. At the end of the permitted OFFSET window, window_end explains why there is no continuation even if the database contains more data. An empty selection is successful; an SQL error produces a separate failure instead of masquerading as an empty page.
There is no exact overall total here. The has_more flag describes this particular read only: the extra record might be deleted before the next request. Clients must accept an empty end to traversal. Binding a count, cards, and every subsequent page to one snapshot would be a different, more expensive requirement.
Compare behavior between requests
The HTTP checks use a disposable schema on actual MySQL 8.4, prepared through App\Infrastructure\MysqlLab under the guarded test fixture, with standard Kernel reboots between requests. Separate native PDO connections share the schema. Changes through the writable connection finish before the next HTTP request: the checks cover OFFSET repeats and omissions, keyset continuation after insertions and deletion of the boundary row, and refusal to initialize twice. A separate migrator prepares the schema; application requests execute no DDL. This is a sequential experiment rather than a concurrent-load benchmark.
| Change after the first page | Expected OFFSET | Expected keyset |
|---|---|---|
| Insert 70 ahead of the list | 50, 41 | 41, 40 |
| Delete 60 | 40, 30 | 41, 40 |
| Delete boundary record 50 | Positions are recalculated | 41, 40 |
Which approach to choose
For sequential feeds with a stable key, keyset expresses movement after the boundary already seen. For a small list with arbitrary jumps by page number, OFFSET can be simpler. An immutable export needs an additional solution regardless of navigation style.
The schema includes a composite index with site, locale, and state filters before the ordering fields. MySQL's multiple-column index documentation explains the use of index prefixes. Check the actual plan, including the value-pair comparison, and cost against your own data with EXPLAIN; this exercise provides no performance measurements or promised speedup.
Use 64-bit PHP 8.4+, PDO_MYSQL, MySQL 8.4, and the dependencies of the existing Symfony 8.1 project. Add src/PaginationDemo, FeedDemoController, InitializePaginationDemoCommand, queries/pagination-demo, and fixtures/pagination-schema.sql to the same article_demo, preserving earlier configuration. Below are the schema and synthetic seed data, not services configuration. The table uses InnoDB and CHECK constraints; site and locale are VARCHAR with utf8mb4_0900_bin, while title and internal_note are LONGTEXT.
CREATE TABLE article (
id BIGINT SIGNED NOT NULL PRIMARY KEY,
site VARCHAR(32) NOT NULL CHECK (site IN ('alpha', 'beta')),
locale VARCHAR(16) NOT NULL CHECK (locale IN ('uk', 'ru', 'en')),
published TINYINT NOT NULL CHECK (published IN (0, 1)),
published_at BIGINT SIGNED NOT NULL CHECK (published_at BETWEEN 0 AND 253402300799),
title LONGTEXT NOT NULL,
internal_note LONGTEXT NOT NULL,
CONSTRAINT article_positive_id CHECK (id > 0),
INDEX article_feed (site, locale, published, published_at DESC, id DESC)
) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin;
-- pagination-seed
INSERT INTO article VALUES
(60, 'alpha', 'uk', 1, 6000, 'North', 'internal'),
(50, 'alpha', 'uk', 1, 5000, 'River', 'internal'),
(41, 'alpha', 'uk', 1, 4000, 'Bridge', 'internal'),
(40, 'alpha', 'uk', 1, 4000, 'Garden', 'internal'),
(30, 'alpha', 'uk', 1, 3000, 'Hill', 'internal'),
(20, 'alpha', 'uk', 1, 2000, 'Forest', 'internal'),
(99, 'beta', 'uk', 1, 9000, 'Other site', 'internal'),
(98, 'alpha', 'en', 1, 9000, 'Other locale', 'internal'),
(97, 'alpha', 'uk', 0, 9000, 'Draft', 'internal');
For the HTTP module, first prepare a dedicated teaching schema in MySQL and two accounts: a migrator for explicit initialization and a runtime account without CREATE, ALTER, or DROP. Configure their connections in the same application; the test wrapper does not automatically configure the HTTP module's connections. Then run from the application root:
File config/services.mysql_pagination.yaml:
services:
app.pagination_runtime_connection:
class: PDO
factory: ['App\Infrastructure\FixtureDatabase', 'runtimeConnection']
arguments:
$dsn: '%env(DEMO_PAGINATION_DB_DSN)%'
$user: '%env(DEMO_PAGINATION_DB_USER)%'
$password: '%env(DEMO_PAGINATION_DB_PASSWORD)%'
app.pagination_migrator_connection:
class: PDO
factory: ['App\Infrastructure\FixtureDatabase', 'runtimeConnection']
arguments:
$dsn: '%env(DEMO_PAGINATION_DB_DSN)%'
$user: '%env(DEMO_PAGINATION_DB_MIGRATOR_USER)%'
$password: '%env(DEMO_PAGINATION_DB_MIGRATOR_PASSWORD)%'
For a local run, create a separate empty schema and two distinct accounts as a MySQL administrator. Replace the placeholders with your own values. Runtime has DML only; supply the migrator only to a separate initialization process. Save runtime variables in untracked .env.local. This example does not transfer data from old SQLite files.
CREATE DATABASE demo_pagination CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin;
CREATE USER 'demo_pagination_r'@'127.0.0.1' IDENTIFIED BY '<runtime-password>';
CREATE USER 'demo_pagination_m'@'127.0.0.1' IDENTIFIED BY '<migrator-password>';
GRANT SELECT, INSERT, UPDATE, DELETE ON demo_pagination.* TO 'demo_pagination_r'@'127.0.0.1';
GRANT CREATE, ALTER, INDEX, REFERENCES, SELECT, INSERT, UPDATE, DELETE, TRIGGER ON demo_pagination.* TO 'demo_pagination_m'@'127.0.0.1';
DEMO_PAGINATION_DB_DSN="mysql:host=127.0.0.1;port=3306;dbname=demo_pagination;charset=utf8mb4"
DEMO_PAGINATION_DB_USER=demo_pagination_r
DEMO_PAGINATION_DB_PASSWORD="<runtime-password>"
read -r -p 'Migrator user: ' DEMO_PAGINATION_DB_MIGRATOR_USER
read -r -s -p 'Migrator password: ' DEMO_PAGINATION_DB_MIGRATOR_PASSWORD
printf '
'
export DEMO_PAGINATION_DB_MIGRATOR_USER DEMO_PAGINATION_DB_MIGRATOR_PASSWORD
php bin/console app:pagination-demo:initialize
unset DEMO_PAGINATION_DB_MIGRATOR_USER DEMO_PAGINATION_DB_MIGRATOR_PASSWORD
The command explicitly creates the teaching table and inserts synthetic data in the configured MySQL schema through a separate migrator; repeat initialization is refused. This is not a destructive reset, an atomic schema upgrade, or an automatic transfer of data from an old SQLite file. MySQL DDL can implicitly commit a transaction, so initialization is separate from business transactions. Never apply the teaching SQL to another database. Ordinary HTTP requests neither create the schema nor seed data. Endpoint: GET /pagination-demo/sites/{site}/articles/{locale}; alpha/beta are public synthetic sites. An unknown site returns 404, an invalid locale or query returns 400, and an SQL failure returns 503. Controller responses have no-store.
The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.
Check the current example against an owned disposable MySQL schema:
bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/PaginationDemo