# Add Cursor Pagination to a Serverless DynamoDB API

Yes. An agent replaces the full-table Scan in your Serverless list handler with limit and cursor parameters backed by LastEvaluatedKey, with tests, and opens a PR.

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

## What the agent does

The agent reads the service before changing a handler. In a service like `aws-node-rest-api-with-dynamodb` in serverless/examples, `serverless.yml` declares `frameworkVersion` 4, the `aws` provider on `nodejs24.x` and `arm64`, a `DYNAMODB_TABLE` environment variable built from the service name and stage, an IAM statement allowing `Query`, `Scan`, `GetItem`, `PutItem`, `UpdateItem` and `DeleteItem` on the table, and five functions on `httpApi` events: `POST /todos`, `GET /todos`, `GET /todos/{id}`, `PUT /todos/{id}` and `DELETE /todos/{id}`. The table resource is `PAY_PER_REQUEST` with a single string hash key `id` and `DeletionPolicy: Retain`. `package.json` is an ES module with `@aws-sdk/client-dynamodb` and `@aws-sdk/lib-dynamodb` and no dev dependencies or test script. `todos/list.js` sends one `ScanCommand` and returns `result.Items` as the body, so a growing table returns more each call until it hits the one megabyte Scan page or the response size limit, and the caller has no way to continue.

From that the agent rewrites `todos/list.js`. It reads `limit` and `cursor` from `event.queryStringParameters`, clamps `limit` to a default and a maximum the prompt sets, decodes `cursor` from base64url into the `ExclusiveStartKey` object, and sends `ScanCommand` with `Limit` and that key. The response becomes `{ "items": [...], "nextCursor": "..." }`, where `nextCursor` is the base64url encoding of `LastEvaluatedKey` and is omitted when DynamoDB returns none; a cursor that fails to decode answers `400` with an error body in the same shape `create.js` and `update.js` already use for bad input. Because the table's only key is `id`, the cursor encodes just that attribute, and the pull request says plainly that a Scan has no order, so a sorted listing would need a global secondary index on `createdAt` and a `Query`, which is a schema change left out on purpose.

The response shape changes from a bare array to an object, which is a breaking change for existing callers. The agent names it in the pull request and updates the README's `List all Todos` example to show `?limit=` and `?cursor=` and the new body; if the prompt asks to keep compatibility, it returns the array unchanged and puts the cursor in a response header instead. `serverless.yml` needs no edit: the IAM statement already allows `Scan`, and the handler reads only the environment variable it already has.

Tests come with the change. The package has no test tooling, so the agent adds `aws-sdk-client-mock` as a dev dependency and a `test` script running Node's built-in `node --test`, which the `nodejs24.x` runtime matches, and writes `todos/list.test.js` with cases for the default limit, a round trip where the first page's `nextCursor` becomes the second call's `ExclusiveStartKey`, a last page with no cursor, and a malformed cursor answering `400`. `npm test` passing in the sandbox is the check; a deploy needs AWS credentials and a Serverless Framework login, so the agent does not deploy and says so.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add cursor pagination to the list endpoint of this Serverless Framework service. Read serverless.yml, package.json, every file under todos and the README first. Rewrite the list handler to accept limit and cursor query parameters, clamp limit to a default of 20 and a maximum of 100, decode the cursor from base64url into ExclusiveStartKey, pass Limit to the Scan, and return an object with items and a nextCursor derived from LastEvaluatedKey, omitted on the last page; answer 400 for a cursor that does not decode, using the same error body shape the other handlers use. Do not change serverless.yml or the table. Add aws-sdk-client-mock as a dev dependency and a test script using node --test, with tests for the default limit, a two-page round trip, the last page and a malformed cursor. Update the README's list example. Run npm test and open a pull request that states the response shape change and explains why a Scan cannot be ordered without an index.",
  "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 with the rewritten `todos/list.js`, a new `todos/list.test.js`, `package.json` with the `test` script and one dev dependency, a new lockfile and the README's updated list section. `serverless.yml`, the table resource and the other four handlers are untouched.

The description shows the new request and response shapes with an example cursor, the clamping rules, the `400` body for a bad cursor, the test output from `npm test`, and the two things it did not do: deploy, because that needs credentials and a Framework login, and order the results, because the table has no index to order by. The commands are in the transcript at `GET /o/{org}/sessions/{id}/messages`.

Before merging, a reviewer decides whether the response shape change is acceptable for current callers or asks for the header variant in a follow-up message to the same session, deploys to a dev stage with `serverless deploy`, and pages through a seeded table with the README's `curl` examples.

## Run it on every Linear issue labelled api

A backend team that plans API work in Linear starts one run per issue from an automation with a `linear` trigger on an `api` label. The automation adds the issue after this prompt, so the endpoint the issue names, or a page size it specifies, is what the agent reads first, and the run starts in the repository the automation names.

Each run opens its own pull request from its own sandbox, and an automation run has its own `max_runs_per_hour` cap. The pull request links the issue and carries the test output, so review is a read of one handler and its tests.

## Why run it on Rush?

Pagination over DynamoDB is small code with sharp edges: `Limit` counts items scanned, not returned, the continuation key must round-trip through a URL, and a bare `Scan` silently stops at a page boundary that only appears once the table grows. The agent reads the key schema and the IAM statement before writing the handler, encodes exactly the key the table has, and proves the round trip with a mocked client in its own sandbox rather than against a live account.

The result names the trade-off, a changed response shape, and the limit, no ordering without an index, instead of hiding either. Several services can be handled at once, each in its own sandbox, with one pull request each.

## Frequently asked questions

### Why not sort the todos by creation time?

The table's only key is `id`, and a `Scan` returns items in storage order. Sorting would need a global secondary index with a partition key and `createdAt` as the sort key, plus a `Query` instead of a `Scan`, which changes the table definition in `serverless.yml`. The pull request describes that path and leaves it for a separate change.

### Is the cursor safe to hand to clients?

It is a base64url encoding of the `LastEvaluatedKey`, which here is only the item's `id`, so it reveals nothing beyond an id the client can already fetch. A tampered or truncated cursor fails to decode and answers `400`; the handler never passes an undecoded string to DynamoDB.

### Does this break existing callers?

Yes, if they expect a bare array: the body becomes an object with `items` and `nextCursor`. The pull request states this on its first line. If you prefer compatibility, ask for the variant that keeps the array and returns the cursor in a response header, and the agent switches in the same session.

### Why does the agent not deploy to check?

A deploy needs AWS credentials and, on Framework version 4, a Serverless login or license key, neither of which the sandbox has. The tests mock the DynamoDB document client with `aws-sdk-client-mock`, so the handler logic is checked without an account, and the pull request leaves the deploy to a reviewer with a dev stage.

## More Serverless Framework jobs

- [Add a Custom Domain to a Serverless Framework API](https://getrush.ai/run/add-custom-domain/serverless/)
- [Add a Dead-Letter Queue to a Serverless SQS Worker](https://getrush.ai/run/add-dlq/serverless/)
- [Turn On DynamoDB Point-in-Time Recovery in a Serverless Framework Service](https://getrush.ai/run/add-dynamodb-point-in-time-recovery/serverless/)

## The same job on other stacks

- [Add Cursor Pagination to a Slim 4 API](https://getrush.ai/run/add-cursor-pagination/slim/)
- [Add Cursor Pagination to a SQLAlchemy API](https://getrush.ai/run/add-cursor-pagination/sqlalchemy/)
- [Add Cursor Pagination to sqlc Queries](https://getrush.ai/run/add-cursor-pagination/sqlc/)

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