📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do feature flags work in .NET with Microsoft.FeatureManagement and Azure App Configuration? Explain how they separate deployment from release, the kinds of flags, targeting and percentage rollouts, and how you stop them turning into technical debt.

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.

Mid-Level Theory Intermediate azure-app-configuration ci-cd devops feature-flags feature-management progressive-delivery

🎯 Key points

  • Deploy puts code in production; release exposes it to users; flags decouple the two
  • Microsoft.FeatureManagement: IFeatureManager / IVariantFeatureManager, [FeatureGate], feature filters
  • Built-in filters: Percentage, TimeWindow, Targeting (users, groups, rollout percentage)
  • Azure App Configuration stores flags centrally; refresh via middleware or provider without redeploying
  • Flag types: release (short-lived), ops kill switch (long-lived), experiment, permission
  • Targeting needs a stable user id so a user sees the same variant every time
  • Every release flag gets an owner and removal date; test both states
  • Flags are not access control; never gate security or data access on a client-visible flag alone

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 with AddFeatureManagement(), check flags with IFeatureManager or the variant-aware IVariantFeatureManager, and gate whole endpoints or controllers with [FeatureGate] or WithFeatureGate style filters. The interesting part is feature filters: the Targeting filter takes a user id and groups from an ITargetingContextAccessor and 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 an az command, 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."


Kinds of flags

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

Built-in filters

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.

Where flags live

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

Production example

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%.

🔍 What the interviewer is checking

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

  • Explains deploy vs release and progressive rollout with a kill switch
  • Knows Targeting vs Percentage and why stickiness matters
  • Uses App Configuration with managed identity and refresh, with defaults if it is down
  • Has a concrete flag clean-up process

Red flags

  • Uses flags for authorisation or security
  • Has no plan to remove flags
  • Thinks flags remove the need for testing

📚 Learn in depth

1. How evaluation works

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.

2. Configuration schema

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.

3. Refresh from App Configuration

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.
  • If App Configuration is unreachable, the provider keeps the last values; at start-up use optional: true (or a startup timeout) and sensible defaults in appsettings.json so the app still starts.
  • Store flags in Australia East with geo-replication to Southeast if your data residency policy requires it, and use labels for environments (dev, prod).

4. Variants and experiments

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.

5. Testing with flags

  • Unit tests: inject a fake IFeatureManager or use in-memory configuration.
  • Integration tests: WebApplicationFactory with configuration overrides to run each test in both states.
  • Avoid combinatorial explosion: flags should be independent; if two flags depend on each other, that's a design smell.

6. Lifecycle

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.

Try it yourself

  1. Add Microsoft.FeatureManagement.AspNetCore, define a flag in appsettings.json, and gate an endpoint.
  2. Implement ITargetingContextAccessor from HttpContext.User and roll out to 20%; call the endpoint as 100 different users and count how many get it.
  3. Connect to Azure App Configuration with DefaultAzureCredential, toggle the flag in the portal and measure how long the app takes to notice.
  4. Write an integration test that runs once with the flag on and once off.
  5. Stop App Configuration access (remove the role assignment) and confirm the app still starts with defaults.

💻 Code

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

⚠ Common mistakes

  • Mistake: Using the 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.
  • Mistake: Creating flags with no owner. Why it is wrong: When the feature ships, nobody feels responsible for removing the flag, and after a reorganisation nobody even knows what it does. Instead: Record an owner team and removal date with every flag (App Configuration tags or a description field) and review the flag list in sprint planning.
  • Mistake: Never removing release flags. Why it is wrong: Dead branches and untested combinations pile up and old flags get flipped by accident. Instead: Create the removal ticket in the same PR that adds the flag, and alert when a flag has been 100% on for 30 days.
  • Mistake: Removing a long-lived flag in one go. Why it is wrong: Deleting the flag in App Configuration before the code stops reading it changes behaviour (the missing flag evaluates as off). Instead: Remove the code checks and the old path first, deploy, then delete the flag definition.
  • Mistake: Treating flags as security controls. Why it is wrong: A misconfigured flag or a client-side check exposes data. Instead: Use authorisation policies for access; flags only decide which code path runs.
  • Mistake: Connecting to App Configuration with a connection string containing an access key. Why it is wrong: It is a long-lived secret. Instead: Use managed identity with the App Configuration Data Reader role and disable local auth.
  • Mistake: Making start-up depend on App Configuration being reachable. Why it is wrong: An outage of the flag store becomes an outage of your app. Instead: Use optional: true or a startup timeout plus safe defaults in appsettings.json.
  • Mistake: Testing only the flag-off path. Why it is wrong: The new path ships untested and fails when switched on. Instead: Run integration tests in both states.
  • Mistake: Nesting flags that depend on each other. Why it is wrong: Combinations explode and some are never tested. Instead: Keep flags independent and short-lived.
  • Mistake: Putting long-term plan entitlements in feature flags. Why it is wrong: Business rules end up in config nobody owns. Instead: Model entitlements in the domain and keep flags for rollout.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says flags let unfinished code merge to main. Why: Checks that the candidate links flags to the branching model they make possible.
    How to answer

    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.

  2. When: Candidate mentions Azure App Configuration. Why: Checks wider knowledge of App Configuration and Key Vault in ASP.NET Core configuration.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Kill switch saved a release when a payment provider slowed down
Situation
A .NET 10 checkout service on Container Apps in Australia East, [about 2,000 orders per hour], rolling out a new payment integration behind a Targeting flag at 25% of customers.
Signals
Application Insights alert: p95 checkout latency up from [800 ms to 3.5 s] for requests where the custom dimension `FeatureFlag.NewCheckout=true`; payment provider dependency calls timing out; a rise in abandoned carts in the business dashboard.
Investigation
Split latency by flag variant in Application Insights (KQL `summarize percentile(duration, 95) by tostring(customDimensions.Variant)`), confirmed only the new path was affected, checked the dependency map and the provider's status page.
Resolution
Immediate: disabled `NewCheckout` in App Configuration with `az appconfig feature disable`; all instances picked it up within 30 seconds and latency returned to normal. Long term: added a timeout and circuit breaker to the new provider client and resumed the rollout at 5% after the provider fixed its issue.
Prevention
Flag evaluations logged as telemetry with the variant; an alert comparing error rate and latency by variant; a runbook entry for the kill switch; a flag-age report with removal tickets.

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.

↩ Usually asked after

More in CI/CD

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me