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

📚 Interview question

You set a configuration value in Azure App Service (or a Kubernetes deployment), but the running app still uses the value from appsettings.json. Possible causes include environment variable naming, provider precedence and reloadOnChange with mounted files. How do you diagnose and fix it?

Diagnosing configuration values that don't take effect in Azure App Service, Container Apps or Kubernetes: environment variable naming (: versus __, ConfigMap key rules, App Service connection string prefixes), provider order and custom sources added last, the wrong environment name, values read once at start-up, mounted ConfigMap symlink swaps and DOTNET_USE_POLLING_FILE_WATCHER, and using GetDebugView with masking, the provider list, printenv and az CLI to find which provider won.

Mid-Level Debugging Intermediate aspnet-core azure-app-service configuration debugging environment-variables kubernetes

🎯 Key points

  • First prove what the process sees: GetDebugView (masked) or the provider list, plus printenv inside the container or Kudu/SSH on App Service
  • Linux App Service and Kubernetes need __ not :; ConfigMap keys cannot contain a colon at all
  • App Service connection strings arrive as SQLAZURECONNSTR_/SQLCONNSTR_/CUSTOMCONNSTR_ variables and map to ConnectionStrings:{name}
  • A source added after the defaults (AddJsonFile, App Configuration) beats environment variables
  • Wrong ASPNETCORE_ENVIRONMENT loads the wrong appsettings.{Env}.json; it defaults to Production
  • Environment variables and options captured at start-up need a restart; IOptions never reloads
  • Mounted ConfigMaps update by symlink swap, which file watchers miss: DOTNET_USE_POLLING_FILE_WATCHER=true or restart on change
  • Prevent with configuration in infrastructure as code, ValidateOnStart and a start-up log of providers (never values)

⏱ 30-second answer

Start by proving what the process actually sees, not what the portal says. Use a masked GetDebugView(), which lists every key with the provider that won, or log the provider list at start-up, and run printenv in the container.

The usual causes are:

  • Naming: : in a Linux App Service or Kubernetes variable instead of __; App Service connection strings arriving as SQLAZURECONNSTR_*.
  • Precedence: a JSON file or App Configuration added after the defaults overrides environment variables.
  • Wrong environment: ASPNETCORE_ENVIRONMENT unset, so appsettings.Production.json loads.
  • Timing: environment variables are read once; IOptions<T> never reloads; mounted ConfigMaps update by symlink swap, which file watchers miss.

The trade-off: configuration layering is flexible, but you must be able to see the final merged result in each environment.

🗣 Full answer (senior)

How I would answer this in an interview

"I don't start by staring at the portal, because the portal shows what was set, not what the process read. I want the merged configuration from inside the running app. In a non-production slot I'd hit a diagnostics endpoint that returns GetDebugView() with a masking function so secrets don't leak; it prints every key and the provider that supplied it. If that's not available, I SSH into the App Service container or kubectl exec into the pod and run printenv | grep -i payments to see the variables the process got.

That usually points at one of four things. Naming: on Linux App Service and in Kubernetes you can't use a colon, so Payments:Timeout must be Payments__Timeout; ConfigMap keys reject colons outright. App Service connection strings come through with a prefix like SQLAZURECONNSTR_Default and map to ConnectionStrings:Default, so code reading config["Default"] won't find them. Precedence: someone called AddJsonFile("settings.json") or AddAzureAppConfiguration after CreateBuilder, so that source now beats environment variables. Environment: ASPNETCORE_ENVIRONMENT isn't set, the app runs as Production and loads a different file than expected. Timing: environment variables are read once at start-up, a singleton captured IOptions.Value, or a mounted ConfigMap changed but the file watcher missed the symlink swap.

For example, at [company] a feature flag set in a Kubernetes ConfigMap mounted as appsettings.override.json never changed until pods restarted. The debug view showed the old value from the file provider; the kubelet had swapped the ..data symlink and the inotify watcher never fired. Setting DOTNET_USE_POLLING_FILE_WATCHER=true fixed reloads within [a few seconds]. The lesson I'd stress: make the merged configuration observable, then it's a five-minute problem instead of a day."


Symptom → likely cause

Symptom Likely cause Check
Variable visible in printenv, not in config : vs __, or a prefix filter on AddEnvironmentVariables("X_") Debug view key names
Value present but a JSON value wins Custom source added after environment variables Order of ((IConfigurationRoot)config).Providers
Connection string missing on App Service Reading config["Default"] instead of GetConnectionString("Default") printenv \| grep CONNSTR
Whole set of values wrong Wrong environment name Log IHostEnvironment.EnvironmentName
Changes need a restart Env vars are static; IOptions / captured value Options type used
ConfigMap file edits ignored Symlink swap not seen by watcher DOTNET_USE_POLLING_FILE_WATCHER
Works in one slot, not after swap Setting not marked as a deployment slot setting Slot settings in the portal

Tools

Tool What it tells you
GetDebugView(ctx => mask(ctx)) (.NET 7+) Every key, final value (masked) and provider
((IConfigurationRoot)config).Providers Provider order
kubectl exec <pod> -- printenv, kubectl get cm -o yaml What Kubernetes injected
App Service SSH/Kudu, az webapp config appsettings list What App Service injected
Start-up log of environment name and provider types Regression evidence without leaking values

Production example

An API on Linux App Service ignored Logging:LogLevel:Default=Warning set in the portal; logs stayed at Information and the Application Insights ingestion bill rose about [30%]. printenv showed the variable with a colon, which the Linux environment provider never mapped. Renaming it to Logging__LogLevel__Default and moving all app settings into Bicep fixed it in one deployment.

🔍 What the interviewer is checking

Checks a systematic approach to configuration problems across platforms, starting from evidence instead of guesses.

Green flags

  • Inspects the merged configuration from inside the process, with masking.
  • Knows the __ rule, App Service connection string prefixes and ConfigMap key rules.
  • Explains provider order and how a later source overrides environment variables.
  • Knows the Kubernetes symlink-swap and polling watcher issue.

Red flags

  • Restarts and redeploys until it works.
  • Exposes all configuration, secrets included, through an endpoint.
  • Believes environment variables change in a running process.

📚 Learn in depth

1. The question to answer: which provider won?

            what you set                 what the app reads
Portal / YAML / pipeline  ──►  process environment  ──►  providers  ──►  IConfiguration  ──►  options
          │                         │                      │                   │                  │
   naming rules             printenv shows this     order matters     GetDebugView     IOptions = start-up copy

A value can be lost at each arrow. Debugging means checking each hop.

2. Naming rules per platform

  • Linux (App Service, containers, Kubernetes): variable names with : are invalid or dropped. Use __.
  • Kubernetes ConfigMap keys must match [-._a-zA-Z0-9]+, so Payments__Timeout is fine, Payments:Timeout is rejected.
  • App Service connection strings: the platform prefixes the name with the type: SQLCONNSTR_, SQLAZURECONNSTR_, MYSQLCONNSTR_, POSTGRESQLCONNSTR_, CUSTOMCONNSTR_. The environment variable provider strips these and produces ConnectionStrings:{name}.
  • Prefix filters: AddEnvironmentVariables("MYAPP_") ignores everything without the prefix.

3. Precedence surprises

CreateBuilder defaults:  json → json.{env} → secrets → ENV VARS → cmdline
then your code:          .AddJsonFile("override.json")      ◄ now beats ENV VARS
                         .AddAzureAppConfiguration(...)     ◄ beats everything above

That may be intended (central config wins), but then a portal variable can't override it. If the platform must win, re-add AddEnvironmentVariables() at the end.

4. Reload mechanics in Kubernetes

A ConfigMap mounted as a volume is projected through a hidden ..data symlink. On update the kubelet writes a new directory and atomically swaps the symlink. FileSystemWatcher on Linux uses inotify on the file path and often misses this. DOTNET_USE_POLLING_FILE_WATCHER=true makes PhysicalFileProvider poll (about every 4 seconds). subPath mounts never update at all. Secrets mounted as files can be read with AddKeyPerFile("/mnt/secrets"), where each file name is a key and __ maps to :.

5. Making it observable safely

GetDebugView prints values, including secrets. Since .NET 7 an overload takes a Func<ConfigurationDebugViewContext, string> so you can mask by key or provider. Expose it only in non-production or behind admin authorisation, and log only the provider list and environment name at start-up.

Try it yourself

  1. Run a container with -e Payments:Timeout=5 and -e Payments__Timeout=5; compare the debug view.
  2. Add AddJsonFile("override.json") after CreateBuilder and observe it beat an environment variable.
  3. In kind or minikube, mount a ConfigMap as a file, change it, and watch for reloads with and without the polling variable.
  4. Write a masked GetDebugView endpoint that hides any key containing Password, Secret or Key.
  5. Log the provider types at start-up and confirm their order.

💻 Code

A safe diagnostics view of the merged configuration, a start-up log of providers, and re-adding environment variables last when the platform must win.

// Program.cs
using Microsoft.Extensions.Configuration;

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddJsonFile("config/override.json", optional: true, reloadOnChange: true);
// Platform variables should still win over the mounted file, so add them again at the end
builder.Configuration.AddEnvironmentVariables();

var app = builder.Build();
var root = (IConfigurationRoot)app.Configuration;

// Log the provider order and environment, never values
app.Logger.LogInformation("Environment {Env}; providers: {Providers}",
    app.Environment.EnvironmentName,
    string.Join(" -> ", root.Providers.Select(p => p.ToString())));

if (!app.Environment.IsProduction())
{
    app.MapGet("/_diag/config", () => root.GetDebugView(ctx =>
        IsSensitive(ctx.Key) ? "***" : ctx.Value ?? "(null)"));
}

app.Run();

static bool IsSensitive(string key) =>
    key.Contains("password", StringComparison.OrdinalIgnoreCase) ||
    key.Contains("secret", StringComparison.OrdinalIgnoreCase) ||
    key.Contains("key", StringComparison.OrdinalIgnoreCase) ||
    key.StartsWith("ConnectionStrings", StringComparison.OrdinalIgnoreCase);
# Kubernetes: valid names, and polling so mounted file changes are seen
env:
  - name: ASPNETCORE_ENVIRONMENT
    value: Production
  - name: Payments__Timeout          # __ not :
    value: "00:00:05"
  - name: DOTNET_USE_POLLING_FILE_WATCHER
    value: "true"
volumeMounts:
  - name: app-config
    mountPath: /app/config            # whole directory: subPath mounts never update
kubectl exec deploy/shop-api -- printenv | grep -i payments
az webapp config appsettings list -g rg-shop -n shop-api --query "[].name"

⚠ Common mistakes

  • Mistake: Trusting the portal or YAML as proof of what the app reads. Why it is wrong: Naming, prefixes and precedence can drop or override the value between there and IConfiguration. Instead: Inspect the merged configuration from inside the process.
  • Mistake: Using : in variable names on Linux App Service or in Kubernetes. Why it is wrong: The name is invalid or never mapped. Instead: Use __.
  • Mistake: Reading an App Service connection string with config["Default"]. Why it is wrong: The platform injects it as SQLAZURECONNSTR_Default (or a similar prefix), which the environment provider maps to the key ConnectionStrings:Default, so a top-level Default key never exists and the read returns null. Instead: Read it with GetConnectionString("Default"), which looks under the ConnectionStrings section.
  • Mistake: Adding a custom JSON file or App Configuration after the defaults without thinking about precedence. Why it is wrong: It silently overrides environment variables. Instead: Decide which source must win and order providers deliberately.
  • Mistake: Mounting a ConfigMap with subPath and expecting live updates. Why it is wrong: subPath mounts are never updated by the kubelet. Instead: Mount the directory, enable polling, or roll the pods on change.
  • Mistake: Exposing an unmasked GetDebugView endpoint in production. Why it is wrong: It prints every secret and connection string. Instead: Mask sensitive keys, restrict to non-production or admins.
  • Mistake: Forgetting to mark per-slot values as deployment slot settings. Why it is wrong: They swap with the code and production gets staging values. Instead: Mark environment-specific settings as slot settings.

🏛 Senior insight: trade-offs

Configuration bugs are cheap to fix and expensive to find, so I invest in making them findable: settings defined in Bicep, Terraform or Helm rather than typed into portals, a masked debug view available in non-production, the provider list logged at start-up, and ValidateOnStart so missing values fail the deployment. I also decide explicitly which source wins, platform variables or central App Configuration, and write it down, because "it depends on the order of three lines in Program.cs" is not something on-call engineers should have to rediscover.

Over time I want configuration changes to be visible next to their effects. Azure Activity Log records App Service setting changes, App Configuration keeps a revision history, and Helm or GitOps history covers Kubernetes. I emit a start-up event with the build version, environment and a hash of the non-secret effective configuration to Application Insights, so a dashboard can line up "configuration changed" with error rate or latency shifts and answer "what changed?" in minutes.

Approach When it fits Cost When not to
Masked GetDebugView endpoint Non-production diagnosis Must be secured Unmasked, or in production without auth
printenv / az ... appsettings list Checking what the platform injected Shell access Doesn't show JSON or precedence
Polling file watcher Mounted ConfigMaps that must reload Small CPU cost of polling Settings that are restart-only anyway
Roll pods on ConfigMap change (checksum annotation) Simple, predictable Restart per change Values that must change without restarts

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions provider order or last one wins. Why: Checks the underlying precedence rules they rely on to reason about the bug.
    How to answer

    ASP.NET Core configuration is a layered key-value store. IConfiguration merges an ordered list of providers into one flat, case-insensitive dictionary. WebApplication.CreateBuilder adds, in order: appsettings.json, appsettings.{Environment}.json, user secrets (only in Development), environment variables and command-line arguments. When two providers set the same key, the one added last wins, so an environment variable on the server overrides the JSON file you shipped.

    • Hierarchy is flattened with :, e.g. ConnectionStrings:Default.
    • Environment variables use __ instead, e.g. ConnectionStrings__Default, because : is not allowed in Linux variable names.

    The trade-off: layering lets one build artifact run everywhere, but a value can come from five places, so you need to know the order to find out which one won.

  2. When: Candidate mentions values not reloading without a restart. Why: Checks they know which options interface sees reloaded values.
    How to answer

    All three give you the same bound options; they differ in lifetime and freshness.

    • IOptions<T>: singleton, built once on first .Value, never changes, no named options. The default for settings that need a restart anyway.
    • IOptionsSnapshot<T>: scoped, rebuilt once per request (per scope), supports Get(name). A request sees one consistent value. It can't go into singletons, and it rebinds on every request.
    • IOptionsMonitor<T>: singleton, CurrentValue is cached and rebuilt when the configuration change token fires, supports Get(name) and OnChange. Use it in singletons and BackgroundService.

    Changes only arrive if a provider reloads (JSON files, App Configuration refresh), never from environment variables. The trade-off: fresher values mean code that must cope with values changing under it.

🛠 Real-world problems: how you handle them

Log level set in the portal ignored on Linux App Service
Situation
A .NET 10 API on Linux App Service in Australia East, [4] instances. Ops set `Logging:LogLevel:Default` to Warning in the portal to cut Application Insights costs before end of month.
Signals
Information-level traces kept arriving in Application Insights; ingestion stayed at about [40 GB] a day; no errors anywhere.
Investigation
Opened an SSH session to an instance and ran `printenv | grep -i logging`: the variable existed with colons in its name. The staging slot's masked debug view showed `Logging:LogLevel:Default` still coming from `appsettings.json`. Linux App Service does not map colon names, so the environment provider never produced the key.
Resolution
Immediate: renamed the setting to `Logging__LogLevel__Default` and restarted; ingestion dropped by about [60%] within the hour. Long term: moved all app settings into Bicep with `__` names and added a pipeline check that rejects colon-named app settings.
Prevention
Bicep-managed settings reviewed in pull requests; start-up log of environment and provider order; a non-production masked debug endpoint; runbook entry for 'setting has no effect'.

How to tell it (STAR)

**S:** At [company], our API on Linux App Service kept logging at Information even after ops set the level to Warning in the portal, and Application Insights costs were climbing. **T:** I needed to find why the setting had no effect and stop it happening again. **A:** I SSH'd into an instance and saw the variable name still had colons, then confirmed with our masked debug view in staging that the value still came from appsettings.json. I renamed it with double underscores, then moved every app setting into Bicep and added a pipeline check that fails on colon names. **R:** Ingestion fell by about [60%] the same day, and we haven't had a 'setting ignored' incident since [in the following year].

↩ Usually asked after

More in Configuration

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me