# Add Cursor Pagination to an Axum API

Yes. An agent adds keyset pagination on created_at to the article list and feed of an Axum and SQLx API, keeps limit and offset working, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-cursor-pagination/axum/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how the list routes page today before it changes them. In an API shaped like launchbadge/realworld-axum-sqlx, `Cargo.toml` pins `axum` 0.3.4, `sqlx` 0.5 with the `postgres`, `uuid` and `time` features, `tokio` 1.14 and `tower-http` 0.2 for its `TraceLayer`. `src/http/articles/listing.rs` declares `ListArticlesQuery` with `tag`, `author`, `favorited`, `limit` and `offset`, defaults the last two to 20 and 0 in `list_articles`, and orders by `article.created_at desc`; `feed_articles` takes the same `limit` and `offset` through `FeedArticlesQuery` and has no `order by` at all, so its pages are not stable between requests. A comment on the `limit` field in that file already says what to do instead: paginate on an indexed column such as `created_at` and hand the client a `next` URL after `articles`, so the frontend never needs to know which column drives the cursor. `MultipleArticlesBody` returns `articles` and an `articles_count` that is the length of the current page. `migrations/4_article.sql` gives `article` a `created_at timestamptz not null default now()` and a GIN index on `tag_list`, but no index on `created_at`. `src/http/types.rs` wraps `OffsetDateTime` in `Timestamptz` with RFC 3339 `Serialize` and `Deserialize`, which is exactly what a cursor in a query string needs.

It adds the cursor beside the old parameters rather than in place of them. Both query structs gain `before: Option<Timestamptz>` and `before_id: Option<Uuid>`, and each `query_as!` gets one more predicate, a row comparison of `(article.created_at, article.article_id)` against the two parameters when they are set, so two articles created in the same instant still page without a gap or a repeat. `feed_articles` gets the `order by article.created_at desc, article.article_id desc` it was missing, and `list_articles` adds the `article_id` tiebreaker to its existing `order by`. A new `migrations/5_article_pagination.sql` creates an index on `article (created_at desc, article_id desc)`, which the `sqlx::migrate!()` call in `src/main.rs` embeds and applies at startup. `MultipleArticlesBody` gains `next: Option<String>` with serde's `skip_serializing_if` on it: when a page is full, it holds a relative URL such as `/api/articles?limit=20&before=<created_at>&before_id=<id>` with the caller's `tag`, `author` or `favorited` filter carried along, built by a small `next_link` function; when the page is short, the field is absent and the body is what it was before.

`query_as!` checks every statement against a live database at compile time and the repository ships no offline query data, so the agent starts Postgres in its sandbox and runs `cargo install sqlx-cli --features postgres` and `sqlx db setup` with the `DATABASE_URL` shape from `.env.sample`, the same two steps `.github/workflows/rust.yml` takes before `cargo build` and `cargo test`. The crate has one unit test, `test_slugify` in `src/http/articles/mod.rs`; the agent adds a `tests` module in `listing.rs` for `next_link`, covering a full page with filters, a short page, and a cursor that round-trips through `Timestamptz`. Then it runs the server with `cargo run`, registers a user through `POST /api/users`, creates more articles than one page holds through `POST /api/articles`, requests `/api/articles?limit=10`, follows `next` until it disappears, and checks that no slug appears twice and every slug appears once. The same walk over `/api/articles/feed` after following an author shows the feed is now ordered.

Last it runs the Realworld Postman collection the way the workflow does, `newman run` against `APIURL=http://localhost:8080/api`, to show the response shape still satisfies the spec, since a client that ignores `next` sees the fields it saw before. It runs `cargo fmt --check` and `cargo clippy` as well, and pastes the test output, the `curl` walk and the newman summary into the pull request.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add cursor pagination to the article list and feed of this Axum API and open a pull request. Read Cargo.toml, src/main.rs, src/http/mod.rs, src/http/articles/mod.rs, src/http/articles/listing.rs, src/http/types.rs, migrations/4_article.sql, .env.sample, README.md and .github/workflows/rust.yml first. Keep limit and offset working. Add before (an RFC 3339 timestamp through the existing Timestamptz type) and before_id (a UUID) to ListArticlesQuery and FeedArticlesQuery, filter with a row comparison on (created_at, article_id) when they are set, order both queries by created_at desc then article_id desc, and add a migration creating an index on article (created_at desc, article_id desc). Add an optional next field to MultipleArticlesBody, omitted when absent, that carries a relative URL to the following page with the caller's limit and filters. Add unit tests for the next link builder. Start Postgres, run sqlx db setup, cargo build and cargo test, then run the server, create enough articles to fill more than one page, walk the list and the feed through next with curl and paste the walk in the pull request. Run the Realworld Postman collection with newman as the CI workflow does and include its summary. Do not change the article shape or the comments routes.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that edits `src/http/articles/listing.rs`, adds `migrations/5_article_pagination.sql`, and touches nothing in `users.rs`, `profiles.rs` or `comments.rs`. The description shows one `curl` page with its `next` link, the last page without one, the new unit tests in the `cargo test` output and the newman summary.

On a repository with the `Rust` workflow, the pull request runs against a Postgres service: `sqlx db setup` applies the new migration, `cargo build` compiles the changed queries against it, `cargo test` runs the link tests, and the Postman collection runs against the started binary.

A reviewer checks that the row comparison and the index use the same column order, that `before` without `before_id` is refused or handled, that the `next` URL keeps the filters and never points a feed at another user's follows, and that `articles_count` still means what it did. Then they decide whether to deprecate `offset` in the API docs.

## Run it on every list endpoint still on limit and offset

A team with several Axum services sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own query structs and migrations, so a service on `chrono` instead of `time` gets a cursor type to match, and each run opens its own pull request.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request and the test output from.

## Why run it on Rush?

Pagination bugs hide at the boundaries: a repeated row where two timestamps tie, a skipped row when an insert lands mid-walk, a feed whose order changes between pages. SQLx checks the SQL at compile time only against a real database, so the work needs Postgres running next to the compiler. In a Rush sandbox the agent starts one, migrates it, compiles against it, fills it with articles and walks every page, and the run's record keeps each request and response, so the pull request shows the walk rather than describing it.

The change keeps the old parameters, adds one migration and one optional field, and builds on the `Timestamptz` type the repository already has, so there is nothing new for a reviewer to learn. The same request works on any Axum and SQLx API with a timestamped table.

## Frequently asked questions

### Will clients that send limit and offset keep working?

Yes. Both parameters stay, with the same defaults of 20 and 0, and a request without `before` returns the same rows in the same order as before, plus a `next` field when the page is full. Clients move to the cursor by following that link.

### Why compare on (created_at, article_id) and not created_at alone?

Two articles can share a `created_at` to the microsecond, and a cursor on the timestamp alone would skip or repeat one of them. The row comparison with `article_id` as the tiebreaker gives a total order, and the new index has the same two columns in the same direction so Postgres can use it.

### Does the change need a database to compile?

Yes. The `query_as!` macros check the SQL against `DATABASE_URL` at compile time and the repository keeps no offline query data, so the agent runs Postgres in its sandbox and `sqlx db setup` before `cargo build`, the same as the CI workflow.

### What is in the next URL?

A relative path with the caller's `limit`, the `created_at` and `article_id` of the last article on the page, and any `tag`, `author` or `favorited` filter the request had. The feed's link points back at `/api/articles/feed`. Nothing in it is secret: the ids are the same ones already in the page.

## More Axum jobs

- [Add Full-Text Search to an Axum API](https://getrush.ai/run/add-full-text-search/axum/)
- [Add Graceful Shutdown to an Axum API](https://getrush.ai/run/add-graceful-shutdown/axum/)
- [Add Health Checks to an Axum Service](https://getrush.ai/run/add-health-checks/axum/)

## The same job on other stacks

- [Add Cursor Pagination to a chi API from a Linear Issue](https://getrush.ai/run/add-cursor-pagination/chi/)
- [Add Cursor Pagination to a Cloudflare Worker on D1](https://getrush.ai/run/add-cursor-pagination/cloudflare-workers/)
- [Add Cursor Pagination to a Django REST Framework API from a Linear Issue](https://getrush.ai/run/add-cursor-pagination/django-rest-framework/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
