Sub topic 12
Rollbacks and feature flags
What you need before this chapter
This chapter assumes you have read the earlier chapters on pipelines, build artifacts, environments, and deployment strategies. You should be comfortable with a pipeline that builds an artifact once and deploys it to production. You should also be able to read a GitHub Actions workflow in YAML.
Why a release needs an undo
Tests and staging catch many defects, but not all of them. Some failures only appear under production traffic, with real data, or alongside other services. A team that deploys often will sometimes ship a bad change. What matters is how quickly the team limits the damage.
Two techniques cover most cases:
- A rollback returns production to a previously released version.
- A feature flag (also called a feature toggle) is a runtime switch that turns a code path on or off without a new deployment.
Rollbacks undo a deployment. Feature flags avoid having to undo one.
Rollbacks
Redeploy a known-good artifact
In an earlier chapter you built one artifact and promoted it through environments. That pays off here. Because the pipeline stored the artifact from every release, a rollback is a deployment of an older artifact. Nothing is rebuilt, so you ship the bytes that already ran in production before, not a new build that might differ.
The workflow below is a manual rollback for the ci-cd pipeline from this tutorial. A person starts it and supplies the ID of an earlier run. The ID is the number at the end of that run's URL in the Actions tab.
name: rollback
on:
workflow_dispatch:
inputs:
run_id:
description: ID of an earlier ci-cd run whose dist artifact should be redeployed
required: true
jobs:
rollback:
runs-on: ubuntu-latest
environment: production
permissions:
actions: read
contents: read
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: dist
path: dist/
run-id: ${{ inputs.run_id }}
github-token: ${{ secrets.GITHUB_TOKEN }}
- run: ./scripts/deploy.sh dist/A few details matter:
download-artifactnormally reads artifacts from the current run. Settingrun-idandgithub-tokenlets it fetch from another run, andactions: readpermits that.- The workflow checks out the current branch, so
scripts/deploy.shis today's version of the script. The artifact is old, but the deploy logic is not. - Artifacts expire. GitHub keeps them for 90 days by default, and your repository may be configured shorter. A rollback target that has been deleted is no target. Make sure retention covers the versions you might return to.
- The
productionenvironment still applies, so an approval rule would also gate the rollback. For urgent incidents, decide in advance who may approve it.
Some deployment strategies make rollback cheaper. With blue/green, the previous version is still running on the idle side, so rollback is a traffic switch that takes seconds. With a canary, rollback means sending the canary's share of traffic back to the stable version. With a rolling update, rollback is another rolling update in the opposite direction, which is slower.
When rollback does not work
Rolling back code is easy. Rolling back state is not. These are the usual failure modes:
- Database migrations. If version 5 renamed a column and wrote data in the new shape, version 4 may crash on it. Restoring the old code does not restore the old schema.
- Data already written. Records created or changed by the bad version stay changed after you roll back.
- External side effects. Emails sent, payments charged, and messages published to other systems cannot be recalled.
- Dependent services. If another service already began calling a new endpoint of yours, removing it breaks that caller.
The standard defense is the expand and contract pattern for schema changes. You split one risky change into steps that are each compatible with the version before and after:
- Expand: add the new column or table. Old code ignores it.
- Deploy code that writes to both old and new structures.
- Migrate existing data.
- Deploy code that reads only the new structure.
- Contract: remove the old column in a later release, once you are sure you will not roll back past it.
At every step, the previous application version still works against the current schema, so a rollback stays safe.
Rolling forward
Sometimes the right response to a bad release is a new release containing a fix. This is rolling forward. It makes sense when a rollback is unsafe (see above), when the fix is a one-line change, or when the pipeline is fast enough that a fix reaches production in minutes. It is a poor choice when you do not yet understand the failure. A team that guesses at fixes under pressure can make the incident worse. A common rule is to roll back first if that is safe, then fix calmly.
Feature flags
Separating deployment from release
A deployment puts code on production servers. A release makes a feature available to users. Without flags, the two happen together. With flags, you deploy code with the new behavior switched off, then release it later by changing a setting.
This supports several practices:
- Merging unfinished work to the main branch every day, hidden behind a flag, which keeps continuous integration honest.
- Releasing to a small group first, such as employees or 5% of users, then widening.
- Turning off a misbehaving feature in seconds. This is often faster than a rollback, and it leaves the rest of the release in place.
A small implementation
The Python example below reads a rollout percentage from an environment variable. It hashes the flag name together with the user ID, so each user lands in a stable bucket from 0 to 99. A user who sees the feature at 25% will still see it at 50%. Hashing the flag name too keeps different flags from selecting the same users every time.
import hashlib
import os
def is_enabled(flag: str, user_id: str) -> bool:
"""Return True if the flag is on for this user."""
percent = int(os.environ.get(f"FLAG_{flag.upper()}_PERCENT", "0"))
digest = hashlib.sha256(f"{flag}:{user_id}".encode()).hexdigest()
bucket = int(digest, 16) % 100
return bucket < percent
def checkout(user_id: str) -> str:
if is_enabled("new_checkout", user_id):
return "new checkout flow"
return "old checkout flow"
if __name__ == "__main__":
os.environ["FLAG_NEW_CHECKOUT_PERCENT"] = "25"
users = [f"user-{i}" for i in range(1000)]
on = sum(is_enabled("new_checkout", u) for u in users)
print(f"{on} of {len(users)} users get the new checkout")
print(checkout("user-1"))When the percentage is unset, it defaults to 0, so the feature is off. That default is deliberate. A flag system that cannot be reached should fall back to the safe, old behavior.
Reading an environment variable is only a starting point, because changing it needs a restart or redeploy. Production systems usually keep flags in a configuration service or a flag product that clients poll or stream from. Changes then take effect in seconds with no deployment.
Kinds of flags
| Kind | Purpose | Typical lifetime |
|---|---|---|
| Release flag | Hide unfinished or newly shipped work | Days to weeks |
| Experiment flag | Compare variants for a measurement such as A/B testing | Weeks |
| Ops flag (kill switch) | Disable a costly or risky feature during an incident | Long-lived |
| Permission flag | Give a feature to certain customers or plans | Long-lived |
Release and experiment flags should be temporary. Kill switches and permission flags are meant to stay.
The costs of flags
Flags are not free:
- Combinations multiply. Ten independent flags allow 1,024 states, and you test only a few of them. Keep flags independent and few.
- Stale flags rot. A release flag left in the code after full rollout is dead branching. Give every release flag an owner and a removal date, and delete the flag and the old path once the rollout is complete.
- Flags are production changes. Flipping one can break the site just as a deployment can. Record who changed what and when, and restrict who may change production flags.
- Both paths need tests. Run your automated tests with the flag on and off.
Choosing a response
The order reflects speed and blast radius. A flag flip is the quickest and affects only one feature. A rollback is slower and reverts everything in the release. A roll forward is the slowest, because it needs a new build, but it is sometimes the only option.
In all three cases, practice before you need it. A rollback workflow that has never run is untested code. Run it in staging on a schedule and time it. Also agree on the signal that triggers it, such as an error-rate threshold, so the decision during an incident is quick.
Summary of the trade-offs
- Rollbacks need no code changes ahead of time, but they cannot undo data changes and they revert the whole release.
- Flags give fine-grained, instant control, but they add code paths that you must test and clean up.
- Rolling forward handles cases where neither works, but it depends on a fast pipeline and a clear diagnosis.
Exercise
Version 12 of your service shipped a database migration that drops a column, and the same release added a new search feature that is failing. Why is redeploying version 11 risky, and what two things could you have done to make recovery safer?
Show answer
Version 11 still reads the dropped column, so it would likely fail against the migrated schema, and the data in that column is gone. Safer approaches: (1) split the migration with expand and contract, so the column is only dropped in a later release after rollback past it is no longer needed. (2) Put the new search feature behind a feature flag, so you could turn it off without redeploying. Rolling forward with a fix would be the fallback.
Exercise
A release flag called new_checkout reached 100% of users three months ago and nothing has gone wrong. What should you do with it, and why?
Show answer
Remove the flag and the old code path, and delete the flag from the flag system. A fully rolled-out release flag is dead branching. It adds untested combinations and confuses readers, and someone could switch it off by mistake.