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.
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.
"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.CreateBuilderreadsappsettings.json, thenappsettings.{Environment}.json, then environment variables, soConnectionStrings__Ordersset on the container overrides the file. That is factor three, config.ILoggerwith the console provider writes to stdout, so the platform collects logs, which is factor eleven. The Generic Host listens forSIGTERMand runsIHostedService.StopAsyncwith a shutdown timeout, which is factor nine, disposability. Kestrel binds a port fromASPNETCORE_HTTP_PORTS, which is port binding. And a multi-stage Dockerfile ordotnet publish /t:PublishContainergives 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."
| # | 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 |
| 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.
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.
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
__ separatorRed flags
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.
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.
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.
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.
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.
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.
Greeting__Text=hello-from-env as an environment variable and confirm it overrides appsettings.json.AddOptions<MyOptions>().BindConfiguration("My").ValidateDataAnnotations().ValidateOnStart() with a [Required] property, remove the setting and watch start-up fail./tmp, delete the container and run a new one: the file is gone. That is factor 6.docker stop to the container and log ApplicationStopping to see disposability in action.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).
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.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.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.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.
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.
:, e.g. ConnectionStrings:Default.__ 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.
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.
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.
Last updated 23 Nov 2026.