# Add a Scheduled Function to a Serverless Framework API

Yes. An agent adds a schedule event and a cleanup handler to a Serverless Framework service, adds the one IAM action it needs, tests it and opens a PR.

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

## What the agent does

The agent starts from the service definition. In a service laid out like the `aws-node-rest-api-with-dynamodb` example in serverless/examples, `serverless.yml` names `serverless-rest-api-with-dynamodb` on `frameworkVersion: '4'`, provider `aws` with `runtime: nodejs24.x` and `architecture: arm64`, one environment variable `DYNAMODB_TABLE: ${self:service}-${sls:stage}`, and an IAM role statement allowing `Query`, `Scan`, `GetItem`, `PutItem`, `UpdateItem` and `DeleteItem` on `!GetAtt TodosDynamoDbTable.Arn`. Five functions map `httpApi` routes to `todos/create.js`, `list.js`, `get.js`, `update.js` and `delete.js`, each an ES module (`"type": "module"` in `package.json`) using `DynamoDBDocumentClient` from `@aws-sdk/lib-dynamodb`. The table is `PAY_PER_REQUEST`, has `DeletionPolicy: Retain` and a single `id` hash key, so there is no index on `checked` or `updatedAt`.

Then it reads what a todo looks like. `create.js` writes `{ id, text, checked: false, createdAt, updatedAt }` with both timestamps from `Date.now()`, so they are millisecond numbers; `update.js` sets `text`, `checked` and a fresh `updatedAt` through an `UpdateExpression` and returns `ALL_NEW`; `delete.js` exports its handler as `del` and re-exports it as `delete` because of the reserved word; `list.js` scans the whole table. The sibling `aws-node-scheduled-cron` example shows the event shape the framework takes: `events: - schedule: rate(1 minute)` on a handler, with nothing else. `package.json` has no test script and no dev dependencies.

The agent adds `todos/purge.js` exporting `purge`: it scans the table with a `FilterExpression` of `checked = :true AND updatedAt < :cutoff`, where the cutoff is now minus a `PURGE_AFTER_DAYS` environment variable, follows `LastEvaluatedKey` until the scan ends, and deletes what it found with `BatchWriteCommand` in the batch size DynamoDB allows, logging the count. In `serverless.yml` a `purge` function points at it with `events: - schedule:` holding a nightly `cron` expression and `enabled: true`, and `PURGE_AFTER_DAYS` joins the provider environment. Because `BatchWriteItem` is its own IAM action and the statement lists `DeleteItem` only, the agent adds `dynamodb:BatchWriteItem` to that statement and nothing else; `Scan` is already there. The README gains a short section on the schedule and the variable.

To prove it, the agent adds `aws-sdk-client-mock` as a dev dependency and a `node --test` script in `package.json`, with `todos/purge.test.js` covering three cases: an unchecked or recent todo is kept, a checked old one is deleted, and a scan that returns `LastEvaluatedKey` is followed. It runs the tests in its sandbox and pastes the output. With a `SERVERLESS_ACCESS_KEY` saved as a Project secret, which Framework v4 needs to run at all, it runs `serverless package` and quotes the `purge` function and the EventBridge rule from `.serverless/cloudformation-template-update-stack.json`, so a reviewer sees the schedule the deploy would create without deploying.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add a nightly cleanup function to this Serverless Framework service. Read serverless.yml, package.json, README.md and every file under todos/ first. Add todos/purge.js exporting purge: scan the table for items with checked true and updatedAt older than PURGE_AFTER_DAYS days, follow LastEvaluatedKey, delete them with BatchWriteCommand in the batch size DynamoDB allows, and log the count. In serverless.yml add a purge function with a schedule event holding a nightly cron expression, add PURGE_AFTER_DAYS to the provider environment, and add dynamodb:BatchWriteItem to the existing IAM statement and nothing else. Add aws-sdk-client-mock as a dev dependency, a test script using node --test, and todos/purge.test.js covering a kept recent item, a deleted old checked item and a followed LastEvaluatedKey. Run the tests and paste the output. Using the SERVERLESS_ACCESS_KEY secret in this Project, run serverless package and quote the purge function and its schedule rule from the generated CloudFormation template. Document the schedule and the variable in the README. Change no existing handler.",
  "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 adds `todos/purge.js` and `todos/purge.test.js`, changes `serverless.yml`, `package.json`, `package-lock.json` and `README.md`, and leaves the five existing handlers untouched. Its description shows the three tests passing under `node --test`, the `purge` function and the EventBridge schedule rule as `serverless package` rendered them, and the one-line IAM change with the reason `BatchWriteItem` is a separate action.

The new function runs on its schedule with the same role as the API, extended by exactly one action; the table, its billing mode and its retain policy are unchanged, and the API routes behave as before. A reviewer sees the exact cron expression, the cutoff variable and what the handler deletes, because the test spells out which items are kept and which go.

Before merging, a reviewer sets `PURGE_AFTER_DAYS` and the cron hour for their data, decides whether a full-table scan every night is acceptable at their size or whether a global secondary index on `checked` is worth adding first, and confirms the deploy happens through their normal `serverless deploy` with the stage they intend.

## Run it on every Linear issue labelled agent

Add an automation to the Project with this prompt and a `linear` trigger on `linear.issue.labeled` with the label you reserve for the agent in its `labels`. Each labelled issue starts one run with the issue as its context, on its own branch; the trigger adds the issue after the prompt and fills in no placeholder, and a change made by an app integration never fires it, so the agent's own comment on the issue starts nothing.

The automation's `max_runs_per_hour` holds a burst of labels to that many runs an hour: a fire past it is created `queued` and starts when the hour has room, and one past a second hour's worth is skipped as `rate_limited` until the issue is labelled again. From your own server, the same run starts with this request and the issue URL in `resources`, with a `request_id` that is a UUID v5 of the issue id so a retried start returns the run already begun.

## Why run it on Rush?

A scheduled function touches three things that must agree, the event in `serverless.yml`, the handler's permissions and the handler's filter, and a mistake in any of them is invisible until the first night. The agent reads the existing handlers for the exact item shape, tests the filter and the pagination against a mocked client, and packages the stack in its own sandbox so the rendered schedule rule is in the pull request rather than discovered after a deploy.

The transcript keeps `node --test` and `serverless package` with their output, so a reviewer reads the evidence from one page. Several services with the same layout can get their cleanup at once, each run in its own sandbox with its own credentials from the Project, and nothing merges until a person reads the diff.

## Frequently asked questions

### Why scan instead of querying an index?

The table has one hash key, `id`, and no secondary index, so there is nothing to query by `checked` or `updatedAt`. A nightly filtered scan is the smallest change and is paid per request on `PAY_PER_REQUEST`. The pull request names the index that would replace it so a reviewer can choose that once the table is large.

### Does the schedule need its own IAM role?

No. The framework attaches the provider's role to every function, so `purge` gets the existing statement. The only addition is `dynamodb:BatchWriteItem`, because batch deletes are a different API action from `DeleteItem` even though they delete the same rows.

### Can I run the purge by hand?

Yes. It is an ordinary function, so `serverless invoke -f purge` runs it against the deployed stage, and the schedule event can be turned off with `enabled: false` while keeping the function. The handler ignores its event payload, so a manual invoke and a scheduled one do the same thing.

### Why node --test and a mocked client instead of a local DynamoDB?

The repository has no test setup, and the handler's logic is the filter, the pagination and the batching, all of which `aws-sdk-client-mock` exercises without a database. A local DynamoDB would need Java in the sandbox and would test the SDK more than the handler. The packaged template covers the deployment side.

## More Serverless Framework jobs

- [Add Structured Logging to a Serverless Framework API from a Linear Issue](https://getrush.ai/run/add-structured-logging/serverless/)
- [Add X-Ray Tracing to a Serverless Framework API from a Linear Issue](https://getrush.ai/run/add-xray-tracing/serverless/)
- [Investigate Lambda Timeouts in a Serverless Service](https://getrush.ai/run/investigate-lambda-timeouts/serverless/)

## More jobs like this: Turn a Linear label into a PR

- [Add a Temporal Schedule to a TypeScript Workflow](https://getrush.ai/run/add-schedules/temporal/)
- [Catch Breaking GraphQL Schema Changes in CI](https://getrush.ai/run/add-schema-check-to-ci/graphql/)
- [Add Custom Search Attributes to Temporal Workflows](https://getrush.ai/run/add-search-attributes/temporal/)

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