Skip to content

7.11 — Feature Flags and Feature Management

← Roadmap · Section: 7. Configuration and Options Prev: 7.10 Custom providers · Next: 8.1 Endpoint routing

Markers: ⭐ · Confidence: 🔴 · Last reviewed: —


TL;DR

A feature flag is a switch that turns a piece of functionality on or off without redeploying.

  • It separates deploying code from releasing it — you can ship a feature turned off and enable it later.
  • Microsoft's Microsoft.FeatureManagement builds on configuration, so flags can come from appsettings.json or a remote store.
  • ⚠️ Flags are technical debt with a shelf life. Every one is a branch you must eventually delete.

Definitions

Term What it is What it means
Feature flag a runtime switch A boolean controlling whether functionality is active. Also called a feature toggle.
Microsoft.FeatureManagement a NuGet package Microsoft's feature flag library. Reads flags from configuration.
IFeatureManager an interface Asks whether a feature is enabled. IsEnabledAsync("Name").
IVariantFeatureManager an interface Returns a variant rather than a boolean. For A/B testing.
[FeatureGate] an attribute Puts a controller or action behind a flag. Returns 404 when disabled.
<feature> tag helper a Razor tag Shows or hides markup based on a flag.
Feature filter an IFeatureFilter Decides whether a flag is on, using rules — percentage, time window, user.
PercentageFilter a built-in filter Enables a feature for a percentage of evaluations.
TimeWindowFilter a built-in filter Enables a feature between two dates.
TargetingFilter a built-in filter Enables per user or group. The basis of a real rollout.
Kill switch a use case A flag whose only job is to disable something quickly during an incident.

The concept

Deploy is not release

Without flags, shipping a feature and turning it on are the same event. That forces all-or-nothing deployments: the code goes live for everyone at once, and if it misbehaves your only remedy is a rollback.

Feature flags separate the two:

  1. Deploy the code with the flag off. Nothing changes for users.
  2. Enable it for internal staff. Test in production, with real data.
  3. Enable for 5% of users. Watch the error rate.
  4. Ramp up to 100%.
  5. Delete the flag and the old code path.

If step 3 goes wrong, you turn the flag off. No deployment, no rollback, seconds not minutes.

A picture: a dimmer switch rather than a light switch. You can bring the new thing up gradually and take it back down instantly, without rewiring the room.

⚠️ The cost nobody mentions

Every flag adds a branch to your code, and branches multiply:

if (await features.IsEnabledAsync("NewCheckout"))
{
    if (await features.IsEnabledAsync("ExpressShipping"))    // 4 combinations
    { }
}

Three flags is eight paths. Most of them are never tested, and some are never reachable.

Flags are technical debt with a shelf life. A flag that has been at 100% for six months is not a flag — it is dead code plus an if statement. The discipline that makes flags work is deleting them, and it is the part teams skip.

Practical habits: record the date and owner when you add one, and treat a flag older than a release cycle or two as a bug.


How it works

The simple version

dotnet add package Microsoft.FeatureManagement.AspNetCore
// appsettings.json
{
  "FeatureManagement": {
    "NewCheckout": false,
    "BetaSearch": true
  }
}
builder.Services.AddFeatureManagement();
public class CheckoutService(IFeatureManager features)
{
    public async Task<Receipt> CheckoutAsync(Cart cart, CancellationToken ct)
    {
        if (await features.IsEnabledAsync("NewCheckout"))
            return await NewCheckoutAsync(cart, ct);

        return await LegacyCheckoutAsync(cart, ct);
    }
}

⚠️ Use constants, not string literals, or a typo silently disables the feature forever — IsEnabledAsync returns false for an unknown flag rather than throwing:

public static class FeatureFlags
{
    public const string NewCheckout = "NewCheckout";
    public const string BetaSearch  = "BetaSearch";
}

Gating an endpoint

[FeatureGate(FeatureFlags.NewCheckout)]
[HttpPost("checkout/v2")]
public async Task<IActionResult> CheckoutV2(CheckoutRequest request, CancellationToken ct)
{
    // ...
}

When the flag is off the action returns 404, as though it does not exist.

That is deliberate — a 404 leaks nothing. A 403 would tell a caller the endpoint exists but is disabled, which is information you may not want to give.

How it actually works — feature filters

A boolean in a file is the simplest case. Filters make a flag conditional:

{
  "FeatureManagement": {
    "NewCheckout": {
      "EnabledFor": [
        {
          "Name": "Percentage",
          "Parameters": { "Value": 10 }        // 10% of evaluations
        }
      ]
    },
    "BlackFridayBanner": {
      "EnabledFor": [
        {
          "Name": "TimeWindow",
          "Parameters": { "Start": "2026-11-27T00:00:00Z", "End": "2026-12-01T00:00:00Z" }
        }
      ]
    }
  }
}
builder.Services.AddFeatureManagement()
    .AddFeatureFilter<PercentageFilter>()
    .AddFeatureFilter<TimeWindowFilter>();

⚠️ PercentageFilter is evaluated per call, not per user. So one user hitting the page five times can get the feature on three of them and off on two — which is useless for a real rollout and actively confusing for the user.

For a real percentage rollout you need TargetingFilter, which hashes a stable user identifier so a given user consistently gets the same answer:

builder.Services.AddFeatureManagement()
    .WithTargeting<HttpContextTargetingContextAccessor>();
{
  "FeatureManagement": {
    "NewCheckout": {
      "EnabledFor": [{
        "Name": "Targeting",
        "Parameters": {
          "Audience": {
            "Users": [ "beta@example.com" ],           // always on for these
            "Groups": [ { "Name": "InternalStaff", "RolloutPercentage": 100 } ],
            "DefaultRolloutPercentage": 10             // 10% of everyone else
          }
        }
      }]
    }
  }
}

That distinction — per-call versus per-user — is the thing worth knowing, because PercentageFilter is the obvious-looking choice and the wrong one.

The deeper detail — where flags should live

Flags in appsettings.json have a problem: changing one requires a redeploy, which defeats the point.

Options, in increasing order of capability:

Source Change without deploy? Notes
appsettings.json ❌ Fine for permanent config, not for flags
A mounted ConfigMap ✅ Reloads on a kubelet interval (7.9)
Azure App Configuration ✅ Purpose-built, with a UI and push refresh
LaunchDarkly / Flagsmith ✅ Full platforms — audit, targeting, analytics
// Azure App Configuration with a refresh interval
builder.Configuration.AddAzureAppConfiguration(options =>
{
    options.Connect(connectionString)
           .UseFeatureFlags(flags => flags.SetRefreshInterval(TimeSpan.FromSeconds(30)));
});

⚠️ Whatever the source, flags rely on configuration reload — so all the limits from 7.9 apply. IFeatureManager reads the current configuration on each call, so it does see changes, but the underlying provider must actually be reloading.

Kill switches

The most valuable flag is often the simplest:

{ "FeatureManagement": { "EnableExpensiveReports": true } }
if (!await features.IsEnabledAsync(FeatureFlags.EnableExpensiveReports))
    return Results.Problem("Reporting is temporarily unavailable.", statusCode: 503);

During an incident, turning off one expensive feature can keep the rest of the application alive. That is a kill switch, and it is worth adding proactively to anything that hammers a shared database or a third-party API.

Unlike rollout flags, kill switches are permanent and should not be cleaned up.


Code

A realistic setup:

// Program.cs
builder.Services.AddFeatureManagement()
    .AddFeatureFilter<PercentageFilter>()
    .AddFeatureFilter<TimeWindowFilter>()
    .WithTargeting<HttpContextTargetingContextAccessor>();
public static class FeatureFlags
{
    // Rollout flags — DELETE these once they reach 100% and settle
    public const string NewCheckout = "NewCheckout";       // added 2026-08, owner: payments team

    // Kill switches — PERMANENT
    public const string EnableReports = "EnableReports";
    public const string EnableEmailNotifications = "EnableEmailNotifications";
}
public class CheckoutService(
    IFeatureManager features,
    ILogger<CheckoutService> logger)
{
    public async Task<Receipt> CheckoutAsync(Cart cart, CancellationToken ct)
    {
        var useNew = await features.IsEnabledAsync(FeatureFlags.NewCheckout);

        // Log which path ran — essential when comparing error rates during a rollout
        logger.LogInformation("Checkout using {Path} flow", useNew ? "new" : "legacy");

        return useNew
            ? await NewCheckoutAsync(cart, ct)
            : await LegacyCheckoutAsync(cart, ct);
    }
}

That logging line is worth including. During a percentage rollout, "is the new path producing more errors than the old one?" is the question you need answered, and you cannot answer it without knowing which path each request took.

// A kill switch, checked before doing expensive work
[HttpGet("reports/annual")]
public async Task<IActionResult> AnnualReport(CancellationToken ct)
{
    if (!await _features.IsEnabledAsync(FeatureFlags.EnableReports))
        return Problem("Reporting is temporarily unavailable.", statusCode: 503);

    return Ok(await _reports.GenerateAsync(ct));
}

Cleaning up

Once NewCheckout is at 100% and stable:

// Before
var useNew = await features.IsEnabledAsync(FeatureFlags.NewCheckout);
return useNew ? await NewCheckoutAsync(cart, ct) : await LegacyCheckoutAsync(cart, ct);

// After — flag gone, legacy method deleted, constant removed, config entry removed
return await CheckoutAsync(cart, ct);

Four things to delete, and teams routinely do only the first. A leftover config entry and an unused constant are harmless; a leftover legacy method is dead code that someone will eventually try to maintain.


Interview questions

Q: What is a feature flag and why use one?

A runtime switch that turns functionality on or off without redeploying. The value is that it separates deploying code from releasing it — you can ship a feature turned off, enable it for internal users, then for a small percentage of real users while watching error rates, and ramp up from there. If something goes wrong you turn it off in seconds rather than rolling back a deployment. It also gives you kill switches, so during an incident you can disable one expensive feature to keep the rest of the application alive.

Q: What is the cost of feature flags?

Every flag is a branch, and branches multiply — three flags is eight code paths, most of which are never tested and some of which are unreachable. So flags are technical debt with a shelf life: a flag that has been at 100% for six months is not a flag, it is dead code plus an if statement. The discipline that makes them work is deleting them once they have settled, including the old code path, the constant and the configuration entry — and that is the part teams skip.

Q: What is wrong with PercentageFilter for a gradual rollout?

It evaluates per call rather than per user, so a single user refreshing a page can get the feature on some requests and off on others. That is useless for measuring a rollout and confusing for the user. For a real percentage rollout you want TargetingFilter, which hashes a stable user identifier so a given user consistently gets the same answer, and which also supports always-on lists for specific users and groups alongside a default rollout percentage.

Q: Where should feature flags be stored?

Not in appsettings.json for anything you want to change quickly, because changing it means a redeploy, which defeats the purpose. A mounted ConfigMap works and reloads on the kubelet sync interval. A purpose-built store like Azure App Configuration or LaunchDarkly is better, because it gives you a UI for non-developers, an audit trail of who changed what, and push-based refresh. Whatever the source, flags depend on configuration reloading, so all the usual reload limits apply.


Traps ⚠️

  • An unknown flag name returns false, so a typo silently disables the feature forever. Use constants.
  • PercentageFilter is per call, not per user. Use TargetingFilter for real rollouts.
  • Flags in appsettings.json need a redeploy to change, which defeats the point.
  • Flags multiply code paths. Three flags is eight combinations, mostly untested.
  • Old flags become dead code. Record the owner and date, and delete on a schedule.
  • [FeatureGate] returns 404, not 403 — deliberately, so it leaks nothing.
  • Cleanup means four deletions: the branch, the old method, the constant, the config entry.
  • Flags depend on configuration reload, so all of 7.9 applies.
  • Not logging which path ran makes a rollout impossible to evaluate.


Sources