Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Cloud-Native .NET: back to the course
    Lesson1 / 12

    What Cloud-Native Means for a .NET Service: Twelve-Factor Config, Logs and Disposability

    A cloud-native .NET service runs as replaceable copies. Twelve-factor config, console logs and disposability help those copies scale and stop safely.

    What makes a .NET service cloud-native?

    Scaling means changing how many copies run, or how much capacity they receive. Each running copy is often called a replica.

    The platform handles restarting, scaling and routing requests. Your code must remain correct when a request reaches a different copy or when a copy disappears. Moving a service usually means starting a replacement elsewhere, not carrying its process memory along.

    Required state, such as completed orders, must survive outside the replaceable process. Resilience means handling failures without unnecessarily losing service or corrupting results. Observability means producing enough diagnostic information to understand the running system. These properties matter more than the number of services.

    flowchart TD
        P["Container platform"] -->|"runs"| A["Service copy A"]
        P -->|"runs"| B["Service copy B"]
        A -->|"reads and writes"| S["Shared durable state"]
        B -->|"reads and writes"| S

    Both copies use state that survives the loss of either process.

    A monolith can be cloud-native too. AKS, Azure Kubernetes Service, is Microsoft's managed service for running applications in containers. Putting a monolith on AKS does not, by itself, change how that application behaves.

    It still needs external configuration and required state, useful diagnostics, and suitable startup and shutdown behaviour. A health probe is a check the platform uses to help decide whether a copy is running properly or can receive requests. Telemetry is diagnostic data emitted by the application, including logs, measurements and records of request activity. A cloud-native monolith needs these just as separate services do.

    The mistake to avoid. Do not equate cloud-native with microservices or with a Kubernetes deployment. Neither guarantees that an application can tolerate replacement.

    In an interview, say: “A cloud-native service is designed to run as replaceable copies on a platform that starts, stops, scales and moves them. External state, resilience and observability matter more than service count. A monolith on AKS can qualify, but deployment there alone does not make it cloud-native.”

    How do the twelve factors apply to a .NET API?

    The twelve factors are a set of application-design practices for services operated across different environments. They describe how code, configuration, processes and operational behaviour fit together. Microsoft's cloud-native definition connects these practices to cloud-native applications.

    A backing service is a dependency the application uses over a connection, such as a database, message broker or external cache. Treating it as an attached resource means supplying its address and access settings through configuration rather than tying the application build to one installation.

    FactorWhat it means for a .NET service
    CodebaseKeep the application in version control; deploy it to different environments.
    DependenciesDeclare dependencies explicitly instead of relying on undeclared software on a machine.
    ConfigSupply settings that vary between environments from outside the image.
    Backing servicesConfigure connections to databases, queues and other services.
    Build, release, runSeparate creating the application package, combining it with deployment configuration, and running it.
    ProcessesKeep required state outside replaceable application processes.
    Port bindingHave the web application listen on a configured port.
    ConcurrencyAdd process copies to handle more work, with suitable coordination.
    DisposabilityStart promptly and shut down gracefully.
    Dev/prod parityKeep development and production environments reasonably similar.
    LogsEmit log records as a stream for the surrounding platform to handle.
    Admin processesRun maintenance tasks, such as data repair, as separately controlled jobs.

    An image digest identifies particular image content. Redeploying a known digest lets you roll back the application code to that image.

    Development/production parity is about avoiding expensive surprises, not giving every developer production-sized infrastructure. For example, using the same database engine can reveal differences that an in-memory substitute would hide. Keep dependency versions and important behaviour close without using production secrets or customer data locally.

    The mistake to avoid. Do not build a different image for every environment and assume testing one proves the others. You have changed the application package being tested.

    In an interview, say: “For a containerised .NET API, I prioritise build once, external config, attached backing services, port binding, stateless processes, disposability, streamed logs and dev/prod parity. I promote the tested image unchanged. A known image digest supports code rollback.”

    How does external configuration change .NET application behaviour?

    ASP.NET Core's default application configuration includes JSON files, environment variables and command-line arguments.

    For hierarchical environment settings, use a double underscore. The environment variable Orders__BatchLimit=2 becomes the configuration key Orders:BatchLimit. Similarly, ConnectionStrings__Orders supplies ConnectionStrings:Orders, which an application can read with GetConnectionString("Orders").

    Keep credentials outside the image and source repository. An environment variable is a way to deliver configuration, not a complete secret-management strategy. See configuration and secrets for cloud-native .NET for layering, secure delivery and validation.

    The following console example needs the Microsoft.Extensions configuration and console-logging packages. Its in-memory configuration stands in for a value supplied by deployment settings.

    Structured logging records named values alongside the message, so a log system can query those values without extracting them from prose. Here, BatchLimit, AcceptedCount and DeferredCount are named log fields.

    Before running it, predict how many orders it accepts and defers.

    C#Runs
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Logging;
    
    var configuration = new ConfigurationBuilder()
        .AddInMemoryCollection(new Dictionary<string, string?>
        {
            ["Orders:BatchLimit"] = "2"
        })
        .Build();
    
    if (!int.TryParse(configuration["Orders:BatchLimit"], out int batchLimit)
        || batchLimit <= 0)
    {
        throw new InvalidOperationException("Orders:BatchLimit must be positive.");
    }
    
    int[] orderIds = [101, 102, 103];
    int acceptedCount = Math.Min(batchLimit, orderIds.Length);
    int deferredCount = orderIds.Length - acceptedCount;
    Console.WriteLine($"Accepted: {acceptedCount}; deferred: {deferredCount}");
    
    using var loggerFactory = LoggerFactory.Create(logging =>
        logging.AddJsonConsole());
    var logger = loggerFactory.CreateLogger("OrderBatch");
    
    logger.LogInformation(
        "Batch limit {BatchLimit}: accepted {AcceptedCount}, deferred {DeferredCount}",
        batchLimit, acceptedCount, deferredCount);
    Output
    Accepted: 2; deferred: 1
    {"EventId":0,"LogLevel":"Information","Category":"OrderBatch","Message":"Batch limit 2: accepted 2, deferred 1","State":{"BatchLimit":2,"AcceptedCount":2,"DeferredCount":1,"{OriginalFormat}":"Batch limit {BatchLimit}: accepted {AcceptedCount}, deferred {DeferredCount}"}}

    First, configuration supplies a limit of 2. Validation rejects a missing, invalid or non-positive limit rather than letting the application continue with an unusable setting.

    Next, the program compares that limit with three order IDs. The log record contains the same counts as named values. Change the setting to 3 and run again: it accepts all three without changing the processing logic.

    Port settings are external configuration too. .NET 8 introduced ASPNETCORE_HTTP_PORTS and ASPNETCORE_HTTPS_PORTS for configuring HTTP and HTTPS listening ports. For example, ASPNETCORE_HTTP_PORTS=8080 selects HTTP port 8080. ASPNETCORE_URLS or explicit Kestrel endpoint configuration takes priority over these port settings. Apps using the older WebHost.CreateDefaultBuilder() must use ASPNETCORE_URLS instead.

    Microsoft's ASP.NET Core container images use port 8080 by default from .NET 8 onward, rather than the earlier default of 80. See Microsoft's container port compatibility note. With docker run -p 5000:8080 myapi, the second number, 8080, must match the application's listening port inside the container. The first number, 5000, is the port on your machine.

    The mistake to avoid. Do not bake an environment's addresses, credentials or operating settings into a new image. Supply them externally and validate required values when the application starts.

    In an interview, say: “I keep environment-specific config outside the image. ASP.NET Core maps double underscores to hierarchical keys, so Orders__BatchLimit becomes Orders:BatchLimit. Connection strings attach backing services. Modern hosting supports ASPNETCORE_HTTP_PORTS, and Microsoft ASP.NET Core images default to 8080 from .NET 8.”

    Where should a containerised .NET app write logs?

    Write application logs to standard output and standard error, usually called stdout and stderr. Prefer structured JSON when the platform's collection system supports it.

    The previous example uses AddJsonConsole. Microsoft's JSON console formatter writes each record on one line by default. The application supplies a message template and values; the formatter performs JSON serialization. Do not serialize the message to JSON yourself before passing it to the logger.

    A log collector captures records and sends them to a searchable storage system.

    flowchart TD
        A[".NET application"] -->|"writes records to"| C["stdout or stderr"]
        C -->|"is captured by"| P["Platform log collector"]
        P -->|"ships records to"| S["Searchable log storage"]

    Log files inside a container belong to its filesystem, may disappear with its replacement, and need separate collection and rotation (starting new files and deleting old ones so the disk does not fill up). Do not make the application manage local log files.

    Never include passwords, access tokens or full connection strings in the named fields.

    The mistake to avoid. Do not assume console JSON is already centralised logging. Someone must configure collection, storage and access outside the application, and decide how long logs are kept (retention).

    In an interview, say: “A containerised .NET app should write logs to stdout and stderr, preferably as structured JSON. The platform or a collector ships those records. The app should not manage container-local log files, and choosing a console formatter alone does not provide collection.”

    What breaks when one service becomes three replicas?

    If a session lives only in copy A's memory, a request that reaches copy B cannot use it, and replacing A loses it. A process can still use memory, temporary files and local caches; the question is whether losing them loses required information.

    The same reasoning applies to other features:

    • Local uploads: a file written by A is not automatically available to B. Use durable shared storage such as Azure Blob Storage or a mounted network file share.
    • Authoritative caches: authoritative state is the accepted source of truth. If the only record of an order is in A's memory, losing A loses the order. Put required records in a durable store.
    • Disposable caches: a local copy of data that can be rebuilt from another source is acceptable. Losing it may increase latency or database traffic, but must not lose required information. Its freshness rules still matter.
    • Timer jobs: do not start the same scheduled job with a timer in every replica. Use one separately controlled scheduled job, such as a Kubernetes CronJob, which starts work on a schedule. Another option is a distributed lock: replicas use a shared service to decide which one may run the job. Make the job idempotent, meaning that repeating it has the same intended effect as running it once. Retrying a billing job must not bill the customer twice.

    Shared storage has costs too: extra network calls, latency and another dependency that can fail. Choose storage according to durability and consistency requirements, rather than moving every temporary value into a database.

    The mistake to avoid. Do not interpret “stateless” as “never cache anything.” It means required state must not depend on one replaceable process surviving.

    In an interview, say: “Required state belongs in shared durable storage; rebuildable local caches can be fine. For scheduled work, do not run a timer in every replica. Use a separate job, such as a CronJob, or a distributed lock. Make it idempotent so retries do not repeat effects such as billing.”

    What does disposability mean for ASP.NET Core?

    Disposability means making a running copy easy to start and stop. Fast startup helps replacements become useful sooner. Graceful shutdown gives current work an opportunity to finish instead of abandoning it immediately.

    On Linux, SIGTERM is a signal asking a process to terminate. The .NET host's normal console lifetime supports graceful shutdown in response to it.

    On SIGTERM, the host stops hosted services, and ASP.NET Core stops taking new requests and gives in-flight ones time to finish, up to the host's ShutdownTimeout (30 seconds by default). Kubernetes waits only for its own termination grace period (also 30 seconds by default), then sends SIGKILL, which stops the process at once. Zero-Downtime Deploys for ASP.NET Core on Kubernetes shows how to size the two together.

    For example, a background worker should observe its stopping token rather than start an unlimited new batch during shutdown. The stopping token is the CancellationToken the host passes to BackgroundService.ExecuteAsync; it is cancelled when shutdown starts. See Worker Services in .NET. An HTTP request may finish within the available shutdown time. Neither case guarantees completion if the process crashes or is forcibly terminated.

    Required state must already survive process loss; a last-second “save everything” handler is not a durability strategy.

    The mistake to avoid. Do not treat graceful shutdown as a guarantee that every operation completes. Crashes and forced termination can bypass the opportunity to finish.

    In an interview, say: “Disposability means fast startup and graceful shutdown. On SIGTERM, the .NET host stops hosted services and lets in-flight requests finish within a time limit; SIGKILL follows if the platform's grace period runs out. Required state must already be durable.”

    Check yourself

    A tested image is ready for production. Which approach best follows build-once promotion?

    A Rebuild it with production connection strings in the image.
    B Copy the development container's writable filesystem into production.
    C Rebuild from the same branch and assume the output is identical.
    D Deploy the same image digest with external production configuration.
    Show answer

    Correct answer: D

    Promote the tested image unchanged and supply environment-specific configuration separately.

    Three replicas each cache product descriptions that can be reloaded from a database. Each also starts a nightly billing timer. Which statement is correct?

    A The caches can be acceptable, but billing needs one controlled run plus retry handling.
    B Both break statelessness, since in-memory data makes a replica stateful.
    C Both are safe, since Kubernetes can limit in-app timers to one replica of a Deployment.
    D Billing is safe, since graceful shutdown prevents a second replica's run.
    Show answer

    Correct answer: A

    Rebuildable caches can be disposable local state. A timer in every copy can duplicate billing work, and shutdown does not provide job coordination.

    Going deeper

    Twelve-factor practice is a foundation, not a full production checklist. A modern .NET service also needs:

    For the objects that run and replace your copies, see Kubernetes Basics for .NET Developers.

    Sources

    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 30 Nov 2026 ·