# Add Cursor Pagination to an Actix Web API

Yes. An agent adds keyset pagination to an Actix Web list endpoint backed by Postgres, with a next cursor in the response and tests, and opens a pull request.

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

## What the agent does

The agent reads the crate in its own sandbox before it changes it. In a service like `databases/postgres` in actix/examples, `Cargo.toml` takes `actix-web` 4.11, `serde`, `dotenvor` and `derive_more` from the workspace, which is on edition 2024 with a minimum Rust of 1.98, and adds `confik`, `deadpool-postgres` with its `serde` feature, `tokio-postgres` and `tokio-pg-mapper` with its derive crate. `src/config.rs` builds an `ExampleConfig` with `server_addr` and a `deadpool_postgres::Config` from environment variables through `confik`, and `README.md` walks through `createuser`, `createdb`, loading `sql/schema.sql` with `psql` and writing a `.env` with `SERVER_ADDR` and the `PG.*` values.

The list endpoint returns everything. `src/main.rs` registers `web::resource("/users")` with `GET` on `get_users` and `POST` on `add_user`, both taking the pool through `web::ThinData<Pool>`. `src/db.rs` reads `sql/get_users.sql`, which is `SELECT $table_fields FROM testing.users;`, substitutes `User::sql_table_fields()` for the placeholder, prepares it and maps every row with `from_row_ref`. `src/models.rs` defines `User` with `email`, `first_name`, `last_name` and `username` and derives `PostgresMapper` for the `users` table; it is also the request body of `POST /users`. `sql/schema.sql` creates `testing.users` with `id BIGSERIAL PRIMARY KEY` and a unique `username`, so a sortable, indexed key already exists but never leaves the database. `src/errors.rs` maps `MyError` to `404` and `500` responses. The crate has no tests, and the workspace `ci.yml` runs `cargo test --workspace --all-features` without a Postgres service, which the `diesel-async` sibling handles by wrapping its database tests in `#[cfg(not(feature = "postgres_tests"))]`, so the `--all-features` run skips them.

The agent splits the model so the id can be returned without being accepted on input: `NewUser` keeps the four writable fields and is the body of `POST /users`, and `User` gains `id: i64` and remains the mapped row, so `$table_fields` now includes `id` in both the select and the `RETURNING` clause of `sql/add_user.sql`. A `ListUsersQuery` with optional `after` and `limit` is read with `web::Query`; `limit` defaults and is capped in one `const` pair, and a value over the cap is clamped rather than rejected. `sql/get_users.sql` becomes a keyset query: `WHERE ($1::BIGINT IS NULL OR id > $1) ORDER BY id LIMIT $2`, which uses the primary key index and costs the same on the last page as on the first. `db::get_users` takes the two parameters and binds them. The response becomes `{"users": [...], "next_cursor": ...}`, where `next_cursor` is the last row's id when the page was full and is omitted otherwise, so a client loops until the field is absent.

Tests are added in two layers. Unit tests in `main.rs` cover the query parsing and clamping and the `next_cursor` rule with no database. Integration tests under the same `#[cfg(not(feature = "postgres_tests"))]` gate, as `diesel-async` does, start from the `.env` the README describes, insert enough users to fill more than one page, walk `/users` with `curl`-shaped requests through `actix_web::test`, and assert that pages do not overlap, that the walk ends with no `next_cursor`, and that a bad `after` value answers `400`. The agent starts Postgres in the sandbox, loads `sql/schema.sql`, runs `cargo test -p db-postgres` with default features, runs the server and pastes a two-page walk in the pull request, and updates `README.md` with the new query parameters and response shape.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add cursor pagination to GET /users in the databases/postgres crate of this Actix Web repository and open a pull request. Read the workspace Cargo.toml, .github/workflows/ci.yml, databases/postgres/Cargo.toml, README.md, .gitignore, sql/schema.sql, sql/get_users.sql, sql/add_user.sql and every file under src, and look at how databases/diesel-async wraps its database tests in cfg(not(feature = \"postgres_tests\")) so the CI run with --all-features skips them. Split the model into NewUser for the POST body and User with an id for rows, so RETURNING and the select include the id. Read after and limit from the query string with a default and a cap, change get_users.sql to a keyset query ordered by id that uses the primary key, and return {users, next_cursor} where next_cursor is the last id of a full page and is left out otherwise. Add unit tests for the query parsing and the next_cursor rule, and database tests under the same cfg(not(feature = \"postgres_tests\")) gate that fill more than one page, walk the pages, assert no overlap and an end with no cursor, and check that a non-numeric after answers 400. Start Postgres in the sandbox, load sql/schema.sql, run cargo test -p db-postgres with default features, cargo clippy and the workspace cargo check, run the server and paste a two-page walk with curl in the pull request. Update README.md. Do not change the POST route or the error type.",
  "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 on its own branch, scoped to `databases/postgres`. The diff changes `src/main.rs`, `src/db.rs`, `src/models.rs`, `sql/get_users.sql`, `sql/add_user.sql`, `Cargo.toml` for the new feature and `README.md`, and adds the test module. The workspace `Cargo.toml` and the other crates are untouched, which a reviewer can confirm from the file list. The description shows two `curl` calls, the first without `after` and the second with the `next_cursor` from the first, and the response bodies that prove the pages meet without overlap.

The run's full record at `GET /o/{org}/sessions/{id}/messages` keeps the Postgres start, the schema load, the `cargo test` output with each test named and the feature flag visible, `cargo clippy` and the workspace `cargo check` that the CI job also runs. `GET /o/{org}/p/{project}/sessions/{id}/changes` returns each file's diff.

Before merging, a reviewer checks that the keyset query orders by the same column it filters on, that `limit` is clamped rather than passed through to Postgres, that `next_cursor` is omitted rather than `null` on the last page as the description states, and that the `--all-features` run in CI skips the database tests, since it has no Postgres service. Nothing is deployed.

## Run it on every list endpoint without a limit

A team can send one `POST /o/{org}/sessions` per service with this prompt and the repository in `resources`, and let each run read its own schema: a table keyed by a UUID gets a cursor on `(created_at, id)` with a row comparison instead of a bare integer, and a crate on `sqlx` gets `query_as!` instead of `tokio-pg-mapper`. Each run opens its own pull request on its own branch.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with `session_url` to read the pull request from. A `request_id` per repository makes the batch safe to run twice, and a key may have at most `max_concurrent` runs in progress, four by default.

## Why run it on Rush?

Keyset pagination is easy to describe and easy to get subtly wrong: a page that repeats a row at the boundary, a cursor that leaks the last page, a limit nobody capped. Each of those shows up only when a real table has more rows than one page and someone walks it to the end. The agent fills the table, walks it, and asserts the boundaries in its own sandbox, with Postgres running beside the crate.

The pull request carries the walk, the test names and the diff, and the trajectory keeps every command, so a reviewer who does not want to set up a database can still see that the second page starts where the first ended.

## Frequently asked questions

### Why a plain integer cursor and not an opaque token?

The table's key is `BIGSERIAL`, so the id is already monotonic and indexed, and a client can store it as a number. An opaque base64 token adds encoding on both sides without changing the query. If you expose the API to third parties and want to keep the freedom to change the sort later, say so in the prompt and the agent encodes the cursor and rejects tokens it did not mint.

### Does this break existing clients of GET /users?

The array moves under a `users` key and is limited to one page, so a client that read the bare array must change. The pull request says so in its first paragraph. Ask for a compatibility mode in the prompt and the agent keeps the bare array when no `limit` or `after` is sent, with a deprecation note in the README.

### What about the response of POST /users?

It now includes the new row's `id`, because `User` carries the id and `RETURNING $table_fields` expands to include it. The request body is the new `NewUser` type with the same four fields as before, so a client that created users keeps working and gains the id it needs as a cursor.

### Will the database tests run in CI?

Not by default. The workspace workflow starts no Postgres service, so the tests carry `#[cfg(not(feature = "postgres_tests"))]`, as the `diesel-async` crate's tests do, and the workspace's `cargo test --workspace --all-features` turns that feature on and skips them. The agent runs them with default features in its sandbox and pastes the output; enabling them in CI is a workflow change the pull request describes but does not make.

## More Actix Web jobs

- [Add Database Migrations to an Actix Web App](https://getrush.ai/run/add-database-migrations/actix/)
- [Add Graceful Shutdown to an Actix Web App](https://getrush.ai/run/add-graceful-shutdown/actix/)
- [Add Health Checks to an Actix Web Server](https://getrush.ai/run/add-health-checks/actix/)

## The same job on other stacks

- [Add Cursor Pagination to an aiohttp App](https://getrush.ai/run/add-cursor-pagination/aiohttp/)
- [Add Cursor Pagination to an Axum API](https://getrush.ai/run/add-cursor-pagination/axum/)
- [Add Cursor Pagination to a chi API from a Linear Issue](https://getrush.ai/run/add-cursor-pagination/chi/)

## 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/)
