Step 10 — Add health checks and outbox cleanup
What you'll do: add liveness and readiness endpoints that check PostgreSQL, RabbitMQ and the outbox lag, and a background job that deletes published outbox rows after a retention period.
Liveness and readiness
An orchestrator (Kubernetes, Azure Container Apps, App Service) asks each instance two questions:
| Probe | Question | If it fails |
|---|---|---|
| Liveness | Is the process alive and answering? | The instance is restarted. |
| Readiness | Can it do useful work right now? | It gets no traffic until it passes again. |
Keep them apart. If liveness checked the database, a database outage would make the orchestrator restart every instance in a loop, which fixes nothing.
The outbox adds a third concern. While RabbitMQ is down the API still answers 201 to every order, so nothing looks wrong, yet no other service hears about any of them. The outbox lag (the age of the oldest message still waiting) makes that visible.
Steps
Add the EF Core health check package to Directory.Packages.props and Orders.Api.csproj:
xml<PackageVersion Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="10.0.15" />Write a RabbitMQ check that reuses the app's connection, RabbitMqHealthCheck.cs:
csharpvar connection = await rabbit.GetAsync(cancellationToken); return connection.IsOpen ? HealthCheckResult.Healthy("Connected to RabbitMQ.") : HealthCheckResult.Unhealthy("The RabbitMQ connection is closed; the client is trying to recover it.");Community packages such as
AspNetCore.HealthChecks.Rabbitmqexist, but they open their own connection. Checking the publisher's own connection reports what the publisher actually sees.Write the outbox lag check, OutboxLagHealthCheck.cs:
csharpvar oldestPending = await db.OutboxMessages .Where(m => m.ProcessedAt == null && m.Attempts < settings.MaxAttempts) .MinAsync(m => (DateTimeOffset?)m.OccurredAt, cancellationToken); var givenUp = await db.OutboxMessages .CountAsync(m => m.ProcessedAt == null && m.Attempts >= settings.MaxAttempts, cancellationToken); var lag = oldestPending is { } oldest ? clock.GetUtcNow() - oldest : TimeSpan.Zero; if (lag > settings.LagUnhealthyThreshold) { return new HealthCheckResult(context.Registration.FailureStatus, $"Oldest pending outbox message is {lag:g} old.", data: data); } if (lag > settings.LagDegradedThreshold || givenUp > 0) { return HealthCheckResult.Degraded($"Outbox lag {lag:g}, {givenUp} message(s) given up.", data: data); }Add the cleanup job, OutboxCleanup.cs, another
BackgroundServiceon aPeriodicTimer:csharpvar cutoff = clock.GetUtcNow() - options.Value.Retention; var deleted = await db.OutboxMessages .Where(m => m.ProcessedAt != null && m.ProcessedAt < cutoff) .ExecuteDeleteAsync(stoppingToken);Add the settings to OutboxOptions.cs and appsettings.json:
Setting Default Meaning LagDegradedThreshold00:00:30Outbox check says Degraded when the oldest pending message is older. LagUnhealthyThreshold00:05:00Outbox check returns its failure status when older still. Retention7.00:00:00Published rows older than this are deleted. CleanupInterval01:00:00How often the cleanup job runs. Register the checks and map the endpoints in Program.cs:
csharpbuilder.Services.AddHostedService<OutboxCleanup>(); builder.Services.AddHealthChecks() .AddDbContextCheck<OrdersDbContext>("postgresql", tags: ["ready"]) .AddCheck<RabbitMqHealthCheck>("rabbitmq", tags: ["ready"]) .AddCheck<OutboxLagHealthCheck>("outbox", failureStatus: HealthStatus.Degraded, tags: ["ready"]);csharpapp.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false }); app.MapHealthChecks("/health/ready", new HealthCheckOptions { Predicate = check => check.Tags.Contains("ready"), ResponseWriter = HealthResponseWriter.WriteAsync, });HealthResponseWriter.cs writes each check's status, description and data as JSON, without exception details.
Check it works
Start the worker and the API. To see the cleanup without waiting a week, override two settings on the command line (anything after -- is configuration):
dotnet build OutboxInbox.slnx -warnaserror
dotnet run --project src/Shipping.Worker
dotnet run --project src/Orders.Api -- --Outbox:Retention=00:00:30 --Outbox:CleanupInterval=00:00:05curl -i localhost:5080/health/liveHTTP/1.1 200 OK
Content-Type: text/plain
Healthycurl localhost:5080/health/ready{"status":"Healthy","totalDuration":"00:00:00.1373360","checks":{
"postgresql":{"status":"Healthy","description":null,"data":{}},
"rabbitmq":{"status":"Healthy","description":"Connected to RabbitMQ.","data":{}},
"outbox":{"status":"Healthy","description":"Outbox lag 0:00:00.","data":{"lagSeconds":0,"givenUp":0}}}}Within five seconds the cleanup job removes everything published more than 30 seconds ago:
info: Orders.Api.Outbox.OutboxCleanup[0]
Deleted 307 processed outbox messages older than 11/27/2026 01:24:36 +00:00Now stop the broker and place an order:
docker compose stop rabbitmq
curl -X POST localhost:5080/orders -H 'content-type: application/json' \
-d '{"customerEmail":"alex@contoso.com","items":[{"sku":"BOOK-1","quantity":1}]}'The order is still accepted (201): that is the point of the outbox. But readiness now fails:
HTTP/1.1 503 Service Unavailable
{"status":"Unhealthy","checks":{
"postgresql":{"status":"Healthy"},
"rabbitmq":{"status":"Unhealthy","description":"The RabbitMQ connection is closed; the client is trying to recover it."},
"outbox":{"status":"Healthy","description":"Outbox lag 0:00:05.199656.","data":{"lagSeconds":5.2,"givenUp":0}}}}Wait half a minute and ask again. The order's event is still waiting, and the outbox check now says so:
"outbox":{"status":"Degraded","description":"Outbox lag 0:00:43.027798, 0 message(s) given up.","data":{"lagSeconds":43,"givenUp":0}}Start RabbitMQ again with docker compose start rabbitmq. The client reconnects on its own, the waiting message is published, and readiness returns to Healthy.
Why it works
Predicate = _ => false runs no checks at all, so /health/live answers 200 Healthy as long as the process can serve HTTP. /health/ready runs only the checks tagged ready.
Status codes. By default Healthy and Degraded answer 200, and Unhealthy answers 503. The outbox check is registered with failureStatus: HealthStatus.Degraded, so it can never make readiness fail on its own. That is deliberate: the outbox lag is the same on every instance, and failing readiness everywhere would take the whole API out of the load balancer, which stops new orders too. Degraded still shows up in the JSON for your monitoring and alerts. The RabbitMQ check does fail readiness; whether you want that depends on whether an instance without a broker should still take orders. With the outbox it can, so you could tag that check differently too.
Lag, not count. A queue of 1,000 pending messages can be fine (a burst) and a single message can be a problem (stuck for an hour). The age of the oldest pending message measures what users feel: how late other services are.
Retention. Published rows are history: useful to answer "did we send that event?", but they make the table and its indexes bigger. ExecuteDeleteAsync sends one DELETE ... WHERE to the database without loading rows. On a very large table, delete in batches (for example LIMIT 10000 in raw SQL) so one statement does not hold locks for long. Running the job in every instance is safe: deleting rows that are already gone does nothing.
The whole picture. With this step the guide is complete. One event's journey, with every safety net from the ten steps:
The inbox grows too. inbox_messages in the Shipping database needs the same treatment, with one rule: keep ids at least as long as a duplicate could still arrive (the outbox retry window plus any time a message can sit in a queue or dead-letter queue).