# Add a DynamoDB TTL to a Serverless Framework Service

Yes. An agent enables TTL on your DynamoDB table in serverless.yml, sets the expiry in the right handler, hides expired items from reads, tests it and opens a PR.

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

## What the agent does

The agent starts with the table and every handler that writes to it, because a TTL is only as good as the attribute the code sets. In a service laid out like the `aws-node-rest-api-with-dynamodb` example in serverless/examples, `serverless.yml` is `frameworkVersion: '4'` on `nodejs24.x` and `arm64`, exposes `DYNAMODB_TABLE` as `${self:service}-${sls:stage}`, scopes the function role to six DynamoDB actions on `!GetAtt TodosDynamoDbTable.Arn`, routes five `httpApi` events to `todos/create.js`, `list.js`, `get.js`, `update.js` and `delete.js`, and declares the table as an `AWS::DynamoDB::Table` with `DeletionPolicy: Retain`, `PAY_PER_REQUEST` billing and a single string hash key `id`. `package.json` is an ES module with `@aws-sdk/client-dynamodb` and `@aws-sdk/lib-dynamodb` and no test script, and there is no test, lint or CI in the service.

The handlers set the shape. `create.js` checks `text` is a string and writes `id` from `randomUUID`, `checked: false` and `createdAt` and `updatedAt` from `Date.now()`, which is milliseconds; `update.js` requires `text` and `checked`, runs one `UpdateExpression` that sets `#todo_text`, `checked` and `updatedAt`, and returns `ALL_NEW`; `list.js` scans the whole table; `get.js` answers 404 when `Item` is missing; `delete.js` deletes by key. DynamoDB's TTL attribute must be a number of seconds since the epoch, so none of the existing timestamps can be reused as it stands, and the agent says so rather than pointing TTL at `updatedAt`.

The change gives the table `TimeToLiveSpecification` with `AttributeName: expiresAt` and `Enabled: true`, and adds `CHECKED_TODO_TTL_DAYS` to `provider.environment` so the retention is set in one place. `update.js` computes `expiresAt` as `Math.floor(Date.now() / 1000)` plus that many days when `checked` is `true`, and the one expression now reads `SET ... , expiresAt = :expiresAt` in that case and `SET ... REMOVE expiresAt` when a todo is unchecked again, so reopening a todo cancels its expiry. Because DynamoDB removes expired items some time after they expire rather than at the second, `list.js` adds a `FilterExpression` of `attribute_not_exists(expiresAt) OR expiresAt > :now` and `get.js` answers 404 for an item whose `expiresAt` has passed, so a client never sees a todo the table is about to drop. No IAM change is needed: enabling TTL is done by CloudFormation with the deploy role, and the functions keep their six actions.

The sandbox has no AWS account, so the agent proves the handlers rather than the deploy. It adds `aws-sdk-client-mock` and a `test` script running `node --test`, and writes `todos/update.test.js` and `todos/list.test.js` that mock `DynamoDBDocumentClient` and assert the `UpdateExpression`, the `REMOVE` clause on uncheck, that `:expiresAt` is in seconds and later than now, and the scan's `FilterExpression`. For the template it checks the new property against the CloudFormation reference for `AWS::DynamoDB::Table` and leaves the first `serverless deploy` to the reader's pipeline, which is where CloudFormation validates it, and says exactly that in the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add a DynamoDB time-to-live to this Serverless Framework service. Read serverless.yml, package.json and every file under todos first. Add TimeToLiveSpecification with an expiresAt attribute to the table resource and a CHECKED_TODO_TTL_DAYS environment variable. In update.js set expiresAt in epoch seconds, not the millisecond timestamps the handlers already use, when checked becomes true, and remove it when checked becomes false, in the one UpdateExpression. Filter expired items out of the scan in list.js and answer 404 for an expired item in get.js, because DynamoDB deletes expired items after a delay. Change no IAM statement. Add aws-sdk-client-mock and a node --test script with tests that assert the update expression in both cases, the unit of expiresAt and the scan filter, and run them in the sandbox. Check the table property against the CloudFormation reference, say in the pull request that the deploy is where CloudFormation validates it, and quote the test output.",
  "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 changes `serverless.yml`, `todos/update.js`, `todos/list.js`, `todos/get.js` and `package.json`, adds two test files and the lockfile entry for `aws-sdk-client-mock`, and leaves `create.js`, `delete.js` and the IAM statements as they were. The description quotes the `node --test` output, shows the before and after of the `UpdateExpression`, and states plainly that it did not deploy and that the first `serverless deploy` in the reader's pipeline is where CloudFormation accepts the new table property.

The run's record keeps the `npm install` log, each test's pass line with the expressions the mock captured, and the agent's reading of the CloudFormation property names, so a reviewer can see the handler change is right before the template is ever deployed.

Before merging, a reviewer sets the retention in `CHECKED_TODO_TTL_DAYS`, decides whether unchecked todos should ever expire, and checks that the deploy role in their pipeline can update the table, since enabling TTL on a retained table is an in-place update with no replacement.

## Run it on every service with a DynamoDB table

A team with several Serverless services starts one run per repository from a script: `GET /o/{org}/github` lists every repository the installation reaches, the script clones each and keeps the ones whose `serverless.yml` declares an `AWS::DynamoDB::Table` with no `TimeToLiveSpecification`, and sends this body with that repository in `resources`. Each call carries a `request_id` that is a UUID v5 of the repository's full name, so a second pass returns the runs already started.

Each run reads its own service. One whose items already carry an expiry in seconds gets the table property and the read filters only; one in TypeScript gets the same tests in its own test runner; one with a `serverless-dynamodb` offline plugin gets the tests run against it. The pull requests arrive one per service, each with its test output in the record.

## Why run it on Rush?

A TTL added by hand fails quietly: the attribute set in milliseconds so every item expires decades out or, worse, in the past, a scan that keeps returning items DynamoDB has not got round to deleting, or an unchecked todo that still vanishes because nothing removed its expiry. In a Rush sandbox the agent reads every handler, writes tests that pin the unit and both branches of the update, and runs them before it opens anything.

The test output stays with the run and the pull request quotes it, so the reviewer reads what the handlers now send rather than reading the diff twice. The same job across every service a team runs happens in parallel, each with its own machine, its own tests and its own pull request.

## Frequently asked questions

### Why seconds, when the handlers already store timestamps?

DynamoDB reads the TTL attribute as seconds since the epoch and ignores a value it cannot read that way. `createdAt` and `updatedAt` come from `Date.now()` in milliseconds, so pointing TTL at either would set expiry centuries away. The agent adds a separate `expiresAt` in seconds and leaves the existing timestamps alone.

### Will expired todos still show up for a while?

Not to clients. DynamoDB deletes expired items after a delay rather than at the second, so the agent filters them out of the scan in `list.js` and answers 404 in `get.js` once `expiresAt` has passed. The storage goes when DynamoDB gets to it.

### Does enabling TTL on an existing table cause downtime or a replacement?

No. `TimeToLiveSpecification` is an in-place update on the table, the `DeletionPolicy: Retain` is untouched, and items with no `expiresAt` are never affected. Only items that gain the attribute expire.

### Does it need new IAM permissions?

No. The functions keep their six DynamoDB actions on the table's ARN. Turning TTL on is a table-level change CloudFormation makes with the deploy role.

### Why doesn't the agent deploy it?

The sandbox has no AWS credentials and the pull request says so. The handler change is proven by the tests in the record; the table property is checked against the CloudFormation reference, and the first `serverless deploy` in the reader's pipeline is where CloudFormation validates it.

## More Serverless Framework jobs

- [Add GitHub Actions CI and Deploy for a Serverless Framework Service](https://getrush.ai/run/add-github-actions-ci/serverless/)
- [Give Each Lambda Its Own IAM Role in a Serverless Framework Service](https://getrush.ai/run/add-iam-roles-per-function/serverless/)
- [Add Request Validation to a Serverless API](https://getrush.ai/run/add-input-validation/serverless/)

## More jobs like this: Hand off a long task

- [Add an EAS Build Workflow on GitHub Actions to an Expo App](https://getrush.ai/run/add-eas-build-workflow/expo/)
- [Add an Edge Function to a Supabase Project](https://getrush.ai/run/add-edge-function/supabase/)
- [Add a CodeMirror Editor Extension to an Obsidian Plugin](https://getrush.ai/run/add-editor-extension/obsidian-plugin/)

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