Feature flags in .NET: Microsoft.FeatureManagement, Azure App Configuration, release vs ops vs experiment flags, filters and targeting, variants, refresh, testing and flag clean-up.
A feature flag is a run-time switch around a code path. It lets you deploy code to production with the feature off and release it later by changing configuration, to a percentage of users or a group first.
In .NET, Microsoft.FeatureManagement gives you IFeatureManager.IsEnabledAsync, [FeatureGate] for endpoints, and feature filters: Percentage, TimeWindow and Targeting (users, groups, rollout percentage), plus variants for experiments. Azure App Configuration stores the flags centrally and the app refreshes them without a redeploy, using managed identity to connect.
The trade-off: flags make releases safe and reversible, but every flag doubles the paths to test. Release flags must have an owner and a removal date; only kill switches should live long.
"The point of a feature flag is to separate deploying code from releasing a feature. Deploying is a technical event: new bits are running in production. Releasing is a business event: users can see the feature. With a flag, I can merge and deploy daily, keep the feature dark, then turn it on for internal staff, then 10% of customers, then everyone, and turn it off in seconds if something goes wrong, without a rollback.
In .NET I use
Microsoft.FeatureManagement. I register it withAddFeatureManagement(), check flags withIFeatureManageror the variant-awareIVariantFeatureManager, and gate whole endpoints or controllers with[FeatureGate]orWithFeatureGatestyle filters. The interesting part is feature filters: the Targeting filter takes a user id and groups from anITargetingContextAccessorand decides consistently, so the same customer always gets the same answer, which matters for a percentage rollout. The flags live in Azure App Configuration, which the app reads using its managed identity, and the App Configuration middleware refreshes them on a sentinel key change, so turning a feature off is a portal click or anazcommand, not a deployment. For example, at [company] we [rolled out a new pricing engine to 5% of customers and turned it off within a minute when error rates rose].The mistake I see is flags that never die. Two years later there are 80 of them, nobody knows which combinations are tested, and someone flips an old one and breaks checkout. So I treat release flags as temporary: an owner, a removal ticket created with the flag, and an alert when a flag has been 100% on for 30 days. Kill switches for risky dependencies are the only flags I expect to keep."
| Type | Purpose | Lifetime | Example |
|---|---|---|---|
| Release | Hide unfinished or unreleased work | Days to weeks | NewCheckout |
| Ops / kill switch | Turn off an expensive or risky path under load | Long-lived | UseRecommendationService |
| Experiment | A/B test with variants and metrics | Weeks | PricingPageLayout (A/B) |
| Permission / entitlement | Plan-based features | Permanent, often better in the domain model | AdvancedReports for premium tenants |
| Filter | What it does |
|---|---|
Microsoft.Percentage |
On for N% of evaluations (random each time, not sticky) |
Microsoft.TimeWindow |
On between start and end times (with recurrence) |
Microsoft.Targeting |
On for listed users/groups, plus a sticky percentage of everyone else; supports exclusions |
Use Targeting rather than Percentage for user-facing rollouts, because Percentage can flip between requests for the same user.
| Store | Good for | Limits |
|---|---|---|
appsettings.json |
Defaults, local development, tests | Changing needs a redeploy or restart |
| Azure App Configuration | Central, per-environment labels, refresh, portal UI, telemetry | Extra dependency; plan for its outage (cache + defaults) |
| Third-party (LaunchDarkly, Unleash, Flagsmith) | Rich experimentation, many platforms | Cost, data residency review |
A team released a rewritten payment flow behind a Targeting flag: staff for a week, then 5%, 25% and 100% over ten days. At 25%, the payment provider's latency doubled; the on-call engineer turned the flag off in App Configuration and the app picked it up within 30 seconds, with no deployment. The flag and the old code path were deleted three weeks after reaching 100%.
Checks whether the candidate uses flags to separate deploy from release safely, knows the .NET tooling and its failure modes, and manages flag debt.
Green flags
Red flags
request ─► IFeatureManager.IsEnabledAsync("NewCheckout")
│
├─ read flag definition (IConfiguration ◄─ App Configuration provider, cached)
├─ enabled = false? ──► false
└─ for each client filter:
Targeting: ITargetingContextAccessor ─► { UserId, Groups }
├─ user excluded? ──► false
├─ user or group listed? ──► true
└─ hash(flag + userId) % 100 < DefaultRolloutPercentage ──► true/false
The hash makes the decision deterministic per user: the same user gets the same answer on every instance, without storing anything.
Version 4 of the libraries reads the feature_management section in the Microsoft Feature Flag schema (feature_flags array with id, enabled, conditions.client_filters, variants, allocation), the same shape App Configuration uses. The older FeatureManagement section with flag names as keys still works.
App Configuration ──(managed identity)──► provider in IConfiguration
▲ │
│ every request, middleware checks │ flags cached
│ "is refresh interval elapsed?" ▼
└──────── refresh feature flags (default 30 s) ── IFeatureManager sees new values
UseFeatureFlags(o => o.SetRefreshInterval(...)) controls the cache interval for flags.app.UseAzureAppConfiguration() triggers refresh on requests; in workers, call IConfigurationRefresher.TryRefreshAsync() yourself.optional: true (or a startup timeout) and sensible defaults in appsettings.json so the app still starts.dev, prod).IVariantFeatureManager.GetVariantAsync("PricingPageLayout") returns a variant (for example A or B) allocated by user, group or percentile. With App Configuration and Application Insights, the evaluation events carry the variant so you can compare conversion between variants.
IFeatureManager or use in-memory configuration.WebApplicationFactory with configuration overrides to run each test in both states.create flag + removal ticket ─► dark in prod ─► staff ─► 5% ─► 25% ─► 100%
│ 30 days stable
▼
delete flag checks and old path ─► delete flag
A simple guard: a scheduled job or analyser that lists flags referenced in code and compares them with App Configuration, reporting flags that are 100% on for more than 30 days or defined but unused.
Microsoft.FeatureManagement.AspNetCore, define a flag in appsettings.json, and gate an endpoint.ITargetingContextAccessor from HttpContext.User and roll out to 20%; call the endpoint as 100 different users and count how many get it.DefaultAzureCredential, toggle the flag in the portal and measure how long the app takes to notice.Flags from Azure App Configuration with managed identity, targeting by user, and a gated endpoint (Program.cs):
using System.Security.Claims;
using Azure.Identity;
using Microsoft.FeatureManagement;
using Microsoft.FeatureManagement.FeatureFilters;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(builder.Configuration["AppConfig:Endpoint"]!), new DefaultAzureCredential())
.Select("Orders:*", labelFilter: builder.Environment.EnvironmentName)
.UseFeatureFlags(flags =>
{
flags.Label = builder.Environment.EnvironmentName;
flags.SetRefreshInterval(TimeSpan.FromSeconds(30)); // how quickly a kill switch takes effect
});
}, optional: true); // the app still starts on appsettings defaults if App Configuration is down
builder.Services.AddAzureAppConfiguration();
builder.Services.AddHttpContextAccessor();
builder.Services.AddFeatureManagement()
.WithTargeting<UserTargetingContextAccessor>(); // sticky per-user rollout
var app = builder.Build();
app.UseAzureAppConfiguration(); // refreshes flags as requests arrive
app.MapPost("/checkout", async (IFeatureManager features, CancellationToken ct) =>
await features.IsEnabledAsync("NewCheckout", ct)
? Results.Ok(new CheckoutResult("v2"))
: Results.Ok(new CheckoutResult("v1")));
app.Run();
public sealed record CheckoutResult(string Engine);
// Gives the Targeting filter a stable user id and groups.
public sealed class UserTargetingContextAccessor(IHttpContextAccessor http) : ITargetingContextAccessor
{
public ValueTask<TargetingContext> GetContextAsync()
{
var user = http.HttpContext?.User;
return ValueTask.FromResult(new TargetingContext
{
UserId = user?.FindFirstValue(ClaimTypes.NameIdentifier) ?? "anonymous",
Groups = user?.FindAll("groups").Select(c => c.Value).ToList() ?? []
});
}
}
The flag as stored (Microsoft Feature Flag schema):
{
"feature_management": {
"feature_flags": [
{
"id": "NewCheckout",
"enabled": true,
"conditions": {
"client_filters": [
{
"name": "Microsoft.Targeting",
"parameters": {
"Audience": {
"Users": ["[email protected]"],
"Groups": [{ "Name": "staff", "RolloutPercentage": 100 }],
"DefaultRolloutPercentage": 5,
"Exclusion": { "Users": [], "Groups": ["enterprise-tenants"] }
}
}
}
]
}
}
]
}
}
# Kill switch during an incident: no deployment needed
az appconfig feature disable --endpoint https://appcs-orders-aue.azconfig.io --auth-mode login \
--feature NewCheckout --label Production --yes
Percentage filter for user-facing rollouts. Why it is wrong: It is evaluated randomly each time, so a user can flip between old and new UI. Instead: Use the Targeting filter with a stable user id.App Configuration Data Reader role and disable local auth.optional: true or a startup timeout plus safe defaults in appsettings.json.Flags are a release tool and a risk tool, and they have a carrying cost. I count them like debt: each release flag is borrowed complexity that must be paid back. The healthiest teams I've seen have a handful of active release flags per service, a few permanent kill switches, a named owner on every flag, and a dashboard showing flag age.
Testing is where flag debt really bites. Each active flag doubles the paths through the code, so I keep the rule simple: the CI suite runs the integration tests with each active release flag both on and off (via WebApplicationFactory configuration overrides), and the production configuration is the one tested in staging before a flag is widened. Flags that are independent keep that matrix linear rather than exponential.
The other senior point is failure modes: the flag store is now in your critical path. Cache, defaults and a tested "App Configuration is down" path matter as much as the flags themselves. And for regulated Australian workloads, check where the flag service stores user identifiers used for targeting: App Configuration in Australia East keeps them in-region; a SaaS flag vendor may not.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
appsettings flags |
Simple dark launches, tests | Needs restart/redeploy to change | Kill switches you need in seconds |
| App Configuration + FeatureManagement | Azure-hosted .NET services | Small monthly cost, one more dependency | Multi-platform product needing rich experiments |
| Third-party flag platform | Many languages, product-led experiments | Licence cost, data residency review | A single .NET service with simple needs |
| No flag (just deploy) | Tiny, low-risk changes | None | Risky or long-running features |
Git Flow keeps two long-lived branches, main (released code) and develop (next release), plus feature/*, release/* and hotfix/* branches that merge back in a set order. Trunk-based development has one long-lived branch, main; developers branch for hours or a day or two, open a small pull request and merge behind CI checks, using feature flags to hide unfinished work.
Most teams moved to trunk-based because long-lived branches delay integration: the longer a branch lives, the bigger the merge and the later you find that two changes conflict. Short branches keep main always releasable, which is what continuous delivery needs.
The trade-off: trunk-based asks for good automated tests and flag discipline; Git Flow still suits products that ship numbered versions and patch several releases at once.
I'd inventory and classify every setting first: secrets, environment-specific values, shared values, and which must change live. Secrets go to Key Vault. Non-secret settings and feature flags go to Azure App Configuration with a label per environment, and secrets are referenced from there through Key Vault references. The app authenticates with its managed identity using least-privilege roles, and where possible secrets disappear entirely through passwordless Entra ID auth to SQL, Storage and Service Bus.
For refresh, use a sentinel key with a refresh interval and a secret refresh interval, and read live values through IOptionsMonitor. Rotation uses overlapping versions, so old and new both work during the window. Add start-up timeouts and replicas, and keep ValidateOnStart.
The trade-off: central, audited, rotatable configuration, in exchange for a network dependency at start-up that you must design for.
How to tell it (STAR)
**S:** We were rolling out a new payment integration to a quarter of customers behind a feature flag. **T:** During the rollout, checkout latency spiked and I had to protect revenue fast. **A:** I split the telemetry by flag variant, saw only the new path was slow because the provider was timing out, and turned the flag off in App Configuration instead of rolling back; then I added a timeout and circuit breaker before restarting the rollout at 5%. **R:** Customers were back on the old path within [about a minute], we avoided a [roughly 30-minute] redeploy, and the full rollout finished [two weeks later] with no further incidents.
Last updated 23 Nov 2026.