AWS deployments

AWS Lambda Deployment Rollback with GitHub Actions

Check that a new version works before sending users to it. If the release fails, have a clear way to switch back to the previous version.

By Published 3 November 2026Updated 5 November 202612 minute read

Technical review by Anuj Dhadge · Co-Founder · DevOps Engineer

A deployment can finish without errors while the application still fails for users. The new code might be running, but can it save data, read it back and allow the right people to use it?

This guide explains how to check an AWS Lambda release and switch back to the previous version when those checks fail. Switching back is called a rollback. We use Python code from Anrotex's Cloud Operations project and show how it connects to GitHub Actions.

You can also download the tests to run on your computer. They let you try the release and safety checks without an AWS account.

1. Keep the working version available

Keep the current version running while you check the new one. Lambda supports this through an alias: a name that points to a particular version of your code. In this example, that name is live.

API Gateway, the AWS service that receives requests for this application, sends them to live. Uploading a new version does not change that name's target. The application keeps using the previous version until the script switches it.

Publishing a Lambda version saves its code and most settings. For the settings AWS allows you to change later, see its function version documentation.

Upload the new version
The application keeps using the previous version
Test the new version
If a check fails, stop and keep the previous version
Checks pass
Switch to the new version
Check access, which version is running, and whether the app can save and read data
Checks pass

Keep using the new version.

Checks fail

Try to switch back. Report the release as failed.

If the script stops or cannot switch back, an engineer needs to check which version is running and restore service.

The script checks the app immediately after a release. It does not keep watching for problems later. It also stops if the alias is already splitting requests between multiple versions; this example expects one version to receive all requests.

2. Check the new version before using it

First, the script records the version currently in use so it knows where to switch back. It then uploads and publishes the new code with Publish=True and waits for the update.

Using Qualifier=version, it calls that specific version directly. The application continues to use the old version while these checks run:

  • Is this the right version? GET /health must return HTTP 200, the success response, and the code version we expect.
  • Can it save data? POST /requests must create a test record or return the same record if the check has already created it.
  • Can it read that data? A request for the saved record must return the expected content.

If any check fails, the script stops before switching versions. Adapt these checks to the actions that matter in your application. Label test records clearly, decide when to delete them, and keep them out of customer reports.

Calling Lambda directly does not check whether API Gateway allows the right people in. That check comes after the switch.

3. Switch versions, then check the application

After the first checks pass, the script changes live to point to the new version. Each change includes a RevisionId, a value AWS uses to detect whether someone else changed the alias in the meantime. If they did, AWS rejects our change. See the UpdateAlias reference.

Here is the complete release() function. The download also contains candidate_check(), which performs the checks described above.

def release(client, name, artifact, release_id, probe, check=candidate_check):
    previous = client.get_alias(FunctionName=name, Name="live")
    if previous.get("RoutingConfig", {}).get("AdditionalVersionWeights"):
        raise RuntimeError("Weighted aliases are outside this release workflow")
    current = client.get_function(FunctionName=name)
    upload = client.update_function_code(
        FunctionName=name, ZipFile=artifact, Publish=True,
        RevisionId=current["Configuration"]["RevisionId"],
    )
    client.get_waiter("function_updated_v2").wait(FunctionName=name)
    version = upload["Version"]
    check(client, name, version, release_id)
    promoted = client.update_alias(FunctionName=name, Name="live", FunctionVersion=version,
                                   RevisionId=previous["RevisionId"])
    try:
        probe(release_id)
    except Exception:
        # RevisionId prevents overwriting somebody else's subsequent promotion.
        client.update_alias(FunctionName=name, Name="live", FunctionVersion=previous["FunctionVersion"],
                            RevisionId=promoted["RevisionId"])
        print(json.dumps({"event": "rollback", "restored_version": previous["FunctionVersion"]}), flush=True)
        raise
    return {"event": "promoted", "previous_version": previous["FunctionVersion"], "version": version, "release": release_id}

Next, the script tests the application through API Gateway. It checks that requests without AWS authentication are refused. It then uses AWS request signing, called SigV4, to make authenticated requests and check:

  • The application is running the expected code version.
  • It can create a record and read it back.
  • Repeating the same request returns the same record instead of creating a duplicate.

If these checks fail, the script tries to point live back to the previous version. It uses the latest revision value from its own change, so it will not overwrite another release that happened afterwards.

The release is still reported as failed, even if switching back succeeds. The script does not test the application again after switching back; an engineer must confirm it works. If the switch fails, check the version now running before making another change.

Switching code versions does not undo saved data, database changes or infrastructure changes. The old version must still be able to use the current data. Keep it available and plan database changes separately.

4. Control releases with GitHub Actions

The GitHub Actions workflow runs tests when code is pushed or a pull request is opened. The release step runs only after those tests pass. Someone must start it manually from main and choose deploy=true.

This part of the workflow sets those rules:

release:
  if: github.event_name == 'workflow_dispatch' && inputs.deploy && github.ref == 'refs/heads/main'
  needs: verify
  runs-on: ubuntu-latest
  timeout-minutes: 15
  environment: aws-sandbox
  concurrency:
    group: aws-sandbox-release
    cancel-in-progress: false
  permissions:
    contents: read
    id-token: write

The full workflow also downloads the selected code, sets up Python and installs the package versions recorded for the project. It uses a specific version of aws-actions/configure-aws-credentials to get temporary AWS access.

That access uses OIDC, which lets GitHub prove its identity to AWS without storing long-lived AWS keys. The workflow then builds the application package and runs the release script:

Use the downloaded release.py and smoke.py in your project's scripts folder when following these commands.

python scripts/package.py --release "$GITHUB_SHA"
python scripts/release.py --function "$FUNCTION" \
  --artifact build/function.zip --release "$GITHUB_SHA" \
  --url "$API_URL" --region "$REGION" \
  --confirm-test-account "$TEST_ACCOUNT_ID"

The package contains GITHUB_SHA, the identifier for the chosen code commit. The checks use it to confirm which code is running. Set FUNCTION to the Lambda function name, API_URL to the application's address and REGION to its AWS region.

Set TEST_ACCOUNT_ID to the 12-digit ID of your separate AWS test account. Before changing resources, the command checks the address and confirms that your AWS credentials belong to that account. Use the function name, not an ARN. You must still confirm that the account and application are suitable for testing.

Before using the workflow:

  • Set up the AWS resources. API Gateway must send requests to the alias, and the previous Lambda version must still exist.
  • Control who can release. Allow only the intended branch to use the GitHub environment. Add reviewer approval if your plan supports it; an environment name alone does not require approval.
  • Limit AWS access. Configure the AWS role to trust only the intended repository and environment. Give it only the permissions the release needs. The id-token: write setting allows GitHub to request an identity token; it does not grant AWS permissions by itself.
  • Run one release at a time. Use the same concurrency group for releases to the same application. With cancel-in-progress: false, a new release will not cancel the one already running. A manual cancellation, timeout or network failure can still stop it.

Use GitHub's guides to connect to AWS with OIDC and control which jobs can run together for the full setup. Check how waiting jobs are handled; not every queued release is guaranteed to run.

5. Run the tests on your computer

The download includes the release script and 23 tests. They simulate AWS and application responses on your computer, so you do not need an AWS account, access keys or extra Python packages. Network connections are blocked while these tests run. Use Python 3.10 or later; these tests passed with Python 3.14.

The release code has been tested this way. It still needs testing in AWS before use with a real application.

Test results: 5 November 2026

All 23 automated tests passed with Python 3.14.6, using the files extracted from the downloadable ZIP. AWS and application responses were simulated. Network connections were blocked during the tests.

  • Checks pass: the script checks the new version, requests the switch, then checks the application.
  • A check fails before the switch: the script makes no request to change the running version.
  • A check fails after the switch: the script requests a return to the previous version and reports the release as failed.
  • Another release changes the version: a rejected update stops the script; it does not retry without the revision check.

These results check the script's decisions. They do not measure recovery time or prove that an application is working in AWS. Follow the AWS test steps below to check your own setup.

Download the rollback tests (.zip)

Review files before using them. Sample code and workflows are for learning and evaluation only. Run code in a separate test environment without production access. Read our download terms and safe-use guidance.

No email required. Read the README and terms inside the ZIP before running code. The test command below uses simulated responses; running the included release scripts directly can change AWS resources. Open a terminal in the folder where you saved the download, then run:

unzip lambda-rollback-tests.zip
cd lambda-rollback
python3 -B -m unittest -v test_release

The tests check what happens when:

  • All checks pass and the steps run in the right order.
  • The new version fails a check before the switch.
  • The application fails a check after the switch.
  • Someone else changes the alias during the release.
  • The alias is already splitting requests between versions.
  • The address or account details are wrong, or account confirmation is missing.
  • A response tries to redirect a request, change its path or return too much data.

This test checks that, after a failure, the script asks AWS to switch back to version 7:

    def test_gateway_failure_rolls_back_previous_version(self):
        with self.assertRaises(RuntimeError):
            self.run_release(Mock(side_effect=RuntimeError("gateway failed")))
        self.assertEqual(2, self.client.update_alias.call_count)
        self.client.update_alias.assert_called_with(
            FunctionName="operations", Name="live", FunctionVersion="7", RevisionId="alias-promoted")

You should see Ran 23 tests followed by OK. A message containing "event": "rollback" is expected: the test deliberately causes a failure and checks the recovery action. The -B option keeps Python from creating extra cache files.

To see the test catch a mistake, change its expected restored version from "7" to "8" and run it again. It should fail because the script requests version 7. Change the test back afterwards.

6. Test the setup in AWS before going live

The tests on your computer check what the script asks AWS to do. A separate AWS test must confirm that permissions work, requests reach the right version and the previous version can serve the application again.

Use a separate AWS test environment, agree its budget and keep a known working version available. Then check the following:

  1. Confirm the AWS role, function, region and application address. Check that requests without authentication fail and authenticated requests work.
  2. Release a working version. Check its version identifier through API Gateway.
  3. Try a version that deliberately fails a check before the switch. Confirm that the application keeps using the old version.
  4. Cause a controlled failure after the switch. Check that the alias points back to the previous version, then test that the application works.
  5. Practise recovery when the release job stops or someone else changes the alias. Check its current version and revision, switch to the approved version, then test the application.

This script tries to switch back after the first failed check through API Gateway. Temporary errors or a delay in the version switch could trigger that action too. Decide how long checks should wait and how many retries your application needs. If you want to move users gradually between versions, use a release approach designed for that and test it separately.

Make your next release easier to manage

The US$1,500 CI/CD Pipeline Setup covers one application and one repository, deploying to an existing AWS test environment. We agree what to check and how to recover before starting the work.

Discuss your pipeline setup, or use the release checklist to record the steps, who handles the release and what to do if it fails.