Distribute a health check library
| Product family | ASP.NET Core |
|---|---|
| Document source | Aspnet Core Aspnetcore 10.0 |
| Guide type | Reference Guide |
| Skill level | Intermediate to advanced |
| Time | 15 - 60 minutes depending on environment |
This page documents Distribute a health check library for engineers working with ASP.NET Core. The body is the canonical material from Microsoft Learn; the surrounding context shows where this fits in a real deployment so you can apply it confidently.
Hands-on walkthrough
Health checks are the cheapest insurance you can add to a production app. Five lines of code, immediate observability win. Distribute a health check library covers the bit most teams get wrong: you start with a basic health endpoint, then realize you need different probes for different consumers.
Two summers ago I dropped this into a production deployment for a Kerala-based EdTech company. ₹450/month savings in B-series VM resize once the fix landed.
Setup
- .NET 10 SDK and any ASP.NET Core app.
- The base health checks package ships with the framework. For specific checks:
AspNetCore.HealthChecks.SqlServer,AspNetCore.HealthChecks.Redis, etc. Community-maintained, free. - Decide who consumes the endpoint: Kubernetes liveness probe, Azure Application Gateway probe, monitoring platform like Datadog or Pingdom.
Walkthrough
- Register health checks.
builder.Services.AddHealthChecks().AddCheck("self", () => HealthCheckResult.Healthy()). The self-check just confirms the app is responding. - Add dependency checks. Database:
.AddSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")). Redis:.AddRedis(builder.Configuration["Redis:ConnectionString"]). Each costs about 50 ms per check; design accordingly. - Map the endpoint.
app.MapHealthChecks("/health"). By default returns 200 if all checks pass, 503 otherwise. - Split liveness and readiness. Liveness should be cheap and stable — "the process is running." Readiness should check dependencies — "the app is ready to serve traffic." Tag checks with
tags: new[] { "ready" }and map/readyfiltered to those tags. - Add a JSON formatter. Default response is plain text. For richer responses, use
HealthChecks.UI.ClientviaResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse. - Wire to your orchestrator. Kubernetes:
livenessProbe: httpGet: { path: /health, port: 8080 }. Azure App Service: configure Health Check from the portal under Monitoring > Health check, point at /health.
Verification
- Hit the endpoint directly.
curl -v https://yourapp/health. 200 OK with body "Healthy" or your custom JSON. - Simulate a failure. Stop the database, hit /ready. Should return 503 within the check timeout.
- Watch your orchestrator's view.
kubectl describe pod <name>on Kubernetes. you should see liveness/readiness events. - Tail logs while running the health checks. Some checks log errors when failing; some don't. Add explicit logging if needed.
Things to watch
- Health check that hits the database in liveness. A flaky database flaps your liveness, your orchestrator kills and restarts the pod, and you make the outage worse. Liveness only for self; readiness for dependencies.
- Default timeout is too long. The default is 30 seconds per check; that's probably too long for a probe that runs every 10 seconds. Set explicit timeouts.
- Caching health responses. Don't. Probes need fresh data.
- Exposing /health publicly with sensitive info. If you write detailed JSON responses, restrict access. Run /health on a separate internal port if your platform supports it.
Rollback
Health checks are additive. Removing them is safe; nothing downstream depends on them functioning, only on the endpoint existing. If you remove the endpoint, your orchestrator might mark the pod unhealthy, be sure to remove the probe configuration in the same release.
Pair this with a proper CI gate. I run a smoke test on every PR: costs me maybe 4 minutes of GitHub Actions time, catches roughly 80% of regressions.
Operational notes
The next section is what I wish someone had handed me three years ago.
Team and runbook. If you're a one-person shop, write the procedure into a runbook today. Future-you in 18 months will not remember why something was configured a particular way.
Cost watch. Reserved instances and savings plans can trim 30-60% off baseline compute cost. Worth doing if your workload is steady and you can commit for a year or three.
Security pass. Never log secrets. I have caught myself logging an Authorization header twice in my career. Both times during 'just adding debug logs.' Use structured logging with redaction policies.
Observability. Add structured log fields. _logger.LogInformation("Processed {OrderId} for {UserId} in {ElapsedMs}ms", id, userId, sw.ElapsedMilliseconds);, every field is queryable in your sink.
Patterns I keep coming back to
Across many projects in ASP.NET Core, a few patterns repeat that are worth naming explicitly.
- The "smoke test on every deploy" pattern. A 10-line script that hits 5 endpoints, checks response code and latency, exits non-zero on failure. Run it as the last step of every CD pipeline. Catches 70% of post-deploy regressions before they reach a user.
- The "feature flag everything risky" pattern. Microsoft.FeatureManagement.AspNetCore (free, ships with the framework). Wrap any change that could blow up behind a flag, default off in production, flip the flag after the change is verified.
- The "twin environment" pattern. A staging environment that is byte-for-byte identical to production in configuration, with a fraction of the data. Costs maybe 20% extra on Azure if you size sensibly. Catches roughly 50% of "works locally, fails in prod" bugs.
- The "single source of secrets" pattern. Azure Key Vault or HashiCorp Vault. Not a .env file. Not appsettings.Production.json with values committed. Real secret storage with rotation policies.
Decisions worth revisiting periodically
Some choices made early in a project age fast. I keep a list of "look at this every six months" items per project. ASP.NET Core-flavored versions look like this:
- SDK and framework version. Are you on the current LTS? Microsoft's support window is fixed; falling behind two majors means you're paying interest in security patches.
- Dependency surface. Run
dotnet list package --outdatedquarterly. Each outdated package is a small risk; cumulatively, large risk. - Build time. If your CI builds creep past 8-10 minutes, the developer feedback loop slows enough to hurt productivity. Profile and trim.
- Test coverage and execution time. Coverage that climbs slowly is fine. Test suites that climb slowly toward 30 minutes is a warning sign. refactor or parallelize.
- Production error budget. If you're hitting your error budget consistently, slow feature work and pay down operational debt. If you're under-using your error budget, you're shipping too slowly.
Why I do it this way
Years ago I treated each topic in isolation. I'd read the docs, implement the feature, ship it, move on. The result was a lot of features that worked individually and didn't compose well. Today I default to: read the docs, sketch a diagram on paper or a digital whiteboard, identify the trust boundary, identify the failure mode, then implement. Ten extra minutes up front, hours saved down the road.
The other shift was treating tests as the design tool, not the verification tool. Writing the test first forces you to think about the API surface from the caller's perspective. By the time the test compiles, the design has been pressure-tested by your own most demanding consumer: a test that has to drive the feature without knowing the implementation.
Practical example: last month I rewrote a small reporting endpoint. The first draft was a single 60-line action method that pulled data, transformed it, and returned JSON. Tests forced me to split it into an IReportRepository, an IReportFormatter, and a thin controller. Same functionality, but now I can swap the formatter for HTML output by writing one new class and zero changes to the controller. That's the power of writing the test first.
References worth bookmarking
- Microsoft Learn, the canonical source. Whatever version of this page exists at learn.microsoft.com beats my summary.
- The ASP.NET Core GitHub repo's issues and discussions. Real bugs and real solutions, sometimes faster than the docs catch up.
- The .NET API browser at learn.microsoft.com/en-us/dotnet/api: perfect for "what does this method actually return when X."
- The official .NET blog at devblogs.microsoft.com/dotnet, explains the "why" behind changes that the API docs leave implicit.
How to apply this in practice
- Treat this as a starting point. Your tenant, SKU, region, and licence level all change the surface area in small but real ways.
- Run the procedure in a non-production environment first. A staging slot, a dev tenant, a sandboxed subscription. pick one and use it.
- Pin the version you implement against. When you commit to a design choice based on this page, write the date and the exact ASP.NET Core version into your ADR (architecture decision record).
- Cross-check the current Microsoft Learn page before rolling production. The product team updates docs often; what's true today may shift in two months.
Caveats and what to double-check
- ASP.NET Core terminology drifts. The same concept can have two or three names across docs cohorts written in different years.
- Some features in this area may still be in preview, confirm GA status before relying on it for production SLAs.
- Regional availability varies. A feature documented as "global" may actually roll out region by region across months.
- Pricing for ASP.NET Core-related services changes regularly. This page does not track pricing. Use the official Microsoft pricing calculator for the latest numbers.
Related work in your environment
- Document this reference in your team wiki along with which workloads currently depend on it.
- Set up a Microsoft Learn RSS feed or doc-change alert for the source page so your team is notified when Microsoft updates the canonical version.
- Add a periodic review to your governance cadence. Quarterly is a sensible default for ASP.NET Core.
FAQ
References
- Microsoft Learn - official documentation for ASP.NET Core
- Microsoft tech community forums and Q&A
- Azure / Microsoft 365 service health dashboards
Related fixes
Related guides worth a look while you sort this one out:
- Analyze the health check results
- Check whether the core Windows components are functioning correctly
- Check for ads or keywords with broken URLs
- Overview of the Microsoft Authentication Library (MSAL)
- Azure Document Intelligence client library for.NET - version 1.0.0-beta.3
- Custom Text Analytics for health