Your Pod Says It’s Ready. Is It Lying?
Liveness vs Readiness Health Checks for .NET on AKS
By Abdul Hafeez Syed, Principal Architect, One Technology Services · November 2026
The outage that every dashboard called healthy
A pod that says “Ready” before it can do real work will drop real customer requests, and Kubernetes will never know.
I have seen this happen on enterprise AKS platforms running dozens of .NET microservices: APIs behind Azure API Management, background workers reading from Service Bus, and data landing in Azure SQL and Cosmos DB. A new release rolls out. Every pod shows Running and 1/1 Ready. The AKS portal is green. Yet for the first two or three minutes, users get 500 errors and timeouts, and messages pile up in dead-letter queues.
Nothing was wrong with the cluster. The problem was in the code. The pods told Kubernetes they were ready, and Kubernetes believed them.
In this post I will show you why this happens, the difference between liveness, readiness and startup checks, and exactly how to build them the right way in C# with ASP.NET Core on AKS.
Why “Ready” often means “the process started”
Kubernetes only knows what your app tells it. If you set no readiness probe, a pod is marked ready as soon as its container starts. If your probe hits an endpoint that always returns 200 OK, the result is the same.
These are the patterns I see most often in .NET code reviews:
- No probes at all. Traffic is sent the moment the container process starts, long before the app has warmed up.
- A “hello world” health endpoint.
app.MapGet("/health", () => "OK")proves that Kestrel is running. It says nothing about the database, the cache or the message broker. - The same endpoint for liveness and readiness. When a dependency like Azure SQL has a short outage, every pod fails liveness, Kubernetes restarts them all at once, and a 30-second blip becomes a 10-minute outage.
- Warm-up work that is not tracked. Loading config from Key Vault, filling a cache or running EF Core migrations happens in the background, but the pod is already taking traffic.
- Workers with no HTTP endpoint. A Service Bus consumer can be stuck for hours, and Kubernetes keeps it alive because no one ever asks it how it is doing.
- No graceful shutdown. During a rolling update, the pod is killed while it still has requests in flight.
The fix is not “add a probe.” The fix is to give each probe a clear, separate job.
Liveness, readiness and startup: three different questions
Each probe asks your app one question, and Kubernetes takes a different action for each answer.
| Probe | The question it asks | If it fails, Kubernetes will… | What it should check |
|---|---|---|---|
| Startup | “Have you finished booting?” | Wait. Liveness and readiness are paused until it passes. If it never passes, restart the container. | Warm-up work: config loaded, cache primed, migrations done |
| Readiness | “Can you serve traffic right now?” | Remove the pod from the Service endpoints. No restart. | Critical dependencies the request path needs: SQL, Cosmos DB, Redis, Service Bus |
| Liveness | “Are you stuck or broken beyond repair?” | Kill and restart the container. | Only the process itself: deadlocks, a stalled worker loop. Never external dependencies. |
The golden rule I give every team: liveness checks the app, readiness checks the app plus what it depends on. If your database is down, restarting your pod will not fix the database. It will only add a restart storm on top of the outage.
A useful way to remember it: readiness is a traffic light, liveness is a defibrillator. You want the traffic light to change often. You want the defibrillator used rarely, and only when the heart has truly stopped.
Building it in C# with ASP.NET Core
ASP.NET Core has health checks built in. The trick is to use tags so one app can answer three different questions on three different endpoints. The examples below target .NET 8 and later.
Step 1: Track warm-up and shutdown state
A small singleton holds the pod’s state. Warm-up code marks it ready when done, and shutdown code marks it as draining.
public sealed class PodState
{
private volatile bool _warmedUp;
private volatile bool _draining;
public bool WarmedUp => _warmedUp;
public bool Draining => _draining;
public void MarkWarmedUp() => _warmedUp = true;
public void MarkDraining() => _draining = true;
}
Step 2: Do the warm-up work in the background
Heavy start-up work goes in a hosted service. The pod is not marked ready until this finishes.
public sealed class WarmUpService(
PodState state,
IServiceScopeFactory scopes,
ILogger<WarmUpService> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var scope = scopes.CreateScope();
// Example: prime a reference-data cache before taking traffic
var cache = scope.ServiceProvider.GetRequiredService<IReferenceDataCache>();
await cache.LoadAsync(stoppingToken);
state.MarkWarmedUp();
logger.LogInformation("Warm-up finished. Pod can accept traffic.");
}
}
Step 3: Write the custom health checks
The startup check reports warm-up. The draining check fails readiness the moment shutdown starts. The Cosmos DB check proves the account is reachable.
public sealed class StartupHealthCheck(PodState state) : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context, CancellationToken ct = default) =>
Task.FromResult(state.WarmedUp
? HealthCheckResult.Healthy("Warm-up complete.")
: HealthCheckResult.Unhealthy("Still warming up."));
}
public sealed class DrainingHealthCheck(PodState state) : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context, CancellationToken ct = default) =>
Task.FromResult(state.Draining
? HealthCheckResult.Unhealthy("Shutting down. Stop sending traffic.")
: HealthCheckResult.Healthy());
}
public sealed class CosmosDbHealthCheck(CosmosClient client) : IHealthCheck
{
public async Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context, CancellationToken ct = default)
{
try
{
await client.ReadAccountAsync();
return HealthCheckResult.Healthy();
}
catch (Exception ex)
{
return new HealthCheckResult(
context.Registration.FailureStatus, "Cosmos DB is unreachable.", ex);
}
}
}
Step 4: Register checks with tags and map three endpoints
This is where liveness and readiness are split. Notice that the database checks are tagged ready only. They are never part of liveness.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<PodState>();
builder.Services.AddHostedService<WarmUpService>();
builder.Services.AddHealthChecks()
// Liveness: is the process itself responsive?
.AddCheck("self", () => HealthCheckResult.Healthy(), tags: ["live"])
// Startup: has warm-up finished?
.AddCheck<StartupHealthCheck>("warm-up", tags: ["startup", "ready"])
// Readiness: can we serve a real request right now?
.AddCheck<DrainingHealthCheck>("draining", tags: ["ready"])
.AddDbContextCheck<OrdersDbContext>("azure-sql", tags: ["ready"])
.AddCheck<CosmosDbHealthCheck>("cosmos-db", tags: ["ready"]);
var app = builder.Build();
// Flip readiness to failing as soon as SIGTERM arrives
app.Lifetime.ApplicationStopping.Register(
() => app.Services.GetRequiredService<PodState>().MarkDraining());
app.MapHealthChecks("/health/startup", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("startup")
});
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("ready")
});
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("live")
});
app.MapControllers();
app.Run();
AddDbContextCheck comes from the Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore package. For Redis, Service Bus and other services, the open-source AspNetCore.HealthChecks.* packages give you ready-made checks.
Step 5: Liveness for background workers
A Service Bus worker can hang without crashing. A heartbeat makes that visible. The worker loop updates a timestamp, and liveness fails if the loop goes quiet.
public sealed class WorkerHeartbeat
{
private long _lastBeatTicks = DateTime.UtcNow.Ticks;
public void Beat() =>
Interlocked.Exchange(ref _lastBeatTicks, DateTime.UtcNow.Ticks);
public TimeSpan SinceLastBeat =>
DateTime.UtcNow - new DateTime(Interlocked.Read(ref _lastBeatTicks), DateTimeKind.Utc);
}
public sealed class WorkerLivenessCheck(WorkerHeartbeat heartbeat) : IHealthCheck
{
private static readonly TimeSpan MaxSilence = TimeSpan.FromMinutes(2);
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context, CancellationToken ct = default) =>
Task.FromResult(heartbeat.SinceLastBeat < MaxSilence
? HealthCheckResult.Healthy()
: HealthCheckResult.Unhealthy(
$"Worker loop silent for {heartbeat.SinceLastBeat.TotalSeconds:N0}s."));
}
public sealed class OrderEventsWorker(
ServiceBusReceiver receiver,
WorkerHeartbeat heartbeat) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// Beat on every loop, even when the queue is empty
heartbeat.Beat();
var messages = await receiver.ReceiveMessagesAsync(
maxMessages: 20,
maxWaitTime: TimeSpan.FromSeconds(30),
cancellationToken: stoppingToken);
foreach (var message in messages)
{
await ProcessAsync(message, stoppingToken);
await receiver.CompleteMessageAsync(message, stoppingToken);
}
}
}
private Task ProcessAsync(ServiceBusReceivedMessage message, CancellationToken ct)
=> Task.CompletedTask; // your business logic
}
Register WorkerLivenessCheck with the live tag. Give the worker a tiny web host with only the health endpoints, so Kubernetes has something to probe.
Wiring the probes into your AKS deployment
Now point each Kubernetes probe at its own endpoint. .NET 8 and later container images listen on port 8080 by default.
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api
spec:
replicas: 3
strategy:
rollingUpdate:
maxUnavailable: 0 # never drop below full capacity during a release
maxSurge: 1
selector:
matchLabels:
app: orders-api
template:
metadata:
labels:
app: orders-api
spec:
terminationGracePeriodSeconds: 45
containers:
- name: orders-api
image: myregistry.azurecr.io/orders-api:1.4.2
ports:
- containerPort: 8080
startupProbe:
httpGet:
path: /health/startup
port: 8080
periodSeconds: 5
failureThreshold: 24 # allows up to 2 minutes to warm up
readinessProbe:
httpGet:
path: /health/ready
port: 8080
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 3
livenessProbe:
httpGet:
path: /health/live
port: 8080
periodSeconds: 15
timeoutSeconds: 3
failureThreshold: 3
lifecycle:
preStop:
sleep:
seconds: 10 # give load balancers time to stop routing here
A few choices here matter more than they look:
- The startup probe protects slow starters. Without it, you would have to set a long initialDelaySeconds on liveness, which slows down detection of real hangs for the life of the pod.
- Liveness is gentle. Three failures 15 seconds apart means a pod must be truly stuck for about 45 seconds before it is restarted.
- maxUnavailable: 0 means a new pod must pass readiness before an old one is removed. This only works if readiness tells the truth.
- The preStop sleep uses the built-in sleep action in Kubernetes 1.30 and later. It works with chiseled .NET images that have no shell, where sleep as a command would fail.
Shutting down without dropping requests
Readiness is just as important when a pod is leaving as when it is arriving. During a rolling update, this is the order you want:
- Kubernetes sends SIGTERM and starts removing the pod from Service endpoints.
- The preStop sleep holds the pod for 10 seconds while that removal spreads to kube-proxy and the load balancer.
- ApplicationStopping fires, PodState is marked draining, and readiness fails, so no new traffic arrives.
- ASP.NET Core finishes in-flight requests and the worker finishes its current batch.
- The process exits well inside the 45-second grace period.
Make sure the .NET host waits long enough. In .NET 8 and later the default shutdown timeout is 30 seconds, but it is worth setting on purpose:
builder.Services.Configure<HostOptions>(options =>
{
options.ShutdownTimeout = TimeSpan.FromSeconds(30);
});
Mistakes I still see in production
- Checking the database in liveness. One SQL failover restarts every pod in the cluster.
- Slow, heavy readiness checks. A probe that runs a big query every 10 seconds on every pod becomes its own load problem. Keep checks to a cheap SELECT 1-style call.
- Ignoring the cancellation token. If a check hangs past the probe’s timeoutSeconds, Kubernetes counts it as a failure anyway.
- Exposing detailed health output publicly. Keep /health/* inside the cluster and do not publish it through API Management or Application Gateway.
- Failing readiness on non-critical dependencies. If the app can still serve most requests without Redis, make Redis report Degraded, not Unhealthy, and log it instead of pulling the pod.
A quick checklist for your next AKS release
- Every service has separate /health/live, /health/ready and /health/startup endpoints
- Liveness checks only the process, never databases or brokers
- Readiness checks every dependency a real request need
- Warm-up work is tracked and gates the startup probe
- Background workers have a heartbeat-based liveness check
- Readiness fails as soon as shutdown begins, with a preStop sleep
- maxUnavailable: 0 on rolling updates for customer-facing APIs
- Health endpoints are not exposed outside the cluster
The bigger lesson
Health checks are not a box to tick in a Helm chart. They are a contract between your code and the platform. When that contract is honest, AKS does what it was built to do: route around trouble, heal stuck pods and release new versions with zero downtime. When it is not, the platform will confidently send your customers to a pod that cannot help them.
The best cloud architecture is not only about picking the right Azure services. It is about making sure the code running on them tells the truth.
About the author
Abdul Hafeez Syed is an enterprise solutions and delivery architect who leads One Technology Services, his independent Azure consulting practice and a Microsoft AI Cloud Partner. He has designed and delivered event-driven .NET platforms on AKS, Azure Functions, Service Bus, Cosmos DB and Azure SQL for large automotive enterprises, taking architectures from whiteboard to review-board approval to production.
Want help getting this right? I help .NET teams build reliable AKS platforms, from probe design and zero-downtime releases to full Azure architecture reviews. I work with teams as a consultant or in a full-time architecture role. Get in touch or connect with me on LinkedIn.