# Set Lambda Log Retention in an AWS CDK Stack

Yes. An agent gives every Lambda in your CDK stack an explicit log group with the retention you choose, adds assertion tests that guard it, and opens a PR.

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

## What the agent does

The agent starts by finding out what happens to the logs today, because the answer depends on a feature flag and not only on the stack code. In a stack like `typescript/api-cors-lambda-crud-dynamodb` in aws-samples/aws-cdk-examples, `index.ts` creates a DynamoDB table named `items` with `removalPolicy: RemovalPolicy.DESTROY` and five `NodejsFunction` constructs (`getOneItemFunction`, `getAllItemsFunction`, `createItemFunction`, `updateItemFunction`, `deleteItemFunction`) that share one `NodejsFunctionProps` object with `Runtime.NODEJS_24_X`, the table name in `environment`, and a bundling rule that leaves `@aws-sdk/*` to the runtime. None of them sets `logRetention` or `logGroup`. `cdk.json` sets `@aws-cdk/aws-lambda:useCdkManagedLogGroup` to `true`, and with that flag on, `aws-cdk-lib` (`2.262.1` in `package.json`) creates a `LogGroup` per function itself with only a name, so each group takes the construct's default retention rather than one anybody chose. The logs stay as long as that default says, and nothing in the repository states what that is.

The change makes the retention a decision in the code. The agent creates one `logs.LogGroup` per function in `index.ts` with a `retention` taken from a context value, defaulting to one month, and a `removalPolicy` that matches the table's `DESTROY` in this example with a note that production stacks usually want `RETAIN`, and passes it as `logGroup` on each `NodejsFunction`. Because the `Function` construct itself refuses `logRetention` together with `logGroup`, and the Lambda README calls `logRetention` the legacy custom-resource path, the agent uses `logGroup` only. The five groups land in the template as `AWS::Logs::LogGroup` resources with `RetentionInDays`, and each function's `LoggingConfig` points at its group.

Tests come with it, in the shape the repository already prepared. `jest.config.js` is present with `@swc/jest` and the `aws-cdk-lib/testhelpers/jest-autoclean` setup, but `package.json` has no `test` script and there is no test file, and `index.ts` both defines `ApiLambdaCrudDynamoDBStack` and instantiates an `App` and calls `app.synth()` at module scope, so importing it from a test would synthesize on import. The agent moves the stack class into `lib/api-lambda-crud-dynamodb-stack.ts`, leaves `index.ts` as the entry `cdk.json` runs, adds `"test": "jest"`, and writes `test/api-lambda-crud-dynamodb.test.ts` with `Template.fromStack`: `resourceCountIs("AWS::Logs::LogGroup", 5)`, `hasResourceProperties` with the expected `RetentionInDays`, and a check that every `AWS::Lambda::Function` carries a `LoggingConfig` referencing one of them.

Then it runs everything in the sandbox: `npm install` (which also installs `lambdas/` through the `postinstall` script), `npm run build` for `tsc`, `npx cdk synth` to produce the template without AWS credentials, since the stack is environment-agnostic, and `npm test`. The README gains a sentence on the context value and the retention it defaults to.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Set an explicit log retention for every Lambda function in this CDK stack. Read index.ts, cdk.json, package.json, jest.config.js, the lambdas directory and the repository's SNAPSHOT_TESTING.md first, and check whether the useCdkManagedLogGroup feature flag is on, because that decides what the log groups are today. Create one logs.LogGroup per function with a retention read from a context value that defaults to one month and a removal policy consistent with the stack, pass it as logGroup on each NodejsFunction, and do not use the deprecated logRetention prop. Move the stack class into lib/ so a test can import it without synthesizing the app, add a test script, and write jest assertion tests with Template.fromStack that count the log groups, assert RetentionInDays and check each function's LoggingConfig references its group. Run npm install, npm run build, npx cdk synth and npm test in the sandbox, document the context value in the README, and open a pull request.",
  "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 stack moved to `lib/api-lambda-crud-dynamodb-stack.ts` and `index.ts` reduced to the entry point, the five `LogGroup` constructs wired into the functions, `test/api-lambda-crud-dynamodb.test.ts`, the `test` script in `package.json`, and the README sentence. The Lambda handlers in `lambdas/`, the table and the API Gateway resources are unchanged, and `cdk.json` keeps its flags.

The description shows the relevant part of the synthesized template, the five `AWS::Logs::LogGroup` resources with their `RetentionInDays`, and the jest summary. The transcript at `GET /o/{org}/sessions/{id}/messages` keeps `npm install`, `tsc`, `cdk synth` and the test run with their full output.

Before merging, a reviewer picks the retention their compliance rules require and the removal policy they want for log groups, since `DESTROY` deletes logs with the stack, and checks how the change deploys: the function name does not change, but the log group becomes a CloudFormation resource with the same `/aws/lambda/` name only if the agent kept that name, which the pull request states. A follow-up message to the same session switches the policy or adds JSON log format in the same place.

## Run it on every Linear issue labelled logging

A team that tracks platform work in Linear starts one run per issue from an automation with a `linear` trigger on the `logging` label. The automation adds the issue after this prompt, so the retention period the issue asks for is what the agent reads, 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 back to the issue and the transcript holds the synthesized template and the test run for that stack.

## Why run it on Rush?

The trap in this job is that the current behaviour is invisible: whether a Lambda's logs expire depends on a feature flag in `cdk.json` and a default inside `aws-cdk-lib`, not on anything in the stack file. The agent reads the flag, reads the library's behaviour for it, and writes the retention into the stack where a reviewer can see it, then proves it from the synthesized template rather than from a sentence.

The proof stays with the pull request: the `cdk synth` output and the jest assertions are in the transcript beside the commands that produced them, and the tests keep guarding the retention on every future change. Several stacks can be handled at once, one sandbox and one pull request each.

## Frequently asked questions

### What does the stack do with logs today?

With `@aws-cdk/aws-lambda:useCdkManagedLogGroup` set to `true` in `cdk.json`, the `Function` construct creates a `LogGroup` per function itself when neither `logRetention` nor `logGroup` is given, passing only a name, so the retention is the `LogGroup` construct's default rather than a value anyone chose. The agent reports what that default is in the library version the lock file pins, and the change replaces it with an explicit value.

### Why not use the logRetention prop?

Because the Lambda README describes it as the legacy path that works through a custom resource, and the construct refuses it together with `logGroup`. An explicit `LogGroup` is a plain CloudFormation resource that supports tags, aspects and a removal policy, and it is what the feature flag already creates implicitly.

### Will the tests slow the build down?

They run in jest with `@swc/jest`, which `package.json` already lists, and they only synthesize the stack in memory with `Template.fromStack`. The `jest-autoclean` setup in `jest.config.js` removes the temporary output after each test file.

### Does deploying this change the log group name?

The pull request says which it is. The agent can keep the `/aws/lambda/<function name>` name so the group CloudFormation now manages is the one the function already logs to, or let CDK generate a name; either way the function's `LoggingConfig` points at the managed group, and the description explains the deployment consequence of the choice.

## More AWS CDK jobs

- [Tag Every Resource in an AWS CDK App from a Linear Issue](https://getrush.ai/run/add-resource-tags/aws-cdk/)
- [Add AWS WAF to an API Gateway REST API in AWS CDK](https://getrush.ai/run/add-waf/aws-cdk/)
- [Add X-Ray Tracing to an AWS CDK Stack from a Linear Issue](https://getrush.ai/run/add-xray-tracing/aws-cdk/)

## The same job on other stacks

- [Set CloudWatch Log Retention in a Serverless Framework Service](https://getrush.ai/run/add-log-retention/serverless/)

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

- [Add macOS Code Signing and Notarization to a Tauri Release Workflow](https://getrush.ai/run/add-macos-code-signing/tauri/)
- [Add a Man Page to a Go CLI](https://getrush.ai/run/add-man-page/go-cli/)

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