How Feature Flags Enable Safe Continuous Deployment

How feature flags make continuous deployment safe: deploy vs release, trunk-based development, testing flag paths, expand-contract migrations, runbooks.

Aug 15, 2025 - 15:04
Nov 6, 2026 - 11:48
 0  98
How Feature Flags Enable Safe Continuous Deployment

Feature flags make continuous deployment safe by separating deploying code from releasing it. Every merge can go to production with new code switched off, then the team turns it on for a small group, watches metrics, and widens or switches it off in seconds without a new build or rollback.

This post looks at the engineering side: how flags change your branching, pipeline, tests, database changes and incident response when you deploy many times a day. For the release strategy view (canaries, targeting, experiments) read why feature flags are essential for progressive delivery. For choosing a product, see the best feature flag tools. Both sit under our CI/CD pillar guide.

Key takeaways

  • Continuous deployment means every change that passes the pipeline goes to production automatically. Flags let unfinished or risky work ship dark.
  • Flags make trunk-based development practical: short-lived branches merge daily behind a flag instead of waiting weeks in a feature branch.
  • Test both states of every flag that is live, and keep the number of live flags small so the combinations stay testable.
  • Pair flags with expand-and-contract database changes. A flag cannot undo a destructive migration.
  • Give every release flag an owner and a removal date. Flag cleanup is part of done.
  • Flags do not replace rollbacks or canaries. They cover feature risk; deployment strategies cover infrastructure and build risk.

Continuous delivery vs continuous deployment

The two terms are often mixed up, and the difference is why flags matter.

Continuous deliveryContinuous deployment
Every change is releasableYesYes
Production deployTriggered by a personAutomatic after the pipeline passes
Who decides users see a featureUsually the deploy itselfNeeds a separate control, typically a flag
Main riskLarge, infrequent releasesUnfinished work reaching users

Once a human no longer approves each deploy, you need another way to stop half-built features from being visible. Feature flags are that way.

What "deploy" and "release" mean with flags

  • Deploy: a new build runs in production. With continuous deployment, this happens many times a day and is routine.
  • Release: users can use a feature. With flags, this is a configuration change made when the business and the metrics are ready.

Separating them shrinks each deploy (fewer changes, easier to diagnose) and makes release reversible without touching the pipeline.

How flags change the development workflow

Trunk-based development

Long-lived feature branches are the enemy of continuous deployment: they merge late, conflict often and hide integration bugs. With flags, a developer merges small changes to main every day. Code for a feature that is not finished is wrapped in a flag that is off in production. The DORA research program lists trunk-based development as one of the capabilities associated with better delivery performance. Our Git strategies for large teams compares branching models.

Wrapping code in a flag

Keep the decision in one place and pass a user context so targeting works. With the vendor-neutral OpenFeature API in Python:

from openfeature import api
from openfeature.evaluation_context import EvaluationContext

client = api.get_client()

def checkout(user, cart):
    ctx = EvaluationContext(targeting_key=user.id, attributes={"plan": user.plan})
    if client.get_boolean_value("new-checkout-flow", False, ctx):
        return new_checkout(user, cart)
    return legacy_checkout(user, cart)

The default value (False) is what users get if the flag service is unreachable. Choose defaults so that a failure falls back to the known, safe path.

Kinds of flags in a CD pipeline

TypePurposeLifetimeWho changes it
Release toggleHide unfinished work, then roll outDays to weeksEngineering
Ops toggle / kill switchTurn off an expensive or failing feature fastLong-livedOn-call, SRE
Experiment toggleA/B test variantsLength of the experimentProduct, data
Permission toggleEnable features for plans or customersLong-livedProduct

This classification comes from Pete Hodgson's article on feature toggles, published on Martin Fowler's site, and it helps decide how strictly each type needs to be managed.

Flags inside the pipeline

Testing both paths

A flag doubles the paths through the code it wraps. Test the code with the flag on and off in CI. OpenFeature providers and most SDKs have an in-memory or test provider for this:

import pytest
from openfeature import api
from openfeature.provider.in_memory_provider import InMemoryProvider, InMemoryFlag

@pytest.mark.parametrize("enabled", [True, False])
def test_checkout_both_paths(enabled):
    api.set_provider(InMemoryProvider({
        "new-checkout-flow": InMemoryFlag("on" if enabled else "off",
                                          {"on": True, "off": False})
    }))
    result = checkout(make_user(), make_cart())
    assert result.status == "ok"

Do not try to test every combination of every flag. Test each live flag in both states with the others at their production values, and limit how many release toggles are live at once.

Flag configuration as code

Flag changes are production changes. Many teams keep flag definitions in Git and sync them to the flag service through Terraform providers or the tool's API, so changes get review and an audit trail. For self-hosted flags, flagd reads definitions from a file or Kubernetes custom resource:

{
  "flags": {
    "new-checkout-flow": {
      "state": "ENABLED",
      "variants": { "on": true, "off": false },
      "defaultVariant": "off",
      "targeting": {
        "fractional": [
          { "var": "targetingKey" },
          ["on", 5],
          ["off", 95]
        ]
      }
    }
  }
}

Here 5% of users, bucketed consistently by their targeting key, see the new flow. Check the flagd documentation for the exact targeting syntax of your version.

Approval for flag changes, not deploys

With continuous deployment, the approval point moves from "can we deploy?" to "can we release to more users?". Put approvals and change records on production flag changes for high-risk features. Our post on approval gates in CI/CD covers where these fit.

A safe release runbook with flags

  1. Merge behind a flag that is off. The pipeline deploys to production. Nothing changes for users.
  2. Turn on for internal users. Target employees or a test tenant. Check logs, errors and traces for the new path.
  3. Roll out to a small percentage. Start at 1 to 5%. Compare error rate, latency and business metrics between flag on and flag off.
  4. Widen in steps. 10%, 25%, 50%, 100%, with a pause long enough at each step to see a full traffic cycle.
  5. Switch off on any regression. The kill switch is the flag itself. No rollback, no redeploy.
  6. Remove the flag. Once at 100% and stable, delete the old code path and the flag in a normal pull request.

To compare cohorts you need the flag state in your telemetry. Add the evaluated variant as an attribute on spans or log lines. OpenTelemetry has semantic conventions for feature flag evaluations, and OpenFeature hooks can add them automatically.

Database changes: where flags stop helping

Turning a flag off reverts code, not data. If the new code path depends on a migration that drops or renames a column, switching the flag off will break the old path. Use expand and contract:

  1. Expand: add the new column or table. Old code ignores it. Deploy.
  2. Dual write: write to both old and new structures; backfill existing rows.
  3. Switch reads behind a flag: the flag chooses which structure to read. Both paths keep working, so the flag stays reversible.
  4. Contract: after the flag is at 100% and removed, drop the old column in a later deploy.

This keeps every deploy backward compatible, which also makes ordinary rollbacks safe.

Flags vs deployment strategies

RiskBetter handled byWhy
A new feature behaves badly for usersFeature flagSwitch off per feature in seconds
A new build crashes on start or leaks memoryCanary or blue-green deployment, rollbackThe problem is in the artefact, not one feature
A dependency or config change breaks everythingCanary with automated analysisFlags do not wrap infrastructure
Testing a variant against a controlExperiment flagConsistent user bucketing and metrics

Most teams use both. See CI/CD rollout types explained for canary and blue-green details, and shadow deployments for testing with mirrored traffic.

Risks and how to keep flags under control

  • Flag debt. Old flags pile up and make code hard to read. Set an expiry date when you create a release flag, and fail a CI check or open a ticket when it passes. Many flag platforms report stale flags.
  • Accidental exposure. A wrong targeting rule can release to everyone. Require review on production flag changes and keep an audit log.
  • Performance. Evaluating flags with a network call per request adds latency. Use SDKs that cache rules locally and evaluate in process, or a sidecar such as flagd.
  • Hidden coupling. Flags that depend on other flags multiply states. Avoid nesting; if two flags must change together, make them one.
  • Security. Flags are not access control for sensitive features on their own. Enforce authorisation in the backend too, and never ship secrets in client-side flag payloads.
  • Old repeated flag names. Reusing a retired flag's name can switch on dead code. Delete code and flag together, and do not recycle names.

Where flags are evaluated

Where the on or off decision happens affects speed, safety and what users can see.

ModelHow it worksGood forWatch out for
Server-side, in processThe SDK downloads rules and evaluates locally on each requestBackend services, low latencyRule updates arrive by streaming or polling, so changes take seconds, not zero time
Server-side, remoteEach evaluation calls a flag service or sidecarSimple setups, polyglot estates with a local sidecarLatency and an extra dependency in the request path
Client-sideThe browser or mobile app gets evaluated values for one userUI changesAnything in the payload is visible to the user; mobile apps keep old versions for months

Mobile apps need extra care. A flag that guards new client code only helps for app versions that contain the code, and users may not update for a long time. Keep server-side checks for anything that must be enforced, and plan for old app versions that will never see the flag.

Flags during an incident

Flags change incident response in useful ways, provided the on-call engineer knows they exist.

  • List kill switches in the service runbook with what each one turns off and the expected side effects.
  • Give on-call engineers permission to change ops toggles in production without waiting for an approval, while still logging the change.
  • Post flag changes to the incident channel automatically, so everyone sees the timeline. Most platforms support webhooks or chat integrations.
  • When looking for the cause of a regression, check recent flag changes alongside recent deploys. A flag change is a release even though no pipeline ran.

Our post-deployment validation steps apply to flag releases too: run the same checks after widening a rollout as after a deploy.

Making flag cleanup part of the pipeline

Cleanup is easier when the pipeline nags about it. A simple pattern is to register every release flag with an owner and an expiry date in a file in the repository, then fail or warn in CI once the date has passed.

# flags.yaml
- key: new-checkout-flow
  type: release
  owner: payments-team
  expires: 2027-01-31
- key: disable-recommendations
  type: ops
  owner: sre
  expires: never
#!/usr/bin/env bash
set -euo pipefail
today=$(date -u +%Y-%m-%d)
yq -r '.[] | select(.expires != "never") | [.key, .expires, .owner] | @tsv' flags.yaml |
while IFS=$'\t' read -r key expires owner; do
  if [[ "$expires" < "$today" ]]; then
    echo "::warning::Flag $key expired on $expires (owner: $owner)"
  fi
done

The script uses the Go-based yq and prints a GitHub Actions warning annotation; adapt the output for your CI system. Searching the codebase for the flag key (grep -rn 'new-checkout-flow' src/) shows every place to remove when the flag retires.

Build your own or adopt a platform?

A config file and an if statement work for a handful of flags. Once you need percentage rollouts with consistent bucketing, targeting rules, audit logs, approvals and change notifications, a dedicated system pays off. Coding against OpenFeature keeps the choice open: you can start with a self-hosted provider such as flagd and move to a commercial service later without rewriting flag checks.

Metrics that show it is working

The DORA metrics are a good check: deployment frequency and lead time should rise because merges are smaller, while change failure rate and failed deployment recovery time should fall because feature problems are switched off rather than rolled back. Our list of key DevOps metrics explains how to measure them.

Learn the full CD workflow

Trunk-based development, pipelines, deployment strategies and release practices are part of our DevOps training in Pune, offered in the Kharadi classroom and live online.

Frequently asked questions

How do feature flags enable safe continuous deployment?

They separate deploying code from releasing features. Code ships to production with the flag off, then the team enables it gradually and can switch it off instantly if metrics get worse, without a rollback or new deploy.

What is the difference between deploying and releasing?

Deploying puts a new build into production. Releasing makes a feature available to users. With flags, deploys can happen many times a day while releases are controlled separately per feature.

Do feature flags replace rollbacks?

No. Flags handle feature-level problems. A build that crashes, leaks memory or has a bad config still needs a rollback, canary or blue-green deployment.

How do you test code that uses feature flags?

Run tests with each live flag both on and off, using an in-memory or test provider from your flag SDK. Keep the number of live release flags small so the combinations stay manageable.

How do feature flags work with database migrations?

Use expand and contract: add new structures first, write to both, switch reads behind a flag, and remove old structures only after the flag is fully rolled out and deleted. A flag cannot undo a destructive migration.

What is a kill switch flag?

A long-lived operational flag that turns off a feature or dependency quickly during an incident, for example disabling recommendations when the recommendation service is slow.

How do you avoid feature flag technical debt?

Give each release flag an owner and an expiry date, track stale flags, and treat removing the flag and the old code path as part of finishing the feature.

Is trunk-based development required for feature flags?

Not required, but they work best together. Flags let developers merge unfinished work to the main branch safely, which is what keeps trunk-based development and continuous deployment practical.

References

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.