Lesson 9 of 9 · 27m
Operating .NET Services: Health, Telemetry, Shutdown, and systemd
Ship services operators can run: structured logs, useful health checks, OpenTelemetry signals, graceful shutdown, and honest process supervision.
The first production deployment is the beginning of the debugging relationship, not the end of development. When a service degrades, operators do not need cleverness; they need evidence. Which dependency is slow, which instance is shutting down, whether the process is ready for traffic, and whether the last deploy changed the error shape. Observability is not a dashboard purchase. It is engineering work embedded in the service.
Health checks answer different questions
Liveness means the process is alive enough to keep running. Readiness means it can safely receive traffic. Startup means slow initialization is still progressing. Do not collapse them into one endpoint:
builder.Services.AddHealthChecks()
.AddCheck("self", () => HealthCheckResult.Healthy(), tags: ["live"])
.AddNpgSql(builder.Configuration.GetConnectionString("Orders")!, name: "orders-db", tags: ["ready"]);
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("live")
});
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("ready")
});A database failure may mean not ready, but restarting the process will not repair the database. If liveness includes every dependency, orchestration can restart healthy processes in a loop during an external outage.
Logs are events, not prose dumps
Use structured logging with stable names and bounded cardinality:
logger.LogInformation("Order {OrderId} created for customer {CustomerId} with {LineCount} lines",
order.Id, order.CustomerId, order.Lines.Count);Do not log authorization headers, tokens, passwords, full payment payloads, or raw connection strings. Be careful with IDs at massive scale: high cardinality is useful in traces but can destroy naive metrics and log indexing budgets. Logs, traces, and metrics have different jobs.
OpenTelemetry is worth doing deliberately
ASP.NET Core and HttpClient instrumentation give immediate distributed visibility:
dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Instrumentation.AspNetCore
dotnet add package OpenTelemetry.Instrumentation.HttpRegister tracing and metrics with resource names that match deployment reality: service name, version, environment, and instance. Propagate trace context through incoming and outgoing HTTP. Without propagation, every dependency becomes an island and latency analysis turns into archaeology.
Graceful shutdown is part of availability
ASP.NET Core supports application lifetime notifications. Background services should observe cancellation and finish or checkpoint work:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await ProcessBatchAsync(stoppingToken);
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
}
}Configure shutdown timeouts long enough for the real workload, not an arbitrary default. Load balancers must stop sending traffic before the process exits; readiness failing early is often the difference between a clean deploy and dropped requests.
systemd is the production interface on many Linux hosts
A basic unit file makes process behavior explicit:
[Unit]
Description=Order API
After=network-online.target
[Service]
Type=notify
User=orderapi
WorkingDirectory=/opt/order-api
ExecStart=/opt/order-api/OrderApi
Restart=on-failure
RestartSec=5
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=ASPNETCORE_URLS=http://127.0.0.1:8080
[Install]
WantedBy=multi-user.targetType=notify works with modern .NET systemd integration when configured; otherwise use Type=simple honestly. Put the service behind a reverse proxy such as nginx or the platform ingress, use least-privilege users, and persist only explicitly provisioned directories.
Field notes
- Health endpoints are public attack surface. Expose minimal detail externally and reserve dependency detail for protected diagnostics.
- A readiness check that executes expensive queries on every probe can become a self-inflicted denial of service.
- Correlation IDs are not a substitute for trace context. Use W3C
traceparentpropagation where possible. - Restart policies hide crashes; they do not fix them. Alert on restart loops and deploy rollbacks.
Was this lesson helpful?