# Add Canary Deployments to Lambda Functions in a CDK App

Yes. An agent gives each Lambda a live alias, a CodeDeploy canary deployment group and an error alarm, points API Gateway at the alias, tests the template, in a PR.

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

## What the agent does

The agent reads the stack before adding anything. In a project like the `typescript/api-cors-lambda-crud-dynamodb` example in aws-samples/aws-cdk-examples, `index.ts` defines `ApiLambdaCrudDynamoDBStack`: a DynamoDB `Table` named `items` with `itemId` as partition key and `RemovalPolicy.DESTROY`, shared `NodejsFunctionProps` that bundle with `@aws-sdk/*` external, read `lambdas/package-lock.json`, set `PRIMARY_KEY` and `TABLE_NAME` and run on `NODEJS_24_X`, and five `NodejsFunction` constructs, `getOneItemFunction`, `getAllItemsFunction`, `createItemFunction`, `updateItemFunction` and `deleteItemFunction`, each from a handler under `lambdas/`. Each gets `grantReadWriteData`, a `LambdaIntegration`, and a method on the `itemsApi` `RestApi`: `GET` and `POST` on `items`, `GET`, `PATCH` and `DELETE` on `items/{id}`, with `OPTIONS` from `addCorsOptions`. `package.json` pins `aws-cdk-lib` 2.262.1 and the `aws-cdk` CLI 2.1133.0, with Jest 30 and `@swc/jest`; `jest.config.js` matches `**/*.test.ts` and loads `aws-cdk-lib/testhelpers/jest-autoclean`, but no test file exists. `cdk.json` runs `npx tsc && npx tsx index.ts` and already sets `@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup`. Every deploy replaces all five functions' code at once, with no way to shift traffic gradually or roll back on errors.

For each function it adds a `lambda.Alias` named `live` on `fn.currentVersion`, and changes the five `LambdaIntegration` constructs to take the alias rather than the function, so API Gateway invokes the alias ARN and CodeDeploy can move traffic between versions behind it. A `cloudwatch.Alarm` per alias watches `alias.metricErrors` over one-minute periods with a threshold of 1 and one evaluation period, and a `codedeploy.LambdaDeploymentGroup` per alias uses `LambdaDeploymentConfig.CANARY_10PERCENT_5MINUTES` with that alarm in `alarms`, so a deploy sends a tenth of requests to the new version for five minutes and rolls back if the alarm fires. The helper that builds the alias, alarm and group is one function in `index.ts` called five times, so the five functions stay symmetric. `grantReadWriteData` stays on the functions, since the alias shares the function's role.

`currentVersion` only publishes a new version when the code or configuration changes, which is what makes a canary meaningful: an unchanged function keeps its version and CodeDeploy has nothing to shift. The agent sets `removalPolicy: RemovalPolicy.RETAIN` on the current version options so an older version stays available for a rollback after the deploy completes, and writes in `README.md` what a deploy now looks like in the CodeDeploy console and how to watch the alarm.

The proof is a test the example never had. `index.test.ts` uses `Template.fromStack` from `aws-cdk-lib/assertions` to assert five `AWS::Lambda::Alias` resources named `live`, five `AWS::CodeDeploy::DeploymentGroup` resources with `DeploymentConfigName` set to `CodeDeployDefault.LambdaCanary10Percent5Minutes` and an alarm in `AlarmConfiguration`, five alarms on the `Errors` metric, and that every API Gateway method's integration URI references an alias rather than a bare function ARN. `npm run build` type-checks, `npx jest` runs the test, and `cdk synth` runs the way `scripts/build-typescript.sh` and `scripts/synth.sh` do in the repository's pull request workflow, with the fake context file so no account is needed.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add canary deployments to every Lambda function in this CDK stack. Read index.ts, cdk.json, package.json, jest.config.js, tsconfig.json, README.md, the handlers under lambdas/ and the repository's scripts/build-typescript.sh and scripts/synth.sh first. For each function create a lambda.Alias named live on currentVersion, point its LambdaIntegration at the alias, add a CloudWatch alarm on the alias's error metric with one-minute periods and a threshold of one, and a codedeploy.LambdaDeploymentGroup using LambdaDeploymentConfig.CANARY_10PERCENT_5MINUTES with that alarm; do it through one helper called once per function. Keep the DynamoDB grants on the functions, retain old versions, and explain in README.md how a deploy now shifts traffic and rolls back. Write index.test.ts with Template.fromStack assertions for the five aliases, five deployment groups with the canary config and alarm, five error alarms, and API Gateway integrations that reference aliases. Run npm run build, npx jest and cdk synth with the repository's fake context, 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 that edits `index.ts` and `README.md` and adds `index.test.ts`. The description names the alias, alarm and deployment group each function gains, the canary configuration, and the one behaviour change a reviewer should expect: a deploy that changes a handler now takes at least five minutes to complete while traffic shifts.

The run's record keeps the `tsc` output, the Jest run with each assertion named, and the synthesized template from `cdk synth`, so a reviewer can read the `AWS::CodeDeploy::DeploymentGroup` resources and the integration URIs directly rather than trusting the description.

Before merging, a reviewer deploys to a non-production account, changes one handler, deploys again, and watches the deployment group in the CodeDeploy console shift ten percent of traffic to the new version. Forcing an error in that version during the window should trip the alarm and roll the alias back, which is the behaviour the alarm wiring exists for.

## Run it on every Linear issue labelled deploy-safety

In the console, an automation with a `linear` trigger on `linear.issue.labeled` and the label `deploy-safety` starts one run per labelled issue in the Project's repository. The trigger adds the issue's text after the saved prompt, so an issue asking for a linear ramp instead of a canary, or for a latency alarm beside the error alarm, carries that itself and the prompt stays fixed. Changes made by an app integration never fire it, and the automation's `max_runs_per_hour` bounds a burst of labelling.

From your own server, the same job is one `POST /o/{org}/sessions` per issue, with the repository in `resources` and the issue's `https://linear.app/<workspace>/issue/<ID>` URL beside it so Rush reads the issue through your Linear connection. A `webhook_url` on the API key receives `run.completed` or `run.failed` for every run that key starts, with the `session_url` to read the pull request link from.

## Why run it on Rush?

The pieces are documented one at a time, and the mistakes are in how they connect: an integration still pointing at the function so the canary shifts nothing, an alarm on the function's metric rather than the alias's so a bad version never trips it, a version removal policy that deletes the only rollback target. The agent synthesizes the real template in its own sandbox and writes assertions against the resources, which a reading of the construct code does not do.

Every command and its output are kept with the run, so a reviewer can open the synthesized template from the record and check the integration URIs and deployment group properties themselves, before any deploy touches an account.

## Frequently asked questions

### Why point API Gateway at the alias instead of the function?

CodeDeploy shifts traffic by changing the weights behind an alias. An integration that names the function directly always invokes `$LATEST`, so the deployment group would move traffic the API never sends. The test asserts every integration URI references an alias for that reason.

### What triggers a canary, and what does not?

A change to a handler under `lambdas/`, to the bundling options or to the environment publishes a new version through `currentVersion`, and the deployment group shifts traffic to it. A deploy that changes only the table or the API resources publishes nothing, and the alias stays where it is.

### Can the alarm be something other than errors?

Yes. `alarms` on the deployment group takes any CloudWatch alarm, and a duration or throttle alarm on the alias's metrics fits the same helper. Errors is the one that catches a handler that throws, which is the most common bad deploy for CRUD functions like these.

### Does this change the DynamoDB table or its removal policy?

No. The table, its `DESTROY` policy and the `grantReadWriteData` calls are untouched; the grants apply to the function's role, which the alias shares. Only the function wiring, the new deployment resources and the README change.

## More AWS CDK jobs

- [Add cdk-nag Checks to an AWS CDK App](https://getrush.ai/run/add-cdk-nag/aws-cdk/)
- [Add CloudWatch Alarms to an AWS CDK Stack](https://getrush.ai/run/add-cloudwatch-alarms/aws-cdk/)
- [Add Cognito Authentication to an API Gateway in AWS CDK](https://getrush.ai/run/add-cognito-auth/aws-cdk/)

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

- [Add Chat Export to an AI SDK Chatbot](https://getrush.ai/run/add-chat-export/ai-sdk/)
- [Add Chat Export to a Reflex Chat App](https://getrush.ai/run/add-chat-export/reflex/)
- [Add Chat History Export to a Streamlit App from a Linear Issue](https://getrush.ai/run/add-chat-export/streamlit/)

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