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.
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.
"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.jsonthat 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/uploadsand 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 anIMemoryCachethat is honestly per instance.Third is shutdown: the
BackgroundServiceloops withwhile (true)andThread.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 andawait Task.Delay(..., token). After that, the non-blocking items: the custom config loader bypassesIConfiguration, 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."
// 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-..."
| # | 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 |
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.
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.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.
Checks whether the candidate reviews code against how containers actually behave and ranks findings by real-world impact.
Green flags
Thread.Sleep, .Result and ignored token, and rewrites with PeriodicTimerRed flags
FileName+---------------------------+ <- 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.
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.
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.
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.
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.
FileName for a path (path traversal, overwrite); generate a GUID name and keep the original as metadata.[RequestSizeLimit], Kestrel MaxRequestBodySize) and content-type checks.UploadAsync(stream) rather than buffering whole files in memory.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.
docker save | tar -x and inspect the layers.docker stop: it takes the full timeout.PeriodicTimer and the token and time docker stop again.--read-only --tmpfs /tmp and see which writes fail.../../app/config.json to the original endpoint in a test container and see what happens.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: {} }
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.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.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).
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.
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.
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.
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.
Last updated 23 Nov 2026.