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

📚 Interview question

Tell me about taking an existing ASP.NET Core API that ran on VMs or App Service and making it cloud-native on Azure Container Apps or AKS. What did you find that stopped it running well in containers, what did you change and in what order, and how did you prove it was ready?

Covers a real migration of an existing ASP.NET Core API to Azure Container Apps or AKS: auditing for hidden state, baked-in config, file-based logs and ignored shutdown; containerising; externalising config and secrets with managed identity; probes, telemetry, resilience and scaling; and proving readiness with chaos and load tests.

Senior RealWorldScenario Advanced aspnet-core azure-container-apps cloud-native kubernetes migration production-readiness

🎯 Key points

  • Start with an audit against twelve-factor: local files, in-memory session/cache, Data Protection keys, config files, log files, scheduled jobs
  • Containerise first with no behaviour change: multi-stage or dotnet publish container, non-root, port 8080
  • Externalise config; Azure SQL via Entra ID (Authentication=Active Directory Default + managed identity), so the connection string holds no password
  • Move state out: Blob Storage for files, Redis for session/IDistributedCache, shared Data Protection keys
  • Health and lifecycle: startup/readiness/liveness probes, preStop delay, ShutdownTimeout inside the grace period
  • Telemetry: OpenTelemetry to Application Insights with service.name; dashboards before cut-over
  • Singletons in a scaled-out world: move in-process timers to Container Apps jobs or a lock; migrations as a pipeline step
  • Prove it: kill replicas under load, rolling deploys with zero errors in CI/CD, gradual traffic shift with a tested rollback

⏱ 30-second answer

I would tell it as a four-step story. Audit the app against twelve-factor and find the hidden state: files written to disk, in-memory session, Data Protection keys, appsettings.Production.json with secrets, log files and in-process scheduled jobs. Containerise with no behaviour change. Fix in order of risk: move state out (Blob Storage, Redis, shared keys), externalise config to env vars and Key Vault with managed identity, add probes and graceful shutdown, OpenTelemetry, resilience on outbound calls, and move scheduled jobs and EF migrations out of the web process. Then prove it: kill replicas under load, deploy during a load test with zero errors, and shift traffic gradually with a rollback path.

The trade-off: you can lift and shift into a container in a day, but the work that makes it safe to scale is the state and lifecycle changes, so budget for those.

🗣 Full answer (senior)

How I would answer this in an interview

"At [company] we had [an orders API on two App Service instances with ARR affinity turned on], and the goal was [moving to Azure Container Apps so it could scale with demand and deploy several times a day]. My first step was an audit, not a Dockerfile. I went through the code looking for anything that assumed one long-lived machine, and found [four things: invoice PDFs written to a local folder, session in memory, which only worked because of sticky sessions, Data Protection keys on local disk, and a System.Threading.Timer that sent a nightly report from inside the web app]. We also had [a connection string with a SQL password in appsettings.Production.json].

I sequenced the work by risk. First, containerise with no behaviour change and run it in a test environment, so any later problem was ours, not Docker's. Second, state: files to Blob Storage, session to Redis, Data Protection keys to Blob Storage protected by Key Vault, and only then did we turn off sticky sessions. Third, config: the password went away entirely because we switched Azure SQL to managed identity; the other settings became environment variables and Key Vault references. Fourth, lifecycle and telemetry: startup, readiness and liveness probes, ShutdownTimeout inside the grace period, OpenTelemetry to Application Insights. Fifth, the timer became a Container Apps job, because with three replicas it would have sent three reports.

To prove readiness I ran a load test at [2x peak], killed replicas and did rolling deploys during it. [The first run showed 502s on deploy, which led us to add a preStop delay; the final runs had zero errors.] We cut over with [10% of traffic through Front Door for a week]. [The result: deploys went from monthly to daily, and infrastructure cost fell by about X%.] The lesson I took: containerising is easy; finding the state is the work."


The audit: what breaks in containers

Finding Symptom after scale-out Fix
Files written under the app folder 404s for files created on another replica; lost on redeploy Azure Blob Storage, SAS or managed identity
In-memory session (sticky sessions hid it) Users lose carts or get logged out AddStackExchangeRedisCache + session
Data Protection keys on local disk Antiforgery and cookie failures across replicas PersistKeysToAzureBlobStorage + ProtectKeysWithAzureKeyVault
Secrets in appsettings.Production.json Secret in the image and in git history Managed identity, Key Vault; rotate the leaked secret
Log files with a rolling file sink Logs lost with the container JSON console + OpenTelemetry
In-process timers / Hangfire in the web app Job runs N times, or is killed mid-run on scale-in Container Apps job / Kubernetes CronJob / distributed lock
Database.Migrate() at start-up Replicas race to migrate; slow start fails probes Migration bundle as a pipeline step
Windows-only dependencies (GDI+, System.Drawing) Fails on Linux images Cross-platform library (e.g. SkiaSharp, ImageSharp licence check)

The order of work

Step Why in this order
1. Containerise, no behaviour change Isolates container problems from app changes
2. Move state out Must happen before removing sticky sessions or adding replicas
3. Externalise config and secrets Allows one image across environments
4. Probes, shutdown, telemetry Needed before the platform manages it and before cut-over
5. Jobs and migrations out of the web process Needed before scaling beyond one replica
6. Prove and cut over gradually Evidence and a rollback path

Production example

The migrated API ran three to ten replicas with an HTTP-concurrency scale rule. Rolling deploys under a 2x-peak load test produced zero non-2xx responses after the preStop fix, p95 latency stayed at about 120 ms, and the nightly report ran exactly once a night as a scheduled job.

🔍 What the interviewer is checking

Checks whether the candidate has actually migrated a service and can explain the hidden problems, the order of work and how they proved it was ready.

Green flags

  • Starts with an audit and names concrete hidden state (session, files, Data Protection keys, timers)
  • Orders changes by risk and keeps each change reversible
  • Uses managed identity rather than moving secrets around
  • Proves readiness with kill, deploy and scale tests and a gradual cut-over

Red flags

  • "We wrote a Dockerfile and deployed it"
  • Big-bang cut-over with no rollback
  • Invents precise metrics without saying how they were measured

📚 Learn in depth

1. Why sticky sessions hide problems

App Service's ARR affinity (and any sticky load balancer) sends a user back to the same instance, so in-memory session, local files and per-instance Data Protection keys appear to work. The day you turn affinity off, scale in, or deploy, every hidden assumption fails at once. A good migration finds them in code before the platform finds them in production.

Before (sticky)                       After (stateless)
user A -> instance 1 (A's session)    user A -> any replica -> Redis (session)
user B -> instance 2 (B's files)      user B -> any replica -> Blob Storage (files)
keys: per-instance disk               keys: Blob + Key Vault (shared)

2. Finding hidden state systematically

Search the code and config for:

  • File., Directory., Path.Combine(env.ContentRootPath, IWebHostEnvironment.WebRootPath writes
  • AddSession without a distributed cache, IMemoryCache used as a store
  • AddDataProtection without PersistKeysTo...
  • Timer, PeriodicTimer, BackgroundService that must run once
  • Database.Migrate, EnsureCreated
  • Rolling file sinks in Serilog or NLog configuration
  • Secrets in appsettings*.json and in git history (gitleaks)

3. Container specifics for .NET

  • Official images listen on port 8080 and run as the non-root app user since .NET 8; old code that binds port 80 or writes to the app folder fails.
  • dotnet publish /t:PublishContainer builds an image without a Dockerfile; chiseled aspnet images have no shell, so debugging uses kubectl debug or Container Apps console with a debug image.
  • The GC reads the cgroup memory limit; set a memory limit so the heap is sized correctly, and consider DATAS (on by default with Server GC since .NET 9) for smaller memory per replica.
  • Linux is case-sensitive: Views/Home/index.cshtml versus Index.cshtml bugs appear here.

4. Scheduled work in a scaled-out world

Option When
Container Apps job (schedule trigger) / Kubernetes CronJob Independent batch work; the cleanest choice
Distributed lock (Azure Blob lease, SQL sp_getapplock) Work that must stay in-process but run once
Durable scheduler (Hangfire with SQL storage, Quartz clustered) Many jobs with retries and dashboards

5. Proving readiness

  1. Kill test: delete replicas every 30-60 seconds during load; error rate should stay flat.
  2. Deploy test: rolling deploy under load; zero non-2xx is the bar.
  3. Scale test: ramp from 1x to 3x peak; autoscale reacts before latency SLO breaks.
  4. Dependency test: block Redis or a downstream API; the service degrades gracefully, readiness behaves as designed.
  5. Gradual cut-over: Azure Front Door or Traffic Manager weights (10% → 50% → 100%), with the old environment kept warm for rollback.

6. Australian context

If the API holds personal information, keep the Container Apps environment and data stores in Australia East (with Australia Southeast for DR) to meet customer data-residency expectations, and treat any secret found in git history as exposed: rotate it and assess under the Notifiable Data Breaches scheme if personal data could have been accessed.

Try it yourself

  1. Take any ASP.NET Core app, run two replicas behind a non-sticky proxy and list everything that breaks.
  2. Grep a codebase for the hidden-state patterns above and write the findings up as a table.
  3. Build the app with dotnet publish /t:PublishContainer and run it with a read-only root file system.
  4. Replace an in-process timer with a Container Apps job (or a kind CronJob) and confirm it runs once with three replicas.
  5. Run a k6 test while doing kubectl rollout restart and count errors before and after adding probes and a preStop delay.

💻 Code

Before and after for the three changes that matter most: state, config and scheduled work. The "after" version needs the NuGet packages Azure.Identity, Azure.Storage.Blobs, Azure.Extensions.AspNetCore.DataProtection.Blobs, Azure.Extensions.AspNetCore.DataProtection.Keys, Microsoft.Extensions.Caching.StackExchangeRedis, Microsoft.EntityFrameworkCore.SqlServer and Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore.

// BEFORE: works on one sticky instance only
builder.Services.AddSession();                       // in-memory: lost across replicas
builder.Services.AddDataProtection();                // keys on local disk, per instance
builder.Services.AddDbContext<OrdersDb>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("Orders"))); // password in appsettings.Production.json
builder.Services.AddHostedService<NightlyReportTimer>(); // runs on every replica

app.MapPost("/invoices/{id:int}", async (int id, IWebHostEnvironment env, CancellationToken ct) =>
{
    var path = Path.Combine(env.ContentRootPath, "invoices", $"{id}.pdf"); // local disk
    await File.WriteAllBytesAsync(path, InvoiceRenderer.Render(id), ct);
    return Results.Ok();
});
// AFTER (.NET 10): stateless, identity-based, scheduled work moved out
using Azure.Identity;
using Azure.Storage.Blobs;
using Microsoft.AspNetCore.DataProtection;

var builder = WebApplication.CreateBuilder(args);
var credential = new DefaultAzureCredential(); // ManagedIdentityCredential in production

builder.Services.AddStackExchangeRedisCache(o => o.Configuration = builder.Configuration.GetConnectionString("Redis"));
builder.Services.AddSession(); // now backed by Redis through IDistributedCache

var blobs = new BlobServiceClient(new Uri(builder.Configuration["Storage:BlobEndpoint"]!), credential);
builder.Services.AddSingleton(blobs);
builder.Services.AddDataProtection()
    .SetApplicationName("orders-api")
    .PersistKeysToAzureBlobStorage(blobs.GetBlobContainerClient("dataprotection").GetBlobClient("keys.xml"))
    .ProtectKeysWithAzureKeyVault(new Uri(builder.Configuration["KeyVault:DataProtectionKeyId"]!), credential);

// Azure SQL with Entra ID authentication: the connection string names the auth method, not a password.
// Microsoft.Data.SqlClient uses the managed identity (or your developer login locally) to get a token.
// ConnectionStrings__Orders = "Server=tcp:orders.database.windows.net;Database=orders;Authentication=Active Directory Default;Encrypt=True"
// In production, prefer "Authentication=Active Directory Managed Identity;User Id=<client-id>" for a user-assigned identity.
builder.Services.AddDbContext<OrdersDb>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Orders")));

builder.Services.AddHealthChecks().AddDbContextCheck<OrdersDb>(tags: ["ready"]);
builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(25));

var app = builder.Build();
app.UseSession();
app.MapHealthChecks("/health/live", new() { Predicate = _ => false });
app.MapHealthChecks("/health/ready", new() { Predicate = c => c.Tags.Contains("ready") });

app.MapPost("/invoices/{id:int}", async (int id, BlobServiceClient blobService, CancellationToken ct) =>
{
    var blob = blobService.GetBlobContainerClient("invoices").GetBlobClient($"{id}.pdf");
    await blob.UploadAsync(BinaryData.FromBytes(InvoiceRenderer.Render(id)), overwrite: true, ct);
    return Results.Ok();
});
app.Run();
-- In the Orders database: let the app's managed identity in, with least privilege
CREATE USER [id-orders-api] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [id-orders-api];
ALTER ROLE db_datawriter ADD MEMBER [id-orders-api];
# The nightly report becomes a scheduled Container Apps job that runs once, not once per replica
az containerapp job create --name orders-nightly-report --resource-group rg-orders \
  --environment cae-orders --trigger-type Schedule --cron-expression "0 14 * * *" \
  --image myregistry.azurecr.io/orders-report:3f2a9c1 --replica-timeout 1800 \
  --mi-user-assigned <identity-resource-id>   # 14:00 UTC = 01:00 AEDT

⚠ Common mistakes

  • Mistake: Writing the Dockerfile first and auditing later. Why it is wrong: The app "works" in a container with one replica and the hidden state surfaces in production. Instead: Audit for state, config, logs, jobs and shutdown before changing hosting.
  • Mistake: Turning off sticky sessions before moving session and Data Protection keys. Why it is wrong: Every user is logged out or loses data at the moment of cut-over. Instead: Move state out first, verify with two replicas, then remove affinity.
  • Mistake: Changing hosting, framework version and architecture in one release. Why it is wrong: When something breaks you cannot tell which change caused it. Instead: Containerise with no behaviour change, then make changes one at a time.
  • Mistake: Leaving in-process scheduled jobs in a scaled-out web app. Why it is wrong: They run once per replica, or get killed mid-run on scale-in. Instead: Use a scheduled Container Apps job, a CronJob or a distributed lock.
  • Mistake: Running Database.Migrate() at start-up across replicas. Why it is wrong: Replicas race, start-up is slow and probes fail during long migrations. Instead: Run an EF Core migration bundle as a pipeline step before the deploy.
  • Mistake: Copying the secret from appsettings.Production.json into Key Vault and moving on. Why it is wrong: It is still in git history and in old images. Instead: Rotate it, or remove it with managed identity, and scan history.
  • Mistake: Declaring it ready after a smoke test. Why it is wrong: Problems appear only under load, scaling and deploys. Instead: Kill replicas and deploy during a load test, then cut over gradually with a rollback path.

🏛 Senior insight: trade-offs

The senior signal in this story is sequencing and evidence. Anyone can write a Dockerfile; a senior engineer finds the assumptions an app makes about its machine, orders the changes so each is small and reversible, and proves readiness with tests that simulate what the platform will do (kill, deploy, scale). Also be honest about whether Container Apps or AKS is the right target: most single-team APIs are better served by Container Apps (or even App Service) than by running a Kubernetes cluster.

Target When it fits Cost When not to
App Service (containers) One or a few web apps, simple scaling Less control over sidecars, scale rules Event-driven scaling, many services
Azure Container Apps Several services, KEDA scaling, scale to zero, Dapr optional Less control than raw Kubernetes Need custom operators, CRDs, full mesh control
AKS Platform team, many teams/services, custom networking Cluster operations, upgrades, security One team, a handful of services

Measure success with deploy frequency, change failure rate, errors during deploys and cost per request before and after.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions stateless processes or externalised config Why: Checks they can map the twelve factors to ASP.NET Core features.
    How to 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.

  2. When: Candidate mentions probes or errors during deploys Why: Checks they understand SIGTERM, ShutdownTimeout, preStop delays and probe design.
    How to answer

    When a pod is stopped, Kubernetes removes it from Service endpoints and sends SIGTERM at the same time, then waits terminationGracePeriodSeconds (30 s by default) before SIGKILL. In .NET the Generic Host turns SIGTERM into IHostApplicationLifetime.ApplicationStopping; Kestrel stops accepting new connections and drains in-flight requests, and every IHostedService.StopAsync runs, all bounded by HostOptions.ShutdownTimeout (30 s by default since .NET 6, including .NET 10; it was 5 s before). Because endpoint removal propagates slowly, add a short preStop delay so the pod keeps serving until load balancers stop sending to it.

    On the way up, a startup probe covers slow initialisation, a readiness probe decides whether the pod gets traffic, and liveness restarts only a truly stuck process. The trade-off: longer grace periods mean safer drains but slower deploys and scale-in.

  3. When: Candidate mentions choosing Container Apps or AKS Why: Checks they can choose between App Service, Functions, Container Apps and AKS on cost and operations.
    How to answer

    I choose by how much platform the team wants to run:

    • App Service: one or a few web apps, always on, deployment slots, almost no ops. Paid per plan instance.
    • Azure Functions: event-driven or spiky work (queues, timers, blobs); Flex Consumption scales per event and to zero.
    • Container Apps: containerised microservices on managed Kubernetes with KEDA scaling, revisions and scale to zero, without touching the cluster.
    • AKS: full Kubernetes when you need its API, custom networking or many services and have a platform team.

    The trade-off is control versus operations: each step towards AKS gives more control and more work. I start with the simplest option that meets the requirements and move only when I hit a concrete limit.

🛠 Real-world problems: how you handle them

Sticky sessions hid four kinds of state
Situation
An orders API on [2] App Service instances with ARR affinity, [~300] requests a second at peak, moving to Azure Container Apps to scale with demand and deploy daily. Holds customer addresses, so data stays in Australia East.
Signals
In the first test with three replicas and affinity off: users logged out at random, antiforgery validation failures, invoice downloads returning 404 about two-thirds of the time, and the nightly report emailed three times.
Investigation
Correlated failures with `cloud_RoleInstance` in Application Insights; grepped the code for local file writes, `AddSession`, `AddDataProtection` and timers; checked `appsettings.Production.json` and git history with gitleaks and found a SQL password.
Resolution
Moved invoices to Blob Storage, session to Azure Cache for Redis and Data Protection keys to Blob Storage protected by Key Vault; switched Azure SQL to managed identity and rotated the old password; turned the timer into a scheduled Container Apps job; added probes, a preStop delay and OpenTelemetry. Cut over with Front Door at 10%, then 50%, then 100% over [two weeks].
Prevention
A migration checklist based on the audit, a pipeline gate for secret scanning, a kill-and-deploy load test in staging, and an ADR recording the move off sticky sessions.

How to tell it (STAR)

**S:** We had an orders API on [two] App Service instances with sticky sessions, and the business wanted daily deploys and automatic scaling, so we moved to Container Apps. **T:** I led the migration and owned making sure customers noticed nothing. **A:** Before writing a Dockerfile, I audited the code and found four kinds of hidden state that sticky sessions had masked, plus a password in a config file. I containerised with no behaviour change, then moved files, session and Data Protection keys out, switched SQL to managed identity, moved the nightly timer into a scheduled job, and added probes and telemetry. I proved it with kill-and-deploy load tests and cut over through Front Door in stages. **R:** We went from [monthly] to [daily] deploys with [zero] customer-visible errors during cut-over, and the report ran exactly once a night.

More in Cloud-Native Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me