skip to content

How do you write a custom IHealthCheck in ASP.NET Core 10, and what does the health check service report when it throws or overruns its timeout?

level: middleimportance: should knowfreq 48%

answer

  1. one method returning Task<HealthCheckResult>
  2. context.Registration.FailureStatus
  3. own DI scope, run concurrently
  4. exception -> FailureStatus plus message
  5. timeout is cooperative, default infinite

basics

~10 s

Implement IHealthCheck.CheckHealthAsync(HealthCheckContext, CancellationToken) to return HealthCheckResult.Healthy, Degraded or Unhealthy, and register it with AddCheck<T>(name, failureStatus, tags, timeout). A thrown exception or an honoured timeout is recorded as the registration's FailureStatus.

solid answer

~40 s

A custom check is a class implementing `IHealthCheck`, whose single method `CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken)` returns `Task<HealthCheckResult>`. It builds the result with `HealthCheckResult.Healthy(...)`, `Degraded(...)` or `Unhealthy(...)`, optionally with a description, an exception and a `Data` dictionary, and it can return `context.Registration.FailureStatus` so the registering code picks the severity. I register it with `AddCheck<SensorFeedHealthCheck>("sensor-feed", failureStatus: HealthStatus.Unhealthy, tags: ["ready"], timeout: TimeSpan.FromSeconds(3))`. The service runs each check in its own DI scope, concurrently with the others. If the check throws, the entry gets the registration's `FailureStatus` with the exception's message. The timeout defaults to infinite and is cooperative: it cancels the token, and only a check that honours the token is reported as a timeout.

code

csharp · 23 lines
csharp
using Microsoft.Extensions.Diagnostics.HealthChecks;

public sealed class SensorFeedHealthCheck(ISensorFeedStatus feed) : IHealthCheck
{
    public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        var age = DateTimeOffset.UtcNow - feed.LastReadingAt;
        var data = new Dictionary<string, object> { ["lastReadingAgeSeconds"] = age.TotalSeconds };

        if (age < TimeSpan.FromMinutes(2))
            return Task.FromResult(HealthCheckResult.Healthy("Sensor readings are current.", data));
        if (age < TimeSpan.FromMinutes(10))
            return Task.FromResult(HealthCheckResult.Degraded("Sensor readings are delayed.", data: data));

        return Task.FromResult(new HealthCheckResult(
            context.Registration.FailureStatus, "No sensor readings for 10 minutes.", data: data));
    }
}

// Program.cs
builder.Services.AddHealthChecks().AddCheck<SensorFeedHealthCheck>(
    "sensor-feed", failureStatus: HealthStatus.Unhealthy, tags: ["ready"], timeout: TimeSpan.FromSeconds(3));

go deeper

for a junior

Know the shape: implement IHealthCheck.CheckHealthAsync, return HealthCheckResult.Healthy, Degraded or Unhealthy, and register it with AddCheck<T> and a unique name.

for a middle

Explain FailureStatus, the per-check DI scope, concurrent execution, and what the report records when a check throws.

for a senior

Explain why the timeout is cooperative, how ActivatorUtilities decides the check's lifetime, and how to avoid a slow check stalling every probe.

for a principal

Decide which failures should be Degraded versus Unhealthy across services, so the platform's reaction matches the business impact.

## The contract `IHealthCheck` lives in `Microsoft.Extensions.Diagnostics.HealthChecks` and has one method: - `Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)` `HealthCheckResult` is a struct with a `Status` (`HealthStatus.Healthy`, `Degraded` or `Unhealthy`), an optional `Description`, an optional `Exception`, and a `Data` dictionary (`IReadOnlyDictionary<string, object>`). Static helpers build it: `HealthCheckResult.Healthy(description, data)`, `HealthCheckResult.Degraded(description, exception, data)`, `HealthCheckResult.Unhealthy(description, exception, data)`. `HealthCheckContext.Registration` gives the check its own registration: `Name`, `Tags`, `Timeout` and **`FailureStatus`**. Returning `new HealthCheckResult(context.Registration.FailureStatus, ...)` instead of hard-coding `Unhealthy` lets whoever registers the check decide whether a failure means "take me out of rotation" or merely "degraded". ## A check for the parking-sensor API The API ingests readings from street sensors. A singleton `ISensorFeedStatus` remembers when the last reading arrived. The check maps the age of that reading to a status: 1. under 2 minutes: `Healthy`; 2. under 10 minutes: `Degraded`, with the age in `Data`; 3. otherwise: the registration's `FailureStatus`. ## Registering it `AddCheck<T>(string name, HealthStatus? failureStatus = null, IEnumerable<string>? tags = null, TimeSpan? timeout = null)`: - `name` must be unique; duplicate names make `HealthCheckService` throw `ArgumentException` when it is first created. - `failureStatus` defaults to `Unhealthy` when omitted. - `tags` feed endpoint predicates. - `timeout` defaults to **infinite** (`Timeout.InfiniteTimeSpan`). How the instance is created matters: `AddCheck<T>` uses `ActivatorUtilities.GetServiceOrCreateInstance<T>` against the check's scope. If `T` is registered in DI, its registered lifetime applies; if not, a **new instance is constructed for every run** with its constructor dependencies resolved from that scope. `AddTypeActivatedCheck<T>(name, args...)` does the same with extra constructor arguments. For trivial checks, `AddCheck(name, () => HealthCheckResult.Healthy())` and `AddAsyncCheck` take a delegate. ## How the service runs checks `DefaultHealthCheckService`, the implementation behind `HealthCheckService`: - creates an **async DI scope per check**, so a scoped `DbContext` or other scoped service is safe inside a check and is disposed afterwards; - starts every selected check with `Task.Run` and awaits them together, so checks run **concurrently**; - wraps each run in a logging scope that names the check. ## What happens when things go wrong | Situation | Entry status | Entry description | |---|---|---| | Check returns a result | the result's `Status` | the result's `Description` | | Check throws (not a cancellation) | registration `FailureStatus` | the exception's `Message` | | Registration `Timeout` elapses and the check observes the token | registration `FailureStatus` | `A timeout occurred while running check.` | | Timeout elapses but the check ignores the token | whatever the check eventually returns | its own description | | The HTTP request itself is aborted | the cancellation propagates; no report | n/a | The timeout is **cooperative**: the service links a `CancellationTokenSource` with `CancelAfter(timeout)` and passes its token in. A check that blocks synchronously, or awaits work without passing the token, keeps the endpoint waiting. ## Delegate checks versus classes | Form | Good for | |---|---| | `AddCheck("self", () => HealthCheckResult.Healthy())` | trivial, dependency-free checks | | `AddAsyncCheck("cache", async ct => ...)` | short async probes written inline | | `AddCheck<T>(name, ...)` | checks with dependencies, logic worth unit-testing, or reuse across services | | `AddTypeActivatedCheck<T>(name, args...)` | one class registered several times with different constructor arguments | ## Unit-testing a check A check is an ordinary class, so it can be tested without a web host: 1. construct it with a fake `ISensorFeedStatus` whose `LastReadingAt` is, say, five minutes ago; 2. build a context: `new HealthCheckContext { Registration = new HealthCheckRegistration("sensor-feed", check, HealthStatus.Unhealthy, null) }`; 3. call `CheckHealthAsync(context)` and assert `Status == HealthStatus.Degraded` and the `Data` value. Repeat with a 15-minute-old reading and a registration whose `FailureStatus` is `Degraded` to prove the severity really comes from the registration. ## Guidelines - Pass `cancellationToken` to every async call in the check. - Keep checks fast; they run on every probe. - Put diagnostic numbers in `Data`, not in the description string. - Do not throw for expected failures; return a result with a clear description. - Remember that **constructing** the check happens before that try/catch: an unresolvable constructor dependency escapes `CheckHealthAsync` and fails the request instead of producing an entry.

  • Why return context.Registration.FailureStatus instead of HealthCheckResult.Unhealthy()?
    It lets the registration decide severity. The same `SensorFeedHealthCheck` can be registered as `Unhealthy` on a service where stale readings must take the pod out of rotation, and as `Degraded` where they should only show on a dashboard. It also matches what the service itself records when the check throws or times out.
  • The check's constructor takes a scoped repository. Is that a captive dependency?
    No, as long as the check itself is not registered as a singleton. When `T` is not registered, `AddCheck<T>` constructs it per run from that run's scope, and the service creates a fresh async scope for each check, so the scoped repository lives exactly as long as one check run.

  • An exception thrown from CheckHealthAsync makes the health endpoint return 500.
  • The registration timeout aborts a check even if it ignores its CancellationToken.
  • AddCheck<T> creates one instance at startup and reuses it for every run.
  • Health checks run one after another, so their durations add up.
  • AddCheck<T> without a timeout argument uses a 30-second timeout.