Canary releases and rollback with Lambda aliases or ECS
Shift traffic in stages with Lambda aliases or ECS deployment settings, gate on metrics and roll back on a tested trigger.
By Invicly Tech, , in AWS Cloud Engineering. About 12 minutes to read.
In short
Progressive delivery sends a new version a small share of real traffic first, watches health metrics, and only then shifts the rest. On AWS, Lambda aliases can split traffic between two versions by weight, and ECS services can roll out with a deployment circuit breaker, CloudWatch alarms, or built-in blue/green and canary strategies. A release is only safe when the rollback is automatic, tested and does not depend on undoing a database change.
Explained simply
Even with good tests, some bugs only appear with real traffic. If you switch everyone to a new version at once, everyone meets the bug at once. Progressive delivery limits the damage. You send a small part of traffic, say 10 percent, to the new version, watch it, and only then move the rest.
This first small step is called a canary, after the birds miners once carried to warn of bad air. A linear release moves traffic in equal steps, such as 10 percent every minute. Blue/green runs the old and new versions side by side and switches between them, which makes going back quick.
On AWS, a Lambda alias is a name like live that points at a numbered version of your function. An alias can split traffic between two versions by weight, so live can send 90 percent to version 7 and 10 percent to version 8. AWS CodeDeploy, often set up through AWS SAM, can move those weights for you on a schedule.
For containers on ECS, the default rolling update replaces tasks gradually. The deployment circuit breaker stops and rolls back a release whose tasks keep failing. ECS can also watch CloudWatch alarms during a deployment, and it offers blue/green, linear and canary strategies behind a load balancer.
The hardest part is often the database. During a canary, old and new code run at the same time against the same data. Every schema change must work for both. Cost note: aliases and alarms cost little, but blue/green on ECS runs two sets of tasks for a while, so you pay double compute during the bake time.
Press Play on a diagram to walk through it one step at a time.
- 1Publish version 8
Alias live still points at version 7
- 2Shift 10 percent
Alias routing sends 0.1 weight to version 8
- 3Bake 10 minutes
Watch errors and p99 duration alarms
- 4Alarm quiet?
Yes: shift to 100 percent. No: weight back to 0
- 5Record evidence
Alias config, alarm history, smoke test
- 1Deploy new version
No traffic yet, smoke test passes
- 2Shift a small share
Canary 10 percent
- 3Bake and watch alarms
Errors, latency, business metric
- 4Promote or roll back
Automatic on alarm, recorded
- 5Review
Note timings, tune gates for next time
- Back to step 1
In depth
Lambda: versions, aliases and CodeDeploy
Publishing a Lambda version freezes the code and configuration under a number. An alias points at one version and can add a second with a weight between 0 and 1 using AdditionalVersionWeights. Clients and event sources should call the alias ARN, never $LATEST, so moving the alias is the release. Doing weight changes by hand works for learning. In practice, AWS SAM's AutoPublishAlias and DeploymentPreference create a CodeDeploy application that shifts traffic with configurations such as Canary10Percent5Minutes, Linear10PercentEvery1Minute or AllAtOnce, watches the alarms you list, and rolls the alias back if one fires. Optional pre-traffic and post-traffic hooks are Lambda functions that run checks before and after the shift. Note that weighted routing is per invocation, so one user can hit both versions.
- Call the alias ARN, never $LATEST, in production
- Weights apply per invocation, not per user
- SAM DeploymentPreference automates canary and rollback
- Hooks run checks before and after the shift
ECS: rolling updates, circuit breaker and alarms
An ECS service with the default ECS deployment controller does rolling updates, bounded by minimumHealthyPercent and maximumPercent. Turn on deploymentCircuitBreaker with enable and rollback set to true: if new tasks repeatedly fail to start or fail health checks, ECS marks the deployment failed and returns to the last completed deployment. The circuit breaker only sees task health, not business errors. For that, add CloudWatch alarms to the deployment configuration: if a named alarm goes into ALARM during the deployment, ECS can roll back too. For traffic-shifting releases, ECS supports blue/green deployments with a load balancer, and canary and linear variants that move a set percentage first and wait for a bake time. Earlier setups used CodeDeploy for this; check which your service uses before changing it.
- Watches task launch and health checks
- Catches crashes and bad images
- Rolls back to last completed deployment
- No traffic split
- Watches CloudWatch alarms you name
- Catches error rate or latency regressions
- Rolls back when an alarm fires
- Works with rolling updates
- New tasks behind a separate target group
- Shifts a share of traffic, then the rest
- Bake time before old tasks stop
- Fast switch back, double compute for a while
Choosing gates that actually catch problems
A gate is only as good as its alarm. Watch signals that the new version can break: error count or rate, p99 latency, throttles, and a business signal such as files processed per minute. For Lambda, alarm on the version-specific metric (the ExecutedVersion dimension or the alias with its version) so a bad canary is not hidden by the healthy majority. Size the bake time so the canary sees enough requests: 10 percent of 20 requests per minute is 2 requests per minute, so a 5-minute bake sees only about 10. Low-traffic services can add synthetic traffic with a CloudWatch Synthetics canary or a scheduled smoke test. Write the gate down: rollback if errors exceed 1 percent over 5 minutes, or if p99 rises by more than 30 percent.
- Alarm on the new version's metrics, not the total
- Enough traffic in the bake window to be meaningful
- Include one business metric
- Write the rollback rule before the release
Backward-compatible schema changes
Rolling back code is easy; rolling back data is not. Use expand and contract. Release 1 expands: add the new column or attribute, make it optional, and write both the old and new fields. Backfill existing rows in the background. Release 2 switches reads to the new field, while still writing both. Release 3, once no running version reads the old field, contracts: stop writing it and drop it. At every step, the previous release still works, so a rollback never meets data it cannot read. In DynamoDB the same idea applies to attributes and to item shapes in a single-table design. Never combine a destructive migration with the code change that depends on it in one release.
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Shift traffic with weighted aliases~40m
- 2Use the ECS deployment circuit breaker~40m
- 3Gate on CloudWatch alarms~40m
- 4Keep schema changes backward compatible~40m
- 5Practise the rollback~40m
Key points
- A Lambda alias is a stable name; moving it or weighting it is the release, not redeploying code.
- The ECS deployment circuit breaker rolls back when new tasks keep failing to start or pass health checks.
- CloudWatch alarms turn health into an automatic go or no-go signal.
- Schema changes must work with both the old and new version at the same time (expand, then contract).
- Practise the rollback before you need it and record how long it took.
Key terms
Tap a card to flip it. 0/5 known
Examples
NEW=$(aws lambda publish-version --function-name file-worker \
--query Version --output text)
# 90 percent stays on version 7, 10 percent goes to the new version
aws lambda update-alias --function-name file-worker --name live \
--function-version 7 \
--routing-config "AdditionalVersionWeights={$NEW=0.1}"
# promote: point at the new version and clear the split
aws lambda update-alias --function-name file-worker --name live \
--function-version $NEW --routing-config 'AdditionalVersionWeights={}'A manual Lambda canary; CodeDeploy or SAM can automate the same steps.
SAM template: canary for the file worker with an alarm gate
Prerequisites: AWS SAM CLI and the sandbox profile. Step 1: add AutoPublishAlias and DeploymentPreference as below. Step 2: sam deploy creates a version, an alias live and a CodeDeploy deployment group. Step 3: deploy a change and watch CodeDeploy shift 10 percent, wait 5 minutes, then shift the rest. Evidence: CodeDeploy deployment history and the alias weights. Test the rollback by deploying a version that throws errors: the alarm fires and CodeDeploy moves the alias back. Cleanup: sam delete.
FileWorker:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
Runtime: python3.12
AutoPublishAlias: live
DeploymentPreference: { Type: Canary10Percent5Minutes, Alarms: [!Ref WorkerErrorsAlarm] }
WorkerErrorsAlarm:
Type: AWS::CloudWatch::Alarm
Properties: { Namespace: AWS/Lambda, MetricName: Errors, Statistic: Sum, Period: 60,
EvaluationPeriods: 1, Threshold: 1, ComparisonOperator: GreaterThanOrEqualToThreshold,
Dimensions: [{ Name: FunctionName, Value: !Ref FileWorker }, { Name: Resource, Value: !Sub "${FileWorker}:live" }] }Turn on the ECS circuit breaker and practise a rollback
Prerequisites: an ECS service on Fargate from the runtime module. Step 1: enable the circuit breaker with rollback. Step 2: register a task definition revision that points at a missing image tag and update the service to it. Step 3: watch tasks fail to start. Evidence: the service deployment shows status FAILED, ECS rolls back, and service events mention the circuit breaker. Record how many minutes the rollback took. Cleanup: scale the lab service to zero or delete it.
aws ecs update-service --cluster lab --service file-api \
--deployment-configuration \
'deploymentCircuitBreaker={enable=true,rollback=true},maximumPercent=200,minimumHealthyPercent=100'
# release a broken revision on purpose
aws ecs update-service --cluster lab --service file-api \
--task-definition file-api:13
aws ecs describe-services --cluster lab --services file-api \
--query 'services[0].deployments[].[status,rolloutState,taskDefinition]'Quick reference
- Lambda canary: update-alias with AdditionalVersionWeights={NEW=0.1}.
- SAM DeploymentPreference types include Canary10Percent5Minutes and Linear10PercentEvery1Minute.
- ECS circuit breaker: deploymentCircuitBreaker enable=true, rollback=true.
- ECS deployment alarms roll back on named CloudWatch alarms during a deployment.
- Gate on the new version's metrics: errors, p99 latency and one business metric.
- Expand, migrate, then contract: never drop a field in the release that stops using it.
- Practise rollback on purpose and record how long it took.
Common mistakes
- Canarying too little traffic for too short a time, so the alarm never sees enough requests.
- Dropping a database column in the same release that stops using it, so rollback breaks.
- Alarms that watch the whole function instead of the new version, hiding a bad canary.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write the rollback rule for the file worker canary: which metrics, thresholds and bake time you would use, and why.
- Exercise 2medium
Run a manual Lambda canary in a sandbox: publish two versions, send 20 percent to the new one, invoke the alias 50 times and count which version answered.
- Exercise 3hard
Plan a three-release migration that renames the DynamoDB attribute size to bytes while canary releases continue, and describe the rollback at each step.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between canary and blue/green?
- Blue/green runs two full environments and switches traffic between them, often all at once. A canary sends a small share of traffic to the new version first and grows it step by step. Many tools combine the two.
- Do I need CodeDeploy for Lambda canaries?
- No. You can change alias weights yourself, which is good for learning. CodeDeploy, usually via SAM, automates the schedule, alarm checks and rollback.
- Can I roll back a database migration?
- Sometimes, but it is risky and slow. Design changes so the previous code still works with the new schema; then you only ever roll back code.
- How small should the canary be?
- Small enough that a bug affects few users, large enough that your alarms see meaningful traffic. 5 to 10 percent with a 10 to 30 minute bake is a common start.