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

📚 Interview question

What is the twelve-factor app? Walk me through the factors that matter most for a .NET service and map each one to an ASP.NET Core feature, and tell me which factors you would bend in practice.

Covers the twelve-factor methodology and maps codebase, dependencies, config, backing services, build/release/run, stateless processes, port binding, concurrency, disposability, dev/prod parity, logs and admin processes to ASP.NET Core and .NET 10 features.

Junior Theory Beginner aspnet-core cloud-native configuration containers stateless twelve-factor

🎯 Key points

  • Twelve factors: a methodology from Heroku (2011) for apps that deploy and scale cleanly on a platform
  • Config in the environment: IConfiguration with environment variables overriding appsettings.json (Section__Key)
  • Backing services as attached resources: a connection string swap, not a code change
  • Build, release, run: one immutable image promoted through environments, config added at release
  • Stateless, share-nothing processes: no local files, in-memory sessions or sticky state; use Redis, Blob Storage, SQL
  • Disposability: fast start-up, graceful SIGTERM shutdown via the Generic Host and IHostApplicationLifetime
  • Logs as event streams: ILogger to stdout, the platform ships them; no log files in the container
  • Dev/prod parity: same image and same backing service types locally (containers, Aspire)

⏱ 30-second answer

The twelve-factor app is a methodology, first published by Heroku in 2011, for building services that a platform can deploy, scale and replace without hand-holding. It is still the baseline that Azure Container Apps, AKS, App Service and AWS ECS assume. The factors that matter most for .NET are: config in the environment (ASP.NET Core's IConfiguration already layers environment variables over appsettings.json), backing services as attached resources (swap a connection string, not code), build, release, run (one immutable container image promoted through environments), stateless processes (no local disk or in-memory session state), disposability (fast start, graceful SIGTERM handling through the Generic Host) and logs as event streams (ILogger to stdout).

The trade-off: it is a set of strong defaults, not a law. Follow its intent, and bend factors such as "logs only" (use OpenTelemetry for all three signals) or secrets in plain environment variables (use Key Vault) where the platform gives you a better tool.

🗣 Full answer (senior)

How I would answer this in an interview

"The twelve-factor app is a checklist Heroku published in 2011 describing how to build a service so that a platform can run it: start it, scale it to many copies, kill it and replace it, without anyone logging into a server. The core idea is that the same build artefact runs in every environment and everything that differs between environments, like connection strings and feature switches, comes from outside the artefact.

In ASP.NET Core most of it is built in. WebApplication.CreateBuilder reads appsettings.json, then appsettings.{Environment}.json, then environment variables, so ConnectionStrings__Orders set on the container overrides the file. That is factor three, config. ILogger with the console provider writes to stdout, so the platform collects logs, which is factor eleven. The Generic Host listens for SIGTERM and runs IHostedService.StopAsync with a shutdown timeout, which is factor nine, disposability. Kestrel binds a port from ASPNETCORE_HTTP_PORTS, which is port binding. And a multi-stage Dockerfile or dotnet publish /t:PublishContainer gives you one image you promote from test to production, which is build, release, run.

The mistake I see is teams that containerise an app but keep it stateful: uploads written to /app/uploads, sessions in memory, a log file in the container. It works with one replica and breaks the day you scale to three or the platform moves a pod. My rule is that any instance must be safe to kill at any moment."


The factors mapped to .NET

# Factor What it means ASP.NET Core / .NET 10 feature
1 Codebase One repo (or one deployable) per app, many deploys One project per service, CI builds from a commit
2 Dependencies Declare everything, rely on nothing installed on the host PackageReference, central package management, chiseled base images
3 Config Settings that vary by environment live in the environment IConfiguration, environment variables (Section__Key), Key Vault provider
4 Backing services Databases, queues, caches are attached resources Connection strings, Aspire resource references
5 Build, release, run Separate stages; releases are immutable One container image, tagged by commit SHA, config added at deploy
6 Processes Stateless, share-nothing Redis for sessions and IDistributedCache, Blob Storage for files
7 Port binding The app is self-contained and exports HTTP on a port Kestrel, ASPNETCORE_HTTP_PORTS=8080 (default in .NET 8+ images)
8 Concurrency Scale out by adding processes Replicas, KEDA, Container Apps scale rules
9 Disposability Fast start, graceful stop Generic Host, HostOptions.ShutdownTimeout, IHostApplicationLifetime
10 Dev/prod parity Keep environments alike Same image everywhere, SQL Server and Redis in containers locally, Aspire
11 Logs Treat logs as an event stream ILogger to stdout (JSON console formatter), OpenTelemetry
12 Admin processes One-off tasks run in the same release EF Core migration bundles, Kubernetes Jobs, Container Apps jobs

Which factors you bend

Factor Where teams sensibly bend it
Config Secrets come from Key Vault or mounted files, not plain environment variables, because environment variables leak into crash dumps and docker inspect
Logs Modern platforms want all three signals (logs, metrics, traces) through OpenTelemetry, not only a stdout stream
Admin processes Migrations run as a separate pipeline step or job, not as a REPL inside the app
Codebase A monorepo holding many services is fine as long as each one builds and deploys separately

The methodology was open-sourced in late 2024 and the community is updating it, but the 2011 version is what interviewers quote.

Production example

A team running an ASP.NET Core API on Azure App Service stored invoice PDFs on local disk and kept a cart in session memory. Moving to Azure Container Apps with three replicas, about 1 in 3 downloads returned 404 and carts emptied on every deploy. Moving files to Blob Storage and session to Azure Cache for Redis made instances interchangeable, and deploys stopped generating support tickets.

🔍 What the interviewer is checking

Checks whether the candidate knows the factors that matter in practice and can tie them to real ASP.NET Core mechanisms rather than reciting a list.

Green flags

  • Names config, statelessness, disposability and logs first, with concrete .NET features
  • Knows the configuration provider order and the __ separator
  • Mentions hidden state such as sessions, local files and Data Protection keys
  • Says where they would bend a factor (secrets not in plain env vars)

Red flags

  • Recites twelve names with no .NET mapping
  • Thinks "in a container" automatically means cloud-native
  • Bakes per-environment config into images

📚 Learn in depth

1. Where twelve-factor came from

Heroku ran thousands of customer apps on shared machines ("dynos"). It could only do that if apps behaved predictably: they started from one command, read settings from the environment, wrote nothing important to local disk and stopped cleanly when told. The twelve factors are those expectations written down. Kubernetes, Azure Container Apps, App Service and AWS ECS all make the same assumptions, so the list still describes what a platform needs from you.

2. The central idea: one artefact, many environments

   source commit
        |
     [ build ]  ---> image: orders-api:3f2a9c1   (immutable)
        |
   [ release ] = image + config for an environment
        |                |                 |
      dev              test             prod
   (env vars)        (env vars)       (env vars + Key Vault)
        |
     [ run ]  N identical, disposable processes

If you rebuild per environment, what you tested is not what you ship. If config is baked into the image, you need a new image to change a timeout. Both break the model.

3. How ASP.NET Core implements factor 3 (config)

WebApplication.CreateBuilder(args) adds configuration providers in this order; later ones win:

appsettings.json
appsettings.{ASPNETCORE_ENVIRONMENT}.json
user secrets (Development only)
environment variables
command-line arguments

Environment variables use __ (double underscore) as the hierarchy separator because : is not allowed in variable names on every OS, so Orders__Timeout=00:00:05 maps to Orders:Timeout. Options classes bound with AddOptions<T>().Bind(...).ValidateOnStart() fail at start-up if a required setting is missing, which is exactly what you want: a bad release fails its readiness check instead of serving errors.

4. Statelessness (factor 6) and why it is the hardest

State hides in many places in a .NET app:

Hidden state Cloud-native replacement
Files written under the content root Azure Blob Storage / S3
AddSession() with the default in-memory cache AddStackExchangeRedisCache
IMemoryCache used as a source of truth Cache only; the database stays authoritative
Data Protection keys on local disk PersistKeysToAzureBlobStorage + ProtectKeysWithAzureKeyVault
In-process timers that must run once A single scheduled job, or a distributed lock

The Data Protection one bites teams: with keys on local disk, each replica has different keys, so auth cookies and antiforgery tokens created on one instance fail on another.

5. Disposability (factor 9) in the Generic Host

On SIGTERM the host's console lifetime triggers IHostApplicationLifetime.ApplicationStopping, Kestrel stops accepting new connections and waits for in-flight requests, and each IHostedService.StopAsync is called with a token that is cancelled when HostOptions.ShutdownTimeout (30 seconds by default) expires. Fast start-up matters too: a service that takes 90 seconds to warm up cannot scale quickly under load. Phase 25's graceful shutdown question goes deeper.

6. Logs (factor 11)

The app writes one event per line to stdout; the platform (Container Apps, AKS with Container Insights, a log agent) ships it. In .NET use builder.Logging.AddJsonConsole() or OpenTelemetry's OTLP exporter. Writing your own rolling log files inside a container loses them when the container is replaced.

Try it yourself

  1. Create a minimal API, set Greeting__Text=hello-from-env as an environment variable and confirm it overrides appsettings.json.
  2. Add AddOptions<MyOptions>().BindConfiguration("My").ValidateDataAnnotations().ValidateOnStart() with a [Required] property, remove the setting and watch start-up fail.
  3. Run the app in a container, write a file to /tmp, delete the container and run a new one: the file is gone. That is factor 6.
  4. Send docker stop to the container and log ApplicationStopping to see disposability in action.
  5. Run two replicas behind a simple YARP proxy with in-memory session and watch the session flip between instances.

💻 Code

A Program.cs that follows the factors that live in code: config from the environment with validation, stateless storage, stdout logs and graceful shutdown.

// Program.cs (.NET 10, nullable enabled)
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.DataProtection;

var builder = WebApplication.CreateBuilder(args);

// Factor 3: config comes from the environment. Orders__StorageContainer overrides appsettings.json.
builder.Services.AddOptions<OrdersOptions>()
    .BindConfiguration(OrdersOptions.Section)
    .ValidateDataAnnotations()
    .ValidateOnStart(); // a bad release fails at start-up, not on the first request

// Factor 6: no state on local disk or in process memory.
// AddSession stores session data in whatever IDistributedCache is registered;
// registering the Redis cache first means session state lives in Redis, not in the process.
builder.Services.AddStackExchangeRedisCache(o =>
    o.Configuration = builder.Configuration.GetConnectionString("Redis"));
builder.Services.AddSession();
builder.Services.AddDataProtection()
    .SetApplicationName("orders-api"); // plus PersistKeysToAzureBlobStorage in production

// Factor 11: logs are an event stream on stdout.
builder.Logging.ClearProviders();
builder.Logging.AddJsonConsole();

// Factor 9: give in-flight work time to finish when SIGTERM arrives.
builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(25));

builder.Services.AddHealthChecks();

var app = builder.Build();
app.UseSession();
app.MapHealthChecks("/health/ready");
app.MapGet("/", () => Results.Ok("orders-api"));
app.Run(); // Factor 7: Kestrel binds ASPNETCORE_HTTP_PORTS (8080 in the official images)

public sealed record OrdersOptions
{
    public const string Section = "Orders";
    [Required] public string StorageContainer { get; init; } = "";
    [Range(1, 60)] public int TimeoutSeconds { get; init; } = 5;
}
# Factor 5: one image, config supplied at release time
docker run -e Orders__StorageContainer=invoices \
           -e ConnectionStrings__Redis=redis:6379 \
           -p 8080:8080 orders-api:3f2a9c1

Where the platform helps: Azure Container Apps revisions give you immutable releases (factor 5), KEDA scale rules give you concurrency by process count (factor 8), and Container Apps jobs or Kubernetes Jobs run one-off admin tasks such as an EF Core migration bundle (factor 12).

⚠ Common mistakes

  • Mistake: Building a separate image per environment with appsettings.Production.json baked in. Why it is wrong: What you tested is not what you ship, and changing a setting needs a rebuild. Instead: Build once, promote the same image and supply config at deploy time.
  • Mistake: Putting secrets in plain environment variables and calling it twelve-factor. Why it is wrong: Environment variables show up in docker inspect, process dumps and portal screens. Instead: Use Key Vault references, managed identity or mounted secret files for secrets; environment variables for non-secret settings.
  • Mistake: Writing uploads or generated files to the container's file system. Why it is wrong: The file exists on one replica only and disappears when the container is replaced. Instead: Write to Blob Storage or S3 and keep the container disposable.
  • Mistake: Using in-memory session or IMemoryCache as the source of truth in production. Why it is wrong: It only works while there is exactly one instance that never restarts; with several replicas, autoscaling or a deploy, users see inconsistent data or lose their session. In-memory is acceptable for local development only. Instead: Use IDistributedCache with Redis for session, and treat caches as caches with the database as the source of truth.
  • Mistake: Leaving Data Protection keys on local disk. Why it is wrong: Cookies and antiforgery tokens from one instance fail on another and after every deploy. Instead: Persist keys to Blob Storage and protect them with Key Vault.
  • Mistake: Writing rolling log files inside the container. Why it is wrong: Logs vanish with the container and fill its writable layer. Instead: Log JSON to stdout or export with OpenTelemetry.
  • Mistake: Treating the twelve factors as a strict standard. Why it is wrong: Some factors (admin processes, logs-only telemetry) predate modern platforms. Instead: Apply the intent: immutable artefacts, external config, disposable processes.

🏛 Senior insight: trade-offs

Twelve-factor is the cheapest architecture review you can do on a service: most production incidents during a container migration come from factors 3, 6 and 9 (config baked in, hidden state, ignoring shutdown). ASP.NET Core gives you most of the plumbing for free; the work is finding the places where the code quietly depends on the machine it runs on.

Factor When strict adherence pays Cost When to bend it
Config in environment Many environments, frequent changes Need a config inventory and validation Secrets: use Key Vault or mounted files
Stateless processes More than one replica, autoscaling External cache/storage, a network hop Single-instance internal tools
Logs as streams Any containerised platform Need a log backend You need traces and metrics too: use OpenTelemetry

To measure how cloud-native a service is, kill a random replica during a load test: error rate should stay flat, and no user data should be lost.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions environment variables overriding appsettings.json Why: Checks they know the provider order and how hierarchical keys map to environment variables.
    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 shipping one immutable image Why: Checks they understand images, layers and why containers suit build, release, run.
    How to answer

    A container is an ordinary process that the Linux kernel isolates with namespaces (its own view of files, network, process IDs) and limits with cgroups (CPU and memory). A virtual machine runs a whole guest operating system on a hypervisor. Containers share the host kernel, so they start in milliseconds and pack densely; VMs isolate more strongly but are heavier.

    An image is the read-only, layered template (an OCI image); a container is a running instance of it with a thin writable layer on top. Layers are cached and shared, so rebuilds and pulls are fast.

    We ship .NET services as containers because the same immutable artefact runs on a laptop, in CI and in Azure Container Apps or AKS. The trade-off: weaker isolation than a VM and a new set of things to operate.

  3. When: Candidate mentions stateless processes Why: Checks they know Data Protection keys and session are hidden state.
    How to answer

    ASP.NET Core's Data Protection system encrypts auth cookies and antiforgery tokens with a key ring. By default each instance creates its own key ring on local disk, so a cookie protected by replica A cannot be decrypted by replica B, and every redeploy creates new keys. Fix it by persisting keys to a shared store (PersistKeysToAzureBlobStorage), protecting them at rest with Key Vault (ProtectKeysWithAzureKeyVault) and setting the same SetApplicationName on every instance. If the app uses session, back it with IDistributedCache (Redis) so any replica can read it. Sticky sessions only hide the problem: they break on scale-in, deploys and pod rescheduling, so treat them as a stopgap, not the fix.

↩ Usually asked after

More in Cloud-Native Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me