examlab .net The most efficient path to the most valuable certifications.
In this note ≈ 25 min

Lambda Deployment — Aliases, Traffic Shifting, and SAM Canary

5,000 words · ≈ 25 min read ·

DOP-C02 deep dive on Lambda deployment strategies: aliases and versions, weighted traffic shifting, CodeDeploy canary and linear configurations, SAM and CloudFormation deployment preferences, alarm-based auto rollback, and provisioned concurrency during deploys.

Do 20 practice questions → Free · No signup · DOP-C02

Lambda deployment is the simplest serverless operation in concept and the trickiest to get right at Pro tier. The DOP-C02 exam expects fluency in Lambda's versioning model, alias-based traffic shifting, CodeDeploy integration for canary and linear rollout, the AWS SAM DeploymentPreference shorthand, alarm-based automatic rollback, and the gotchas around provisioned concurrency during deploys. Unlike EC2 or ECS, Lambda has no instances or tasks to drain — traffic shifting happens at the alias layer, so the entire deployment story is about pointing an alias at a different (or weighted) version.

This guide builds the Lambda deployment mental model from versions and aliases up. It covers when to use raw alias updates versus CodeDeploy-managed traffic shifting, how SAM's DeploymentPreference simplifies the CodeDeploy plumbing, how PreTraffic and PostTraffic hooks plug in for validation, how alarm-based rollback works, and the subtle interaction between provisioned concurrency and version replacement. By the end you should be able to look at any Lambda deployment question and instantly recognise whether the answer is "use an alias", "use CodeDeploy with a canary configuration", or "use SAM AutoPublishAlias plus DeploymentPreference".

Why Lambda Deployment Demands Pro-Level Thinking

Lambda deployments differ from EC2 and ECS in three critical ways. First, immutability at the version: every published version is immutable, which makes rollback a metadata-only operation (point alias at old version) — no re-deployment of code. Second, alias-as-routing-layer: aliases can route weighted traffic to two versions simultaneously (e.g., 90% to v5, 10% to v6) without any infrastructure change. Third, invocation-time integration: API Gateway, EventBridge, S3 events, SNS, SQS, and other invokers point at the alias, not the function name; the alias is the stable address.

Together these properties make Lambda's deployment model uniquely well-suited for canary deployments — you literally just adjust alias weights. The complexity comes from automation: CodeDeploy plus alarm-based rollback transforms manual weight adjustment into a hands-off canary or linear rollout, and SAM DeploymentPreference reduces the CodeDeploy configuration to two lines of YAML.

DOP-C02 questions tend to test (1) when CodeDeploy adds value over a raw alias update, (2) the verbatim names of CodeDeploy Lambda configurations, (3) PreTraffic and PostTraffic hook semantics, and (4) the interaction between alias updates and provisioned concurrency.

  • Lambda version: an immutable snapshot of function code and configuration; identified by a numeric version (e.g., 1, 2) or $LATEST for the unpublished version.
  • Lambda alias: a named pointer to a version (or weighted pair of versions) that invokers can target instead of $LATEST; common names: prod, staging, live.
  • Weighted alias: an alias configuration with RoutingConfig.AdditionalVersionWeights mapping a second version to a fractional weight (0.0–1.0).
  • CodeDeploy Lambda deployment configuration: a named policy controlling traffic-shift schedule (e.g., LambdaCanary10Percent5Minutes, LambdaLinear10PercentEvery1Minute).
  • PreTraffic hook: a Lambda function CodeDeploy invokes before any traffic shifts, used for validation; non-zero exit aborts deployment.
  • PostTraffic hook: a Lambda function CodeDeploy invokes after traffic fully shifts, used for post-deploy verification.
  • AutoPublishAlias (SAM): a SAM property that auto-publishes a new version on every code update and points the named alias at it.
  • DeploymentPreference (SAM): a SAM property declaring CodeDeploy configuration (Type, Hooks, Alarms, Role) for a function.
  • Provisioned concurrency: pre-warmed Lambda execution environments; tied to a specific version or alias, with subtle interactions during deploys.
  • Reference: https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html

Plain-Language Explanation: Lambda Deployment

Lambda deployment can feel different from other compute platforms because there is no fleet to manage. Three analogies from different domains make the alias-based traffic-shifting model intuitive.

Analogy 1: Phone Forwarding Service

Picture a small business with a published phone number that forwards to whichever staff member is on duty. The published phone number is the alias — printed on business cards, in the phone book, given to API Gateway and EventBridge. The specific staff member's direct line is the version — immutable, fixed at hire time. Updating the alias is changing the forwarding rule — instant, atomic, no caller experiences any disruption.

Weighted aliases are call-routing magic: 90% of incoming calls go to the experienced staff member (version 5), 10% are routed to the new hire (version 6) for evaluation. After a week of evaluation, if the new hire's call quality holds up, the routing flips to 100% to the new hire. Rollback is flipping the rule back to the experienced staff — a single phone-system change, no re-training or re-hiring required.

CodeDeploy with canary configuration is the automated phone-routing manager: it adjusts the percentage on a schedule (10% for 5 minutes, then 100%), monitors call-complaint metrics, and if complaints spike it auto-flips routing back to the experienced staff. The PreTraffic hook is the vetting interview — before any real customer call hits the new hire, the manager runs a mock call (synthetic test); if the new hire bombs the mock, no real traffic is shifted.

Analogy 2: Restaurant Tasting-Menu Trial

A high-end restaurant introduces a new dish. The published menu lists the dish by name (the alias seared scallops). Behind the scenes, the chef has two recipes — recipe v5 (the proven preparation) and recipe v6 (the new technique). The kitchen runs a canary trial: of the next 10 orders for seared scallops, 1 is prepared with recipe v6 (new technique) and 9 with recipe v5 (proven). If the v6 plate comes back perfectly, the chef increases v6 to 25% next service, then 50%, then 100%.

The PreTraffic hook is the tasting-by-the-chef — the new recipe must be plated and tasted by the head chef before any customer receives it. The PostTraffic hook is the post-service review — after the new recipe is fully rolled out, the chef reviews customer feedback for the entire service to confirm acceptance.

Analogy 3: Software Beta Testing Programme

A consumer software company runs a beta programme for a new feature. The product (alias) appears in the app store as one entity. Internally, versions are immutable releases — v5 is the current production release, v6 is the beta. The company's rollout system routes 1% of users to v6 for the first day, 5% for the second day, 20% for the third day, 100% by the fourth day. Crash reports are the CloudWatch alarm — if v6 crashes more than v5 by some threshold, the rollout system auto-reverts to 100% v5 within minutes. No engineer needed.

The phone-forwarding analogy maps cleanest to alias updates and is the most intuitive for first-time learners. The restaurant analogy is best for hook semantics. The software beta analogy is the right model when the exam emphasises percentage-based rollout and alarm-driven rollback. Reference: https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html

Versions and Aliases — The Foundation

Every Lambda function starts with a single version: $LATEST. This is mutable — every code update overwrites it. Publishing a version (PublishVersion API or aws lambda publish-version) creates an immutable numbered version (1, 2, 3, ...) by snapshotting the current $LATEST.

Aliases are named pointers that resolve to a version. A prod alias might point at version 5; updating the alias to version 6 changes which code prod requests hit. Aliases support weighted routing: a prod alias can point at version 5 with AdditionalVersionWeights: {6: 0.10}, sending 10% of invocations to version 6 and 90% to version 5.

Critical convention: invokers always target the alias, never $LATEST directly. API Gateway integrations, EventBridge rules, S3 event notifications, SNS subscriptions, and SQS event sources all should reference function-name:prod, not function-name (which means $LATEST). This makes alias updates the single point of release control.

CodeDeploy Lambda Deployment Configurations

CodeDeploy automates alias weight adjustment over time. The configuration determines the schedule:

  • CodeDeployDefault.LambdaAllAtOnce: shift 100% in one step. Equivalent to a raw alias update; CodeDeploy adds nothing except hooks and rollback.
  • CodeDeployDefault.LambdaCanary10Percent5Minutes: 10% for 5 minutes, then 100%.
  • CodeDeployDefault.LambdaCanary10Percent10Minutes: 10% for 10 minutes, then 100%.
  • CodeDeployDefault.LambdaCanary10Percent15Minutes: 10% for 15 minutes, then 100%.
  • CodeDeployDefault.LambdaCanary10Percent30Minutes: 10% for 30 minutes, then 100%.
  • CodeDeployDefault.LambdaLinear10PercentEvery1Minute: 10% steps, 1 minute apart (10 minutes total).
  • CodeDeployDefault.LambdaLinear10PercentEvery2Minutes: 10% steps, 2 minutes apart.
  • CodeDeployDefault.LambdaLinear10PercentEvery3Minutes: 10% steps, 3 minutes apart.
  • CodeDeployDefault.LambdaLinear10PercentEvery10Minutes: 10% steps, 10 minutes apart.

Custom deployment configurations let you define arbitrary canary or linear schedules for non-standard SLAs.

The exam sometimes shows a partial config name in answer choices and asks which is canary vs linear. Canary names always include Canary{percent}Percent{minutes}Minutes (one initial percentage, then jump to 100). Linear names include Linear{percent}PercentEvery{minutes}Minute(s) (uniform increments throughout). Knowing the schema lets you answer even if you have not memorised every variant. Reference: https://docs.aws.amazon.com/codedeploy/latest/userguide/deployment-configurations.html

SAM AutoPublishAlias and DeploymentPreference

AWS SAM compresses the entire Lambda canary plumbing into two properties:

Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./src
      Handler: app.handler
      Runtime: nodejs18.x
      AutoPublishAlias: live
      DeploymentPreference:
        Type: Canary10Percent5Minutes
        Hooks:
          PreTraffic: !Ref PreTrafficHookFunction
          PostTraffic: !Ref PostTrafficHookFunction
        Alarms:
          - !Ref ErrorRateAlarm
        Role: !GetAtt CodeDeployRole.Arn

AutoPublishAlias: live instructs SAM to (1) publish a new version of the function on every code change, and (2) ensure an alias live exists pointing at the latest published version.

DeploymentPreference declares the CodeDeploy configuration: Type selects the schedule (Canary10Percent5Minutes, Linear10PercentEvery1Minute, etc.), Hooks lists pre- and post-traffic Lambda functions, Alarms lists CloudWatch alarms for auto rollback, and Role is the CodeDeploy service role.

Behind the scenes, SAM generates the CodeDeploy application, deployment group, and deployment configuration as CloudFormation resources. The exam loves to test that DeploymentPreference exists in SAM but not in raw CloudFormation AWS::Lambda::Function — for plain CFN you must declare the CodeDeploy resources manually.

PreTraffic and PostTraffic Hooks

Hooks are Lambda functions CodeDeploy invokes during the deployment lifecycle, paid for by the deploying account at standard Lambda rates.

PreTraffic hook runs after the new version is published but before any traffic shifts. Use it for synthetic invocations of the new version (with a test payload) to validate basic functionality. The hook function calls aws codedeploy put-lifecycle-event-hook-execution-status --status Succeeded (or Failed) to signal CodeDeploy whether to proceed.

PostTraffic hook runs after the deployment completes (alias points entirely at the new version). Use it for end-to-end verification — synthetic API calls, integration tests, smoke tests across dependent services. Same status-signalling pattern.

A typical PreTraffic hook invokes the new version directly with a known-good test event and verifies the response shape; a PostTraffic hook calls the API Gateway endpoint that fronts the function and verifies a happy-path response.

A hook function that completes successfully without calling PutLifecycleEventHookExecutionStatus will eventually time out (after the deployment timeout) and CodeDeploy will mark it Failed. Many candidates assume returning normally from the hook is enough; it is not. The hook function must explicitly call the CodeDeploy API to report status. Reference: https://docs.aws.amazon.com/lambda/latest/dg/services-codedeploy.html

Alarm-Based Auto Rollback

CodeDeploy can roll back the alias automatically when a CloudWatch alarm enters ALARM during the deployment. Configure via DeploymentPreference.Alarms (SAM) or alarmConfiguration (raw CodeDeploy).

Best practice alarms:

  • Function error rate: Errors / Invocations > 1% over 1 minute.
  • Function duration: Average Duration > 1000ms for high-priority functions.
  • API Gateway 5xx error rate: catches downstream impacts of bad Lambda code.
  • Custom metrics from EMF: business-level signals embedded in logs via embedded metric format.

When the alarm trips during a canary or linear deployment, CodeDeploy halts the schedule and reverts the alias to the previous version — instant rollback because it is just a metadata change.

Provisioned Concurrency Interaction

Provisioned concurrency keeps execution environments warm. It is allocated to a specific version or alias and is the source of subtle deployment interactions.

If provisioned concurrency is on the alias, weight-shifting splits the provisioned capacity proportionally. A canary at 10% to v6 with 100 PC on the alias means 10 PC at v6 and 90 PC at v5. CodeDeploy auto-handles the rebalance.

If provisioned concurrency is on a specific version, that version retains its PC regardless of alias updates. A common deploy pattern: pre-allocate PC on the new version before traffic shift starts so the canary does not see cold starts. SAM's ProvisionedConcurrencyConfig can be tied to the alias for this auto-balance.

A subtle gotcha: deploying a function with version-specific provisioned concurrency without re-allocating PC on the new version means the new version starts cold under traffic. Always tie PC to the alias unless you have a reason not to.

Provisioned concurrency on the alias auto-rebalances during canary; provisioned concurrency on a fixed version does not migrate to the new version. The exam tests "the canary deployment is causing user-visible cold starts" — the fix is moving PC from version to alias. Reference: https://docs.aws.amazon.com/lambda/latest/dg/provisioned-concurrency.html

Comparison — Raw Alias Update vs CodeDeploy

Three approaches to Lambda deployment, in order of automation:

1. Raw alias update (UpdateAlias API): instantaneous switch from old to new version. No traffic-weighted shift, no hooks, no auto rollback. Use for non-critical functions where rollback is acceptable to be a manual operation.

2. Manual weighted alias update: set RoutingConfig.AdditionalVersionWeights and adjust manually over time. Gives canary semantics but requires operator scheduling. Rare in production.

3. CodeDeploy with deployment preference: full automation with scheduled traffic shift, hooks, alarms. Standard for production.

Choose 3 by default for any function with stated SLA, customer-facing impact, or alarm-based rollback requirements. Use 1 for internal automation, scheduled batch jobs, or ops scripts.

CloudFormation Deployment Considerations

When deploying Lambda functions via raw CloudFormation (AWS::Lambda::Function), code updates trigger an in-place replacement of $LATEST. To get versioning semantics, you must explicitly create AWS::Lambda::Version resources — but those are immutable, so each update requires a new logical resource ID.

This is what SAM's AutoPublishAlias automates. Without SAM, the canonical raw-CFN pattern is to encode the function code's S3 object version in the AWS::Lambda::Version logical ID, forcing CloudFormation to create a fresh version resource on every code change.

For DOP-C02, knowing that "SAM is preferred for Lambda CI/CD" is enough; you rarely need to write the raw-CFN pattern from scratch.

Common Trap Patterns

Trap one: deploying with LambdaAllAtOnce and expecting auto rollback to catch problems. AllAtOnce gives you the rollback mechanism but no canary period — by the time alarms fire, all traffic already hits the new version.

Trap two: pointing API Gateway integration at $LATEST instead of the alias. Updates to $LATEST immediately affect production with no rollback path.

Trap three: PreTraffic hook does not call PutLifecycleEventHookExecutionStatus. Hook silently times out and fails the deployment.

Trap four: alarms on the alias's metrics — by default, CloudWatch metrics are emitted per function, not per alias. To alarm on alias-level metrics, enable per-alias metrics or use embedded metric format.

Trap five: forgetting to allocate provisioned concurrency on the new version before canary traffic shifts; PC tied to the old version means new-version cold starts during canary.

CodeDeploy auto-rollback fires when an associated alarm enters ALARM. If a brand-new alarm has insufficient data (no datapoints yet), it stays in INSUFFICIENT_DATA — CodeDeploy treats this as healthy. For freshly-created functions or alarms, ensure baseline metrics exist before relying on alarm-based rollback. The exam tests stems where the alarm "didn't fire" because of insufficient data. Reference: https://docs.aws.amazon.com/codedeploy/latest/userguide/deployment-configurations.html

End-to-End Lambda Pipeline Pattern

A canonical DOP-C02 Lambda pipeline assembles like this. Source in CodeCommit. Build in CodeBuild runs sam build, runs unit tests, and produces a packaged.yaml and zipped code uploaded to S3. Deploy to staging via CloudFormation deploy action targeting a SAM stack with DeploymentPreference: AllAtOnce. Approval action pauses for release-manager signoff. Deploy to production uses the same CFN deploy action against a production stack with DeploymentPreference: Canary10Percent5Minutes, PreTraffic hooks invoking synthetic tests, PostTraffic hooks calling integration tests, and alarms on function error rate and duration plus API Gateway 5xx.

Memorise this pattern — it is the reference architecture the exam tests permutations of.

For any Lambda deployment question, anchor on:

  1. Versions and aliases: invokers target the alias; alias points at one version (or weighted pair).
  2. CodeDeploy configuration: AllAtOnce (no canary), Canary{percent}Percent{minutes}Minutes (single canary step), or Linear{percent}PercentEvery{minutes}Minute(s) (uniform ramp).
  3. Hooks: PreTraffic (validate before shift), PostTraffic (verify after shift); both must call PutLifecycleEventHookExecutionStatus.
  4. Alarms: tie to function error rate, duration, downstream API Gateway 5xx; auto rollback when in ALARM.

SAM's AutoPublishAlias plus DeploymentPreference encapsulates 1–4 in two YAML properties. Reference: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-function-deploymentpreference.html

常考陷阱(Common Exam Traps)

  1. Invoking $LATEST instead of an alias — every code update immediately affects production with no rollback path; production invokers must always target the alias.
  2. PreTraffic hook missing PutLifecycleEventHookExecutionStatus — hook times out and fails the deployment even when it ran successfully.
  3. Provisioned concurrency on a fixed version — does not migrate to the new version during canary; cold-start spikes during traffic shift. Allocate PC on the alias for auto-rebalance.
  4. Alarm in INSUFFICIENT_DATA state — auto rollback only triggers on ALARM; freshly-created alarms with no data points do not fire.
  5. LambdaAllAtOnce expecting canary safety — AllAtOnce shifts all traffic immediately; alarms still trigger rollback but every user has already hit the bad version.

FAQ

Q1: When is CodeDeploy worth it over a raw alias update? Whenever the deployment needs traffic-weighted shift, alarm-based auto rollback, or hooks. Raw alias updates are fine for ops scripts and internal Lambdas. CodeDeploy is the default for production customer-facing functions with SLAs.

Q2: Can I use CodeDeploy for Lambda without SAM? Yes. Declare AWS::CodeDeploy::Application, AWS::CodeDeploy::DeploymentGroup, and link to the function alias manually in CloudFormation. SAM hides this boilerplate; the underlying CodeDeploy mechanics are identical.

Q3: What happens to in-flight invocations during a Lambda deployment? They complete on whichever version the alias resolved to at invocation time. Lambda does not forcibly terminate running executions during traffic shift. Long-running invocations may complete on the old version after canary started.

Q4: How do I roll back a Lambda alias to a specific previous version? Manual rollback: aws lambda update-alias --name prod --function-version 5 --routing-config AdditionalVersionWeights={}. CodeDeploy rollback re-creates a deployment with the previous task-set's version as the target.

Q5: Does CodeDeploy support Lambda blue/green in the EC2 sense? The Lambda service does not have multiple "fleets" — Lambda's blue/green is the alias-weighted traffic shift between versions. Conceptually it is blue/green (old version stays alongside new version) but mechanically it is alias routing.

Q6: Why would I use LambdaLinear10PercentEvery1Minute over LambdaCanary10Percent5Minutes? Linear gradually ramps over the full deployment window (10 minutes for Linear10PercentEvery1Minute). Canary holds 10% for 5 minutes then jumps to 100%. Linear is safer for slowly-manifesting issues; canary is faster and adequate for fast-failing bugs.

Q7: How do I synchronise a Lambda function deployment with a downstream DynamoDB schema change? Two-phase deploy. (1) DynamoDB table update first (add new column, dual-write code). (2) Lambda function deploy that reads new column. (3) Backfill old data. (4) Lambda follow-up deploy that drops dual-write. Wrap as a Step Functions state machine for orchestration; CodeDeploy alone does not handle multi-resource sequencing.

Q8: Can I share a deployment configuration across multiple Lambda functions? Yes. The CodeDeploy application can have multiple deployment groups, each targeting a different function alias. The same custom or default deployment configuration can be referenced by multiple groups. This is the standard pattern for monorepo serverless apps with many functions.

Official sources

More DOP-C02 topics