Explain it simply
Like changing shifts in a shop
When a shop changes shifts, the new staff arrive and work alongside the old ones for a while. The old shift leaves only once the new one is clearly fine. If the new staff are unwell, the old shift stays and the shop never closes. That is a rolling update with a circuit breaker.
Blue/green is opening an identical branch next door and sending 10% of customers there first. If all is well, everyone goes there, and the old branch stays open for fifteen minutes so you can switch back instantly if something goes wrong.
Problem → Why → Solution
Overwriting ':latest' and restarting everything
You met ALBs and Auto Scaling in AWS Fundamentals. For many teams moving to containers, the first 'deploy' looks like the snippet below: overwrite ':latest' from a developer laptop and force a new deployment. In CI, it is often an IAM user's access key stored as a GitHub secret for years.
This leaves three questions without answers. Which commit is running right now? What do we roll back to, when ':latest' no longer points at the old version? And who stops the rollout if the new image fails to start?
# "Deploy" = overwrite :latest and restart everything at once
docker build -t 111122223333.dkr.ecr.us-east-1.amazonaws.com/web:latest .
docker push 111122223333.dkr.ecr.us-east-1.amazonaws.com/web:latest
aws ecs update-service --cluster web --service web --force-new-deployment
# Which code is running now? Which commit was running an hour ago?
# What do we roll back TO? ":latest" no longer points at it.Why this is dangerous
A mutable tag breaks the link between artifact and code. A long-lived key lets anyone who finds it deploy. And with nothing watching the rollout, tasks failing health checks restart in a loop until a human happens to notice.
Three layers of deployment safety
The first layer is an immutable artifact. Tag the image with the git commit SHA and turn on tag immutability in the ECR repository, and a tag always means exactly one image. With the SHA in the task definition you can always answer 'what is running?', and a rollback is simply deploying the previous SHA.
The second layer is the CI identity. GitHub Actions issues an OIDC token per job, and the IAM role trusts only tokens from this repository's production environment. The credentials expire within the hour and there is no secret to store.
The third layer is the rollout itself. With minHealthyPercent 100 and maxHealthyPercent 200, ECS starts new tasks first and removes old ones only after the new ones pass ALB health checks. The deployment circuit breaker fails the deployment when new tasks repeatedly fail to reach a steady state, and rolls back to the last completed version. The circuit breaker catches 'it does not start'. It does not catch 'it starts but returns 5xx'; that is what CloudWatch deployment alarms are for: if an alarm goes into ALARM during the rollout, ECS rolls back.
Blue/green goes one step further. The new version (green) runs at full size in a separate target group, can be tested through a test listener, and then receives traffic gradually (canary) or all at once. Blue stays ready the whole time, so rollback is just moving traffic back, which takes seconds. The price is double capacity during the deployment and more moving parts.
FROM COMMIT TO TRAFFIC
----------------------
git push main
|
v
GitHub Actions --OIDC token--> STS --> role github-deploy-web (1h)
| docker build/push web:<sha> (ECR: immutable tags, scan)
| cdk deploy Web-Service -c imageTag=<sha>
v
ECS service 'web' (rolling: min 100% / max 200%)
| new tasks <sha> start --> ALB health check /healthz
|
+-- tasks never healthy ------> circuit breaker --> ROLLBACK
+-- 5xx or p99 alarm fires ---> deployment alarm --> ROLLBACK
+-- healthy, alarms OK -------> old tasks drained --> COMPLETED- Deployment circuit breaker
- An ECS feature for rolling deployments: when new tasks keep failing to reach a steady state beyond a threshold, the deployment is marked FAILED and, with rollback enabled, ECS returns to the last COMPLETED deployment.
| Strategy | Rollback | Use when |
|---|---|---|
| Rolling + circuit breaker + alarms | Old tasks are started again (minutes) | Good default for most services |
| CodeDeploy blue/green | Traffic shifts back (seconds) | You need canary/linear shifts, a test listener or manual approval |
| ECS native blue/green | Traffic shifts back (seconds) | You want blue/green inside ECS without CodeDeploy (check the docs) |
- Tag image with the git SHA
- CI assumes role via OIDC
- New tasks start beside old ones
- Breaker + alarms decide
- Pass: drain old / Fail: rollback
Health checks and alarms, not a human watching a dashboard, decide whether a deploy succeeds.
A Dockerfile shape for production images
# Build stage: dev dependencies never reach production
FROM public.ecr.aws/docker/library/node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev
# Runtime stage: small, non-root, one process
FROM public.ecr.aws/docker/library/node:20-alpine
WORKDIR /app
ENV NODE_ENV=production PORT=8080
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
USER node
EXPOSE 8080
CMD ["node", "dist/server.js"]The multi-stage build keeps build tools and dev dependencies out of the runtime image, so it is small and pulls fast. USER node avoids running as root. Pulling the base image from ECR Public sidesteps Docker Hub rate limits. The app must listen on 8080 and serve /healthz.
The CDK app: registry, CI role and service
The app has two stacks. Web-Registry (the ECR repository and the GitHub OIDC role) is deployed once and lives long. Web-Service is redeployed on every commit with a new image tag, taken from CDK context (-c imageTag=...).
import { App, Duration, Stack, StackProps } from "aws-cdk-lib";
import * as cloudwatch from "aws-cdk-lib/aws-cloudwatch";
import * as ec2 from "aws-cdk-lib/aws-ec2";
import * as ecr from "aws-cdk-lib/aws-ecr";
import * as ecs from "aws-cdk-lib/aws-ecs";
import * as patterns from "aws-cdk-lib/aws-ecs-patterns";
import * as elbv2 from "aws-cdk-lib/aws-elasticloadbalancingv2";
import * as iam from "aws-cdk-lib/aws-iam";
import { Construct } from "constructs";
// Only this repo's "production" environment may assume the deploy role.
const GITHUB_SUB = "repo:example-org/web:environment:production";
// Long-lived: the registry and the CI identity outlive every deployment.
class RegistryStack extends Stack {
readonly repo: ecr.Repository;
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
this.repo = new ecr.Repository(this, "Repo", {
repositoryName: "web",
imageScanOnPush: true,
imageTagMutability: ecr.TagMutability.IMMUTABLE,
lifecycleRules: [{ maxImageCount: 50 }],
});
const github = new iam.OpenIdConnectProvider(this, "GitHub", {
url: "https://token.actions.githubusercontent.com",
clientIds: ["sts.amazonaws.com"],
});
const deployRole = new iam.Role(this, "DeployRole", {
roleName: "github-deploy-web",
maxSessionDuration: Duration.hours(1),
assumedBy: new iam.WebIdentityPrincipal(github.openIdConnectProviderArn, {
StringEquals: { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" },
StringLike: {
"token.actions.githubusercontent.com:sub": GITHUB_SUB,
},
}),
});
this.repo.grantPullPush(deployRole);
// cdk deploy works by assuming the bootstrap roles, nothing more.
deployRole.addToPolicy(
new iam.PolicyStatement({
actions: ["sts:AssumeRole"],
resources: [`arn:aws:iam::${this.account}:role/cdk-hnb659fds-*`],
}),
);
}
}
interface ServiceProps extends StackProps {
repo: ecr.IRepository;
imageTag: string;
}
class ServiceStack extends Stack {
constructor(scope: Construct, id: string, props: ServiceProps) {
super(scope, id, props);
const vpc = new ec2.Vpc(this, "Vpc", { maxAzs: 2, natGateways: 1 });
const cluster = new ecs.Cluster(this, "Cluster", {
vpc,
clusterName: "web",
containerInsightsV2: ecs.ContainerInsights.ENABLED,
});
const web = new patterns.ApplicationLoadBalancedFargateService(this, "Web", {
cluster,
serviceName: "web",
cpu: 512,
memoryLimitMiB: 1024,
desiredCount: 2,
minHealthyPercent: 100, // keep full capacity while new tasks start
maxHealthyPercent: 200,
circuitBreaker: { enable: true, rollback: true },
healthCheckGracePeriod: Duration.seconds(30),
taskImageOptions: {
image: ecs.ContainerImage.fromEcrRepository(props.repo, props.imageTag),
containerPort: 8080,
environment: { APP_VERSION: props.imageTag },
},
});
web.targetGroup.configureHealthCheck({
path: "/healthz",
healthyThresholdCount: 2,
interval: Duration.seconds(15),
});
web.targetGroup.setAttribute("deregistration_delay.timeout_seconds", "30");
const scaling = web.service.autoScaleTaskCount({ minCapacity: 2, maxCapacity: 10 });
scaling.scaleOnCpuUtilization("Cpu", { targetUtilizationPercent: 60 });
// Alarms that a bad deployment trips before customers notice.
const errors5xx = new cloudwatch.Alarm(this, "Target5xx", {
alarmName: "web-target-5xx",
// 5xx returned by the containers themselves (not by the ALB)
metric: web.loadBalancer.metrics.httpCodeTarget(
elbv2.HttpCodeTarget.TARGET_5XX_COUNT,
{ period: Duration.minutes(1), statistic: "Sum" },
),
threshold: 10,
evaluationPeriods: 2,
treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
});
const latency = new cloudwatch.Alarm(this, "P99Latency", {
alarmName: "web-p99-latency",
metric: web.targetGroup.metrics.targetResponseTime({
period: Duration.minutes(1),
statistic: "p99",
}),
threshold: 1.5, // seconds
evaluationPeriods: 3,
});
// ECS watches these during a rollout and rolls back if one fires.
web.service.enableDeploymentAlarms([errors5xx.alarmName, latency.alarmName], {
behavior: ecs.AlarmBehavior.ROLLBACK_ON_ALARM,
});
}
}
const app = new App();
const env = { account: process.env.CDK_DEFAULT_ACCOUNT, region: "us-east-1" };
const registry = new RegistryStack(app, "Web-Registry", { env });
new ServiceStack(app, "Web-Service", {
env,
repo: registry.repo,
imageTag: app.node.tryGetContext("imageTag") ?? "bootstrap",
});
app.synth();Not runnable in the browser
This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.
Code breakdown
- ECR repository
imageTagMutability: ecr.TagMutability.IMMUTABLETags can no longer be overwritten, so a SHA tag always means one image. Scan on push checks for vulnerabilities on every push, and the lifecycle rule deletes images beyond the newest fifty.
- OIDC deploy role
"token.actions.githubusercontent.com:sub": GITHUB_SUBThe role trusts only tokens with audience sts.amazonaws.com and sub 'repo:example-org/web:environment:production'. Forks, other branches and other repositories cannot assume it. Its permissions are ECR push and assuming the CDK bootstrap roles, nothing else.
- Rolling settings
minHealthyPercent: 100, maxHealthyPercent: 200New tasks start first so capacity never drops during a deploy. healthCheckGracePeriod ignores failed ALB checks while the app boots. A 30-second deregistration delay lets in-flight requests finish.
- Circuit breaker
circuitBreaker: { enable: true, rollback: true }If new tasks cannot start (image pull failure, crash loop, failing health checks) the deployment is marked FAILED and the old version comes back. The CloudFormation update fails too, so the pipeline goes red.
- Deployment alarms
web.service.enableDeploymentAlarms([...], { behavior: ROLLBACK_ON_ALARM })ECS watches two alarms during the rollout: target 5xx (errors returned by the containers themselves) and p99 latency. If either enters ALARM, it rolls back. NOT_BREACHING for missing data keeps the alarm quiet when there is no traffic.
Sample output (ARNs and DNS names vary):
✅ Web-Service
Outputs:
Web-Service.WebLoadBalancerDNS... = Web-S-WebLB-0a1b2c3d.us-east-1.elb.amazonaws.com
Web-Service.WebServiceURL... = http://Web-S-WebLB-0a1b2c3d.us-east-1.elb.amazonaws.com- New task definition registered
- New tasks start (max 200%)
- ALB health checks pass?
- Deployment alarms quiet?
- Old tasks drained
Everything passes
rolloutState COMPLETED
Breaker or alarm trips
FAILED -> previous version restored
The pipeline: GitHub Actions with OIDC
The workflow uses no secrets. The 'id-token: write' permission lets the job request an OIDC token, and the configure-aws-credentials action exchanges it via STS AssumeRoleWithWebIdentity for temporary credentials. 'environment: production' must match the role's sub condition; protect that GitHub environment with required reviewers and the job gets the role only after a human approves.
'concurrency' prevents two deploys from running at once, and cancel-in-progress false avoids killing a rollout halfway. If the circuit breaker or an alarm rolls back, cdk deploy fails and the workflow turns red.
name: deploy-web
on:
push:
branches: [main]
permissions:
id-token: write # lets the job request a GitHub OIDC token
contents: read
concurrency:
group: deploy-web-production
cancel-in-progress: false # never kill a rollout halfway
jobs:
deploy:
runs-on: ubuntu-latest
environment: production # must match the role's "sub" condition
env:
AWS_REGION: us-east-1
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::111122223333:role/github-deploy-web
aws-region: ${{ env.AWS_REGION }}
- id: ecr
uses: aws-actions/amazon-ecr-login@v2
- name: Build and push an immutable image
env:
REGISTRY: ${{ steps.ecr.outputs.registry }}
run: |
docker build -t "$REGISTRY/web:$GITHUB_SHA" app/
docker push "$REGISTRY/web:$GITHUB_SHA"
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Roll out (circuit breaker + alarms guard it)
working-directory: infra
run: |
npm ci
npx cdk deploy Web-Service -c imageTag="$GITHUB_SHA" \
--require-approval neverBlue/green: the CodeDeploy approach
CodeDeploy blue/green requires switching the ECS service's deployment controller to CODE_DEPLOY. You need two target groups (blue and green), the production listener and a test listener (8080). For each deployment, CodeDeploy starts the green task set, points the test listener at it, waits for approval (ten minutes in this app), then shifts production traffic with CANARY_10PERCENT_5MINUTES: 10% for five minutes, then the rest. Blue is kept for fifteen minutes and, if an alarm fires, traffic goes back to blue.
import { App, Duration, Stack, StackProps } from "aws-cdk-lib";
import * as cloudwatch from "aws-cdk-lib/aws-cloudwatch";
import * as codedeploy from "aws-cdk-lib/aws-codedeploy";
import * as ec2 from "aws-cdk-lib/aws-ec2";
import * as ecs from "aws-cdk-lib/aws-ecs";
import * as patterns from "aws-cdk-lib/aws-ecs-patterns";
import * as elbv2 from "aws-cdk-lib/aws-elasticloadbalancingv2";
import { Construct } from "constructs";
class BlueGreenStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const vpc = new ec2.Vpc(this, "Vpc", { maxAzs: 2, natGateways: 1 });
const cluster = new ecs.Cluster(this, "Cluster", { vpc });
// Same pattern, but CodeDeploy (not ECS) now controls deployments.
const web = new patterns.ApplicationLoadBalancedFargateService(this, "Web", {
cluster,
desiredCount: 2,
deploymentController: { type: ecs.DeploymentControllerType.CODE_DEPLOY },
taskImageOptions: {
image: ecs.ContainerImage.fromRegistry("public.ecr.aws/nginx/nginx:stable"),
containerPort: 80,
},
});
// Green target group + a test listener to smoke-test green before cutover.
const green = new elbv2.ApplicationTargetGroup(this, "Green", {
vpc,
port: 80,
protocol: elbv2.ApplicationProtocol.HTTP,
targetType: elbv2.TargetType.IP,
healthCheck: { path: "/" },
});
const testListener = web.loadBalancer.addListener("Test", {
port: 8080,
protocol: elbv2.ApplicationProtocol.HTTP,
defaultTargetGroups: [green],
});
const errors = new cloudwatch.Alarm(this, "Green5xx", {
metric: green.metrics.httpCodeTarget(elbv2.HttpCodeTarget.TARGET_5XX_COUNT, {
period: Duration.minutes(1),
statistic: "Sum",
}),
threshold: 5,
evaluationPeriods: 1,
treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
});
new codedeploy.EcsDeploymentGroup(this, "Deploy", {
service: web.service,
blueGreenDeploymentConfig: {
blueTargetGroup: web.targetGroup,
greenTargetGroup: green,
listener: web.listener,
testListener,
deploymentApprovalWaitTime: Duration.minutes(10),
terminationWaitTime: Duration.minutes(15),
},
deploymentConfig: codedeploy.EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES,
alarms: [errors],
autoRollback: { failedDeployment: true, deploymentInAlarm: true },
});
}
}
const app = new App();
new BlueGreenStack(app, "Web-BlueGreen");
app.synth();# Green is up and receiving TEST traffic on :8080. Smoke-test it:
curl -fsS "http://$ALB_DNS:8080/"
# Happy? Let CodeDeploy shift production traffic (canary 10%, then 100%)
aws deploy continue-deployment --deployment-id "$DEPLOYMENT_ID" \
--deployment-wait-type READY_WAIT
# Not happy? Stop and roll back: production traffic is still on blue
aws deploy stop-deployment --deployment-id "$DEPLOYMENT_ID" --auto-rollback-enabledWhat the CODE_DEPLOY controller changes
With the CODE_DEPLOY controller, the ECS circuit breaker is not available; CodeDeploy owns rollback. After the first deploy, new versions roll out by creating a CodeDeploy deployment whose AppSpec names the new task definition, not by a plain service update. That changes your pipeline design, so check the documentation before committing to it.
ECS native blue/green
ECS itself now supports a blue/green deployment strategy within the ECS deployment controller, with a bake time and lifecycle hooks, and no CodeDeploy. In CDK it appears as the deploymentStrategy property. It is relatively new, so confirm supported load balancer types, regions and CDK version in the ECS developer guide before adopting it.
Watching a rollout and finding why it rolled back
When a rollback happens, read the service events first: ECS states the reason in plain words such as 'circuit breaker triggered' or 'alarm ... in ALARM state'. Then check the stopped task's stoppedReason and exit code. Exit code 137 usually means the container was killed for exceeding memory, and 'CannotPullContainerError' usually means a wrong image tag or missing execution role permissions.
# One PRIMARY deployment = steady. PRIMARY + ACTIVE = rollout in progress.
aws ecs describe-services --cluster web --services web \
--query 'services[0].deployments[].[status,rolloutState,runningCount]'
# Why did it roll back? The service events say so in plain words.
aws ecs describe-services --cluster web --services web \
--query 'services[0].events[:5].message'
# Tasks that died during the rollout, and why
aws ecs list-tasks --cluster web --service-name web --desired-status STOPPED
aws ecs describe-tasks --cluster web --tasks "$TASK_ARN" \
--query 'tasks[0].[stoppedReason,containers[0].exitCode]'
# Block until the service is steady (handy as a pipeline gate)
aws ecs wait services-stable --cluster web --services webIn production
How production teams do it
In production the image is built once and the same SHA is promoted to staging and then production. Rebuilding per environment means the artifact you tested in staging is not the one you ship. With separate accounts, each of staging and production has its own OIDC role, and only the protected environment can assume the production role.
Deployment alarms are chosen with one question: 'would I accept a rollback because of this alarm?'. An alarm that fires on downstream dependency problems will roll back every deploy even when your code is fine. Most teams use target 5xx rate and latency, and add a business metric such as checkout success rate.
Teams also rehearse rollback monthly: they deliberately deploy a build whose /healthz fails to staging and confirm the circuit breaker does its job.
Common mistakes
Common mistakes
A health check that tests dependencies
If /healthz also pings the database, one slow database moment marks every task unhealthy and the ALB removes all of them: a full outage. A load balancer health check should answer only 'can this process accept requests?'; dependency health belongs in metrics and alarms.
An OIDC trust with a wildcard
With a sub condition of 'repo:example-org/*', or none at all, any repository, branch or pull-request workflow in the organization can assume the production role. Pin sub to the exact repository and environment (or branch), and always include the audience condition.
Relying on the circuit breaker alone
The circuit breaker only catches tasks that fail to start. It is blind to a version that passes health checks but returns 500 on the checkout endpoint. Without deployment alarms, that version rolls out completely.
Best practices
Best practices
- Tag images with the git SHA and enable ECR tag immutability
- Connect CI only through an OIDC role whose sub is pinned to repo and environment
- Use both the circuit breaker (with rollback) and deployment alarms
- Choose blue/green when you need instant rollback, test traffic or canaries
💰 Cost & Cleanup
What costs money here: Fargate tasks (per vCPU and GB-hour, two tasks always running), the ALB (hourly plus LCUs), the NAT Gateway (hourly plus per GB processed), ECR storage, CloudWatch alarms and Container Insights metrics. Deploying the blue/green stack as well doubles the ALB, NAT and tasks. Most of this is outside the free tier, so even a few days adds up. Delete everything as soon as you finish.
Clean up when you are done
cdk destroy Web-Service Web-BlueGreen
# The registry stack keeps images; delete them with the repository
aws ecr delete-repository --repository-name web --force
cdk destroy Web-RegistryMini challenge
Make the pipeline rollback-aware and add a smoke test
Add two steps after the deploy step: one that proves the rollout really COMPLETED, and one that proves the live app reports the SHA that was just deployed.
- Wait until the service is stable, then check the first deployment's rolloutState
- Fail the job unless it is COMPLETED
- Call /version with retries and compare it with GITHUB_SHA
Expected: On success the log shows 'rollout state: COMPLETED' and 'live version: <sha>'. After a rollback the job turns red.
Show hint
Run 'aws ecs wait services-stable', then describe-services with --query 'services[0].deployments[0].rolloutState'. The app must return its APP_VERSION env var on /version.
Show solution
- name: Prove the rollout finished and was not rolled back
run: |
aws ecs wait services-stable --cluster web --services web
state=$(aws ecs describe-services --cluster web --services web \
--query 'services[0].deployments[0].rolloutState' --output text)
echo "rollout state: $state"
test "$state" = "COMPLETED"
- name: Smoke test the live version
env:
URL: ${{ vars.WEB_URL }}
run: |
for i in 1 2 3 4 5; do
body=$(curl -fsS "$URL/version") && break
sleep 10
done
echo "live version: $body"
test "$body" = "$GITHUB_SHA"Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- You need all three layers: immutable SHA tags, OIDC identity and a guarded rollout
- The circuit breaker catches 'does not start'; deployment alarms catch 'starts but misbehaves'
- minHealthyPercent 100 / maxHealthyPercent 200 keeps full capacity during a deploy
- Blue/green gives rollback in seconds at the cost of double capacity and more moving parts
Amazon ECS deployment types — AWS Documentation
Configuring OpenID Connect in AWS (GitHub Docs) — AWS Documentation
AWS CodeDeploy: blue/green deployments for Amazon ECS — AWS Documentation