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

📚 Interview question

Code review: a teammate's ASP.NET Core service, about to be deployed to Kubernetes, saves uploaded files and a SQLite cache to the container's local disk, reads its settings (including an API key) from a config.json copied into the image, logs to a rolling file, and runs a background loop that ignores the stopping token. What do you flag, in what order, and what does the fixed version look like?

A code review of a container-unfriendly ASP.NET Core service: local disk state, secrets in a config file baked into the image, file logging, a BackgroundService that ignores SIGTERM, and missing probes; findings ranked by severity with a cloud-native rewrite using Blob Storage, IConfiguration with Key Vault, stdout logging, cancellation and health endpoints.

Senior CodeReview Advanced aspnet-core cloud-native code-review configuration graceful-shutdown kubernetes

🎯 Key points

  • Severity order: secret in the image (security) > data loss on non-persistent container disk > shutdown ignored > config inflexibility > logs and diagnostics
  • API key in config.json inside the image: anyone with registry pull access has it; rotate and move to Key Vault + managed identity
  • Uploads and SQLite on the writable layer: not persistent, lost on every restart, invisible to other replicas; use Blob Storage and a shared cache
  • BackgroundService ignoring stoppingToken: work killed by SIGKILL after the grace period; pass the token, finish or abandon cleanly
  • Custom config.json bypasses IConfiguration: no env var overrides, no validation; bind options with ValidateOnStart
  • Rolling file logs in the pod: lost with it, fill the writable layer, never reach central logging (Azure Monitor / App Insights), so incidents cannot be traced
  • Health endpoints wired to probes: readiness gates traffic, liveness restarts only a hung process; plus non-root and read-only root file system
  • Close with blocking vs suggested comments and automation: secret scanning, analysers, manifest policy

⏱ 30-second answer

I rank the findings by severity. Blocking: the API key is baked into the image through config.json, so anyone who can pull the image (or read the repo) has it; rotate it and load it from Key Vault with managed identity. Blocking: uploads and the SQLite cache live on the container's disk, so files vanish on every restart or reschedule and other replicas cannot see them; use Blob Storage and a shared cache. Blocking: the background loop ignores the stopping token, so on SIGTERM the host waits out ShutdownTimeout and Kubernetes then SIGKILLs work mid-flight. Then the non-blocking but important items: replace the hand-rolled config file with IConfiguration and validated options, log JSON to stdout instead of a rolling file, and add readiness and liveness endpoints.

The trade-off: each fix adds an external dependency, which is the price of a disposable container.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd read it as 'what happens when Kubernetes treats this pod as disposable', because it will. The first thing I flag is security: the API key sits in a config.json that the Dockerfile copies into the image. Images get pushed to registries, cached on nodes and pulled by anyone with access, so that key is effectively published. I would block the PR, ask for the key to be rotated, and move it to Key Vault, read with managed identity.

Next is data loss. Uploads go to /app/uploads and the cache to a SQLite file in the container. A pod is restarted on every deploy, every node upgrade and every OOM kill, and the writable layer goes with it. With three replicas, a file uploaded to one is missing on the other two. For example, at [company] we [had exactly this: users uploaded documents that disappeared after the Tuesday deploy, and we lost about N files before we noticed]. Uploads belong in Blob Storage; a cache that must be shared belongs in Redis, or it should be an IMemoryCache that is honestly per instance.

Third is shutdown: the BackgroundService loops with while (true) and Thread.Sleep, so SIGTERM is ignored, the host waits 30 seconds and Kubernetes kills it, possibly halfway through processing an item. It must use the stopping token and await Task.Delay(..., token). After that, the non-blocking items: the custom config loader bypasses IConfiguration, so environment variables cannot override anything; logs go to a rolling file nobody will ever read; and there are no health endpoints. My closing line on a review like this is: a container should hold code, not data or secrets."


Code under review

// Program.cs
var config = JsonSerializer.Deserialize<AppConfig>(File.ReadAllText("config.json"))!; // 1

var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddFile("logs/app-{Date}.log");                                       // 2
builder.Services.AddSingleton(config);
builder.Services.AddDbContext<CacheDb>(o => o.UseSqlite("Data Source=/app/data/cache.db")); // 3
builder.Services.AddHostedService<SyncWorker>();

var app = builder.Build();
app.MapPost("/upload", async (IFormFile file) =>
{
    var path = Path.Combine("/app/uploads", file.FileName);                            // 4
    using var stream = File.Create(path);
    await file.CopyToAsync(stream);
    return Results.Ok(path);
}).DisableAntiforgery();
app.Run();                                                                             // 5

public class SyncWorker(AppConfig config, HttpClient http) : BackgroundService
{
    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (true)                                                                   // 6
        {
            http.DefaultRequestHeaders.Add("X-Api-Key", config.ApiKey);                // 7
            var data = http.GetStringAsync(config.PartnerUrl).Result;                  // 8
            Thread.Sleep(TimeSpan.FromMinutes(1));
        }
    }
}
COPY config.json /app/config.json   # contains "ApiKey": "live-..."

Findings, by severity

# Severity Finding Why it matters Fix
1 Security (blocking) API key in config.json copied into the image Anyone with registry or repo access has the key; it lives in every image layer forever Rotate; Key Vault + managed identity via IConfiguration
4 Security + data loss (blocking) Uploads saved to local disk using the client's FileName Path traversal and overwrite risk; files lost on restart; invisible to other replicas Blob Storage, server-generated names, size and type limits
3 Data loss (blocking) SQLite cache on the container file system Lost on restart, diverges per replica, writes fail with a read-only root FS Redis / IDistributedCache, or honest per-instance IMemoryCache
6, 8 Stall (blocking) while (true), Thread.Sleep, .Result, token ignored; ExecuteAsync never yields Blocks host start-up (synchronous work before the first await), ignores SIGTERM, SIGKILL mid-work, thread-pool starvation async loop with PeriodicTimer and stoppingToken
7 Bug DefaultRequestHeaders.Add every loop Header list grows each minute; not thread-safe Typed client configured once; per-request header
1 Design Hand-rolled config loader No env var overrides, no validation, no reload Options pattern with ValidateOnStart
2 Diagnostics Rolling file logs in the container Lost with the pod; fill the writable layer JSON console / OpenTelemetry
5 Operability No health endpoints Kubernetes cannot tell ready from broken /health/ready and /health/live with probes

The rewrite

See the code example: options bound from IConfiguration (Key Vault for the key), Blob Storage with server-generated names, an async worker on PeriodicTimer honouring cancellation, stdout logging and health endpoints.

How I'd close the review

  • Blocking: 1 (rotate the key today, regardless of the PR), 4, 3, 6/8.
  • Suggested in this PR: 7, options pattern, stdout logging, health endpoints.
  • Automation so it doesn't recur: secret scanning in the pipeline (GitHub secret scanning or gitleaks), Roslyn analysers (CA2016 forward the CancellationToken, VSTHRD002/CA1849 for sync-over-async), and an admission policy requiring readOnlyRootFilesystem and probes, which makes findings 2, 3 and 4 fail fast in test.

Production example

A service like this lost user uploads on every deploy, roughly 40 files a week, before anyone noticed, and the rotated key had been in the registry for months. After the rewrite, deploys lost nothing, shutdown took about 2 seconds instead of being SIGKILLed at 30, and a read-only root file system policy caught two similar services in test.

🔍 What the interviewer is checking

Checks whether the candidate reviews code against how containers actually behave and ranks findings by real-world impact.

Green flags

  • Flags the baked-in secret first and asks for rotation, not just relocation
  • Explains why local disk is lost and not shared, and proposes Blob Storage / Redis
  • Spots the blocking loop, Thread.Sleep, .Result and ignored token, and rewrites with PeriodicTimer
  • Closes with blocking vs suggested comments and automation (secret scanning, analysers, read-only root FS)

Red flags

  • Starts with style or logging
  • Suggests a PersistentVolume for scaled-out uploads
  • Misses the path traversal through FileName

📚 Learn in depth

1. The container file system

+---------------------------+  <- writable layer (copy-on-write), deleted with the container
| /app/uploads/report.pdf   |
| /app/data/cache.db        |
| /app/logs/app-2026...log  |
+---------------------------+
| image layer: app files    |  <- read-only, shared, includes config.json + API key
| image layer: aspnet base  |
+---------------------------+

Everything the app writes goes to the writable layer, which belongs to one container on one node. Kubernetes recreates containers on deploys, crashes, OOM kills, node drains and rescheduling, so writes there are temporary by design. Volumes (emptyDir) live as long as the pod; only a PersistentVolume or an external service outlives it, and a ReadWriteOnce volume cannot be shared across replicas anyway.

2. Why secrets in images are permanent

Image layers are content-addressed and immutable. Even if a later layer deletes config.json, the earlier layer still contains it, and docker history / docker save exposes it. Registries replicate images, nodes cache them and CI logs may print build context. The only real fix is rotation plus never building secrets into images.

3. Why the worker ignores SIGTERM and wastes a thread

The ExecuteAsync here never awaits anything: it runs while (true) with .Result and Thread.Sleep. Before .NET 10, BackgroundService.StartAsync ran ExecuteAsync synchronously up to its first incomplete await, so a loop like this never returned and blocked host start-up entirely (Kestrel never started listening). .NET 10 changed BackgroundService to start ExecuteAsync on a thread-pool thread, so start-up now proceeds, but the loop still permanently holds a thread-pool thread and blocks it again on every .Result and Thread.Sleep, which contributes to thread-pool starvation under load. Interviewers still ask about the older behaviour, and many services run on .NET 8.

On SIGTERM, StopAsync cancels stoppingToken, but the loop never checks it, so the host waits the full ShutdownTimeout (30 s) and the kubelet SIGKILLs the process at the end of the grace period, possibly halfway through a sync.

The fix is an async loop:

using var timer = new PeriodicTimer(interval);
while (await timer.WaitForNextTickAsync(stoppingToken)) { await DoWorkAsync(stoppingToken); }

WaitForNextTickAsync throws OperationCanceledException when the token is cancelled, ending the loop promptly.

4. Why file logs are worse than they look

A rolling file sink inside a pod means: logs disappear when the pod is replaced (often exactly when you need them, after a crash), nothing reaches the central store (Azure Monitor / Application Insights / Container Insights), so you cannot search across replicas or correlate with traces, and synchronous file I/O plus a filling writable layer can eventually cause disk-pressure evictions on the node. Writing JSON to stdout lets the platform collect logs; OpenTelemetry adds trace ids so a log line links to the request that produced it.

5. Health checks and probes

Without endpoints, Kubernetes only knows the process exists. A readiness probe on /health/ready keeps traffic away until the app can serve (and during shutdown); a liveness probe on /health/live with no dependency checks restarts only a hung process; a startup probe protects slow starts. Misconfigured probes (liveness checking a database, too-short timeouts) cause restart storms, so keep liveness trivial.

6. Uploads done properly

  • Never use the client-supplied FileName for a path (path traversal, overwrite); generate a GUID name and keep the original as metadata.
  • Enforce size limits ([RequestSizeLimit], Kestrel MaxRequestBodySize) and content-type checks.
  • Stream to Blob Storage with UploadAsync(stream) rather than buffering whole files in memory.
  • For large files, issue a short-lived user delegation SAS so the client uploads directly to Blob Storage.

7. Making the platform catch it

Setting readOnlyRootFilesystem: true in the pod security context turns silent data loss into an immediate IOException in test. Combined with emptyDir mounted at /tmp for genuine scratch space, it is one of the cheapest guardrails available.

Try it yourself

  1. Build an image with a secret in a layer, delete it in a later layer, then find it with docker save | tar -x and inspect the layers.
  2. Run the original worker in a container and time docker stop: it takes the full timeout.
  3. Replace the loop with PeriodicTimer and the token and time docker stop again.
  4. Run the container with --read-only --tmpfs /tmp and see which writes fail.
  5. Upload a file named ../../app/config.json to the original endpoint in a test container and see what happens.
  6. Target .NET 8 and then .NET 10 with the original worker and compare whether Kestrel starts listening.

💻 Code

The rewrite: validated options from IConfiguration (Key Vault for the key), Blob Storage uploads, a cancellable worker, stdout logs and health endpoints.

// Program.cs (.NET 10)
using Azure.Identity;
using Azure.Storage.Blobs;
using System.ComponentModel.DataAnnotations;

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

// Settings from env vars; the API key from Key Vault secret "Partner--ApiKey". Nothing secret in the image.
if (builder.Configuration["KeyVault:Uri"] is { } vaultUri)
    builder.Configuration.AddAzureKeyVault(new Uri(vaultUri), credential);

builder.Services.AddOptions<PartnerOptions>()
    .BindConfiguration(PartnerOptions.Section)
    .ValidateDataAnnotations()
    .ValidateOnStart();

// Logs as an event stream on stdout.
builder.Logging.ClearProviders();
builder.Logging.AddJsonConsole();

// State lives outside the container.
builder.Services.AddSingleton(new BlobServiceClient(new Uri(builder.Configuration["Storage:BlobEndpoint"]!), credential));
builder.Services.AddStackExchangeRedisCache(o => o.Configuration = builder.Configuration.GetConnectionString("Redis"));

builder.Services.AddHttpClient<PartnerClient>().AddStandardResilienceHandler();
builder.Services.AddHostedService<SyncWorker>();
builder.Services.AddHealthChecks();

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

app.MapPost("/upload", async (IFormFile file, BlobServiceClient blobs, CancellationToken ct) =>
{
    if (file.Length is 0 or > 20 * 1024 * 1024) return Results.BadRequest("File must be 1 byte to 20 MB.");

    var name = $"{Guid.NewGuid():N}{Path.GetExtension(file.FileName)}"; // never trust the client's file name
    var blob = blobs.GetBlobContainerClient("uploads").GetBlobClient(name);
    await using var stream = file.OpenReadStream();
    await blob.UploadAsync(stream, overwrite: false, ct);
    return Results.Created($"/files/{name}", new { name });
}); // antiforgery stays on for browser clients; use token auth for API clients

app.Run();

public sealed record PartnerOptions
{
    public const string Section = "Partner";
    [Required, Url] public string BaseUrl { get; init; } = "";
    [Required] public string ApiKey { get; init; } = "";
    public TimeSpan Interval { get; init; } = TimeSpan.FromMinutes(1);
}

public sealed class PartnerClient(HttpClient http, Microsoft.Extensions.Options.IOptionsMonitor<PartnerOptions> options)
{
    public async Task<string> GetUpdatesAsync(CancellationToken ct)
    {
        var o = options.CurrentValue;
        using var request = new HttpRequestMessage(HttpMethod.Get, new Uri(new Uri(o.BaseUrl), "updates"));
        request.Headers.Add("X-Api-Key", o.ApiKey); // per request, not DefaultRequestHeaders in a loop
        using var response = await http.SendAsync(request, ct);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync(ct);
    }
}

public sealed class SyncWorker(PartnerClient partner, Microsoft.Extensions.Options.IOptions<PartnerOptions> options,
    ILogger<SyncWorker> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(options.Value.Interval);
        try
        {
            do
            {
                try { _ = await partner.GetUpdatesAsync(stoppingToken); }
                catch (HttpRequestException ex) { logger.LogWarning(ex, "Partner sync failed; will retry next tick"); }
            }
            while (await timer.WaitForNextTickAsync(stoppingToken)); // returns promptly when SIGTERM cancels the token
        }
        catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
        {
            logger.LogInformation("Sync worker stopping");
        }
    }
}
# Pod security context that makes local-disk writes fail fast in test
securityContext:
  runAsNonRoot: true
  readOnlyRootFilesystem: true
volumeMounts:
  - { name: tmp, mountPath: /tmp }
volumes:
  - { name: tmp, emptyDir: {} }

⚠ Common mistakes

  • Mistake: Approving because "it works in the container locally". Why it is wrong: Locally there is one container that never restarts; in Kubernetes pods are recreated constantly and run as several replicas. Instead: Review against what the platform will do: restart, reschedule, scale, SIGTERM.
  • Mistake: Asking only to move the API key into an environment variable. Why it is wrong: The key is already in image layers and git history, and env vars still leak. Instead: Rotate the key, load it from Key Vault with managed identity, and remove it from the repo.
  • Mistake: Suggesting a PersistentVolume to fix the uploads. Why it is wrong: ReadWriteOnce volumes do not share across replicas, and shared file volumes add latency and locking problems. Instead: Use Blob Storage for files and Redis for shared cache.
  • Mistake: Fixing the worker with Task.Run(() => loop) but still ignoring the token. Why it is wrong: Start-up no longer blocks, but shutdown still waits out the timeout and SIGKILLs the work. Instead: Use an async loop with PeriodicTimer and pass stoppingToken everywhere.
  • Mistake: Ranking findings in file order or by style. Why it is wrong: The author spends time on log configuration while the leaked key stays live. Instead: Rank by severity: security, data loss, stalls, then design and diagnostics.
  • Mistake: Leaving the review as comments only. Why it is wrong: The same mistakes come back in the next service. Instead: Add secret scanning, cancellation analysers and a read-only root file system policy.
  • Mistake: Using the client's FileName when saving uploads. Why it is wrong: It enables path traversal and overwriting other users' files. Instead: Generate server-side names and keep the original as metadata.

🏛 Senior insight: trade-offs

This review is really one principle applied five times: a container holds code, not data, secrets or long-lived work. The senior contribution is ranking by blast radius (a leaked key and lost customer files outrank a log sink) and then making the platform enforce the principle so reviewers don't have to: readOnlyRootFilesystem, secret scanning and analysers catch most of these automatically.

Fix for local state When it fits Cost When not to
Blob Storage Uploads, generated files Network latency, SDK Tiny scratch files: use /tmp on emptyDir
Redis (IDistributedCache) Shared cache, session Another dependency Per-instance cache is fine: use IMemoryCache
PersistentVolume Single-replica stateful workloads (rare for APIs) Pinned to a zone/node, no sharing Scaled-out web APIs
Azure Files (RWX) Legacy apps needing a shared folder Latency, locking, SMB/NFS quirks New code

Measure the outcome: time from SIGTERM to exit (should be seconds), number of secrets found by scanning (zero), and files lost per deploy (zero).

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the Dockerfile or Kubernetes manifest Why: Checks they can review container images and Deployments for security and reliability.
    How to answer

    I rank by blast radius. Blocking first: the database password in a plain env var in Git (rotate it now, then use Workload Identity with Entra authentication to Azure SQL, or Key Vault); running as root on the SDK image (huge attack surface, compilers and a shell for an attacker: multi-stage build, chiseled runtime, runAsNonRoot).

    Then reliability: :latest (you can't tell what's running or roll back: use version or SHA tags), no probes (traffic hits unready pods, hung pods never restart), no requests or limits (noisy neighbours, evictions, and .NET sizing itself to the whole node), one replica (downtime on every deploy).

    Then diagnostics and polish: exec-form entry point for SIGTERM, .dockerignore, labels. I close with policy so the cluster rejects these by default.

  2. When: Candidate mentions moving the API key to Key Vault Why: Checks they know how secrets reach IConfiguration and how rotation works.
    How to answer

    I split settings from secrets. Non-secret settings that vary by environment come from environment variables (Orders__TimeoutSeconds) or, when many services share them, Azure App Configuration with labels per environment and feature flags. Secrets live in Azure Key Vault and reach the app either through the AddAzureKeyVault configuration provider, through Key Vault references resolved by App Service, Container Apps or App Configuration, or as files mounted by Kubernetes or the Secrets Store CSI driver and read with AddKeyPerFile. The app authenticates with managed identity, so there is no bootstrap secret. All of them land in IConfiguration, so code just binds options.

    The trade-off is refresh: IOptions<T> is fixed at start-up, so anything that rotates needs IOptionsMonitor<T> and a reload interval, or a restart.

  3. When: Candidate mentions SIGTERM or the stopping token Why: Checks they understand the full shutdown sequence and how to size timeouts.
    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.

🛠 Real-world problems: how you handle them

Uploads lost on every deploy, key leaked in the registry
Situation
A document-intake service in .NET deployed to AKS with [3] replicas; customers uploaded identity documents that were processed later by a background sync. Personal information subject to the Privacy Act 1988.
Signals
Support tickets about uploaded documents that "disappeared", clustered after deploys; intermittent 404s when processing picked up a file on a different replica; pods taking the full 30-second grace period to stop, with SIGKILL in `kubectl describe pod` events.
Investigation
Matched missing files to the replica that received them using Application Insights `cloud_RoleInstance`, and to pod restart times from `kubectl get events`. Read the code and Dockerfile in review and found local disk writes, the SQLite cache and the worker loop ignoring the token. A registry scan found the partner API key in an image layer.
Resolution
Immediate: rotated the partner key, scaled to one replica and paused deploys to stop losses. Real fix: uploads to Blob Storage with server-generated names, the key in Key Vault via managed identity, cache in Redis, the worker rewritten on `PeriodicTimer` with the stopping token, stdout logging and health probes. Assessed the exposure of the leaked key and documents under the Notifiable Data Breaches scheme with the privacy officer.
Prevention
Pod security policy requiring `readOnlyRootFilesystem`, secret scanning in CI and on the registry, analysers for cancellation and sync-over-async, and a checklist item for state and shutdown in code review.

How to tell it (STAR)

**S:** We had a document-intake service on AKS with [3] replicas, and customers reported uploads vanishing after deploys. **T:** I was asked to review the service and stop the losses. **A:** I matched missing files to replicas and restart times, then reviewed the code and found uploads and a SQLite cache on container disk, a partner key baked into the image and a worker that ignored SIGTERM. I had the key rotated the same day, then moved files to Blob Storage, the key to Key Vault with managed identity, and rewrote the worker to honour cancellation. I added a read-only root file system policy and secret scanning so the platform would catch this next time. **R:** Lost uploads went from about [40] a week to [zero], shutdown dropped from 30 seconds to about [2], and the policy caught [two] similar services in test.

More in Cloud-Native Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me