# Add Cursor Pagination to a Litestar API

Yes. An agent adds keyset pagination to a Litestar list endpoint with an opaque cursor, a typed schema and tests on Postgres, keeping the offset route, in a PR.

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

## What the agent does

The agent reads how lists work today. In an app laid out like litestar-org/litestar-fullstack, every list endpoint is limit/offset through advanced-alchemy: `src/py/app/domain/admin/controllers/_audit.py` builds its dependencies with `create_service_dependencies(AuditLogService, filters={...})`, naming `pagination_type` as `limit_offset`, `pagination_size` 50, `sort_field` `created_at` descending, a `search` across `actor_email,action,target_label` and `in_fields` for `action`, `target_type`, `target_id` and `actor_id`; `list_logs` calls `audit_service.list_and_count(*filters, *conditions)` and returns `OffsetPagination[AuditLogEntry]`. `uv.lock` pins advanced-alchemy 1.8.2, whose `service/pagination.py` defines only `OffsetPagination` (`items`, `limit`, `offset`, `total`); its `PaginationFilter` base class says subclasses may implement cursor-based pagination, but none ships. The model in `src/py/app/db/models/_audit_log.py` extends `UUIDv7AuditBase`, so `id` is a time-ordered UUID v7 with `created_at` and `updated_at` beside it, and `src/py/app/domain/admin/schemas/_audit.py` describes rows as msgspec structs that render in camelCase.

The audit log is where offset pagination hurts: new rows arrive while an admin scrolls, so page 2 repeats what page 1 showed. The agent adds a keyset endpoint beside the offset one rather than replacing it, because the React admin in `src/js/web/src/components/admin/audit-log-table.tsx` and the generated client under `src/js/web/src/lib/generated/api` consume `total` and page numbers today. The cursor is the `id` of the last row returned: a UUID v7 sorts by creation time, so a query for `id` below the cursor, ordered by `id` descending, with a limit of one more than requested, is both the order the table already uses and a stable position in it. The extra row tells the service whether there is more without a second count query.

Concretely, `AuditLogService` in `src/py/app/domain/admin/services/_audit.py` gets `list_after(after, limit, *conditions)`, which builds a `select(m.AuditLog)` with the keyset condition and the same `action`, `target_type`, `actor_id` and `end_date` conditions the controller already assembles, and passes it to `self.repository.list(statement=...)`. A `CursorPage[T]` struct in `src/py/app/lib/schema.py` carries `items`, `limit`, `next_cursor` (`None` on the last page) and `has_more`, camelized like the other schemas. The controller gains a handler with `operation_id` `AdminScrollAuditLogs` at `/api/admin/audit/scroll`, taking `after: UUID | None` and a `limit` capped at 200 through `Parameter(le=200)`, under the same `requires_superuser` guard. The response is typed, so `/schema` shows it and `openapi-ts` can regenerate the web client from `src/js/web/openapi-ts.config.ts` when the table switches to a load-more button.

Tests follow the repository's own fixtures. `src/py/tests/integration/conftest.py` provides `client`, `superuser_token_headers` and a per-test `db_cleanup` against the pytest-databases Postgres from `src/py/tests/conftest.py`; the agent adds `src/py/tests/integration/admin/routes/test_audit_scroll.py`, which writes entries through `AuditLogService.log_action`, walks the cursor until `has_more` is false, asserts no row repeats and none is skipped, and asserts that a row inserted between two requests does not shift the next page. It runs `uv run pytest src/py/tests` the way `.github/workflows/ci.yaml` does, with the `--cov-fail-under=65` floor from `pyproject.toml`, and `make lint`, which is ruff, mypy, pyright, slotscheck, biome and codespell, before opening 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 admin audit log of this Litestar app. Read pyproject.toml, uv.lock, src/py/app/domain/admin/controllers/_audit.py, src/py/app/domain/admin/services/_audit.py, src/py/app/domain/admin/schemas/_audit.py, src/py/app/db/models/_audit_log.py, src/py/app/lib/schema.py, src/py/app/lib/deps.py, src/py/tests/conftest.py and src/py/tests/integration/conftest.py first. Keep the existing limit/offset route unchanged. Add a CursorPage struct to src/py/app/lib/schema.py with items, limit, next_cursor and has_more. Add AuditLogService.list_after(after, limit, *conditions) that selects rows with id below the cursor ordered by id descending and fetches limit + 1 rows to compute has_more, reusing the action, target_type, actor_id and end_date conditions. Add GET /api/admin/audit/scroll with after and limit query parameters (limit at most 200) under the superuser guard, returning CursorPage[AuditLogEntry] with the last row's id as next_cursor. Add src/py/tests/integration/admin/routes/test_audit_scroll.py that seeds entries through log_action, walks the cursor to the end, checks for no repeats or gaps, and checks that a row inserted mid-walk does not shift the next page. Run uv run pytest src/py/tests and make lint until they pass, then open a pull request that explains the cursor format and why the offset route stays.",
  "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

The pull request changes `src/py/app/domain/admin/controllers/_audit.py`, `src/py/app/domain/admin/services/_audit.py` and `src/py/app/lib/schema.py`, and adds the test module under `src/py/tests/integration/admin/`. Its description shows one request and response pair for `/api/admin/audit/scroll`, explains that the cursor is the last row's UUID v7 and therefore sortable, and quotes the pytest summary and the coverage line from the sandbox.

It states the trade-off plainly: the scroll route returns no `total`, because counting is what makes offset pages slow on a growing table, and the offset route stays for the admin table until the web client is regenerated. It also notes that the `search` filter is not wired into the scroll route, since a text search across three columns changes the ordering question, and leaves that for a follow-up.

Before merging, a reviewer decides the default and maximum `limit`, whether the other lists (tags, teams, users) should get the same treatment, and when to regenerate the TypeScript client and switch `audit-log-table.tsx` to a load-more button.

## Run it on every Linear issue labelled pagination

An automation on the Project with a `linear` trigger on `linear.issue.labeled`, `pagination` in `config.labels`, and the prompt 'this issue names a list endpoint that must page by cursor; add a keyset method to its service, a scroll route beside the offset one, and an integration test that walks the cursor, then open a pull request' starts one run per labelled issue. The trigger adds the issue after the prompt and fills in nothing else, so an issue about the teams list and an issue about the users list each get a run that reads that controller.

A team with several Litestar services sends this body once per repository from its own server, each `POST /o/{org}/sessions` with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own models: a service whose primary keys are UUID v4 gets a cursor that encodes `created_at` and `id` together, and the pull request says why.

## Why run it on Rush?

Keyset pagination is easy to describe and easy to get subtly wrong: a cursor on a timestamp alone repeats rows that share a millisecond, a limit without the extra row needs a count query, a scroll route that returns `total` reintroduces the cost it was meant to remove, and a change to the existing route breaks a generated client. The agent reads the model's key type, the service layer and the test fixtures before choosing, and proves the walk on a real Postgres in its sandbox.

The test output, the coverage line and the diff stay with the run, so a reviewer sees the no-repeat and no-gap assertions pass rather than taking the description's word for it. A team with several services runs the same request across all of them at once.

## Frequently asked questions

### Why not change the existing route to use cursors?

The admin table and the generated TypeScript client read `total` and compute page numbers from it. Changing the response shape would break them in the same pull request. A second route lets the client move over when its table is ready, and the old route can be removed then.

### Why is the cursor an id rather than a timestamp?

The audit log's primary key is a UUID v7, which embeds its creation time, so ordering by `id` is ordering by time with no ties. A `created_at` cursor needs a tie-breaker and a two-column comparison. For a table with UUID v4 keys the agent encodes `created_at` and `id` together instead.

### Does advanced-alchemy already do this?

Not in the version this app locks. advanced-alchemy 1.8.2 ships `OffsetPagination` and a `LimitOffset` filter; its `PaginationFilter` base class leaves room for a cursor filter but none is included. The service builds the keyset `select` itself and hands it to the repository's `list`, which accepts a statement.

### Can I combine the cursor with filters and search?

The `action`, `target_type`, `actor_id` and `end_date` filters work unchanged, because they narrow the set without changing the order. Text search across several columns is left out of the scroll route on purpose; adding it means deciding whether relevance or time orders the results, and the pull request flags that choice.

## More Litestar jobs

- [Write a Dockerfile for a Litestar App](https://getrush.ai/run/add-dockerfile/litestar/)
- [Add Graceful Shutdown to a Litestar App](https://getrush.ai/run/add-graceful-shutdown/litestar/)
- [Add a Health Check Endpoint to a Litestar App](https://getrush.ai/run/add-health-checks/litestar/)

## The same job on other stacks

- [Add Cursor Pagination to a Mongoose and Express API](https://getrush.ai/run/add-cursor-pagination/mongoose/)
- [Add Cursor Pagination to a Prisma API](https://getrush.ai/run/add-cursor-pagination/prisma/)
- [Add Cursor Pagination to a Quarkus Panache REST Endpoint](https://getrush.ai/run/add-cursor-pagination/quarkus/)

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