skip to content

In ASP.NET Core 10, how does IHealthCheckPublisher run health checks without any probe calling, and what do HealthCheckPublisherOptions Delay, Period, Timeout and Predicate control?

level: seniorimportance: nice to knowfreq 20%

answer

  1. a hosted service AddHealthChecks already adds
  2. idle until a publisher is registered
  3. defaults 5 s, 30 s, 30 s
  4. Period must be at least one second
  5. per-registration Delay and Period override

basics

~20 s

With an IHealthCheckPublisher registered, the hosted service AddHealthChecks adds runs the checks on a timer and hands each HealthReport to PublishAsync. Delay (5 s) defers the first run, Period (30 s) spaces runs, Timeout (30 s) bounds one, Predicate picks checks.

solid answer

~40 s

`AddHealthChecks()` also registers `HealthCheckPublisherHostedService`. At startup it looks for `IHealthCheckPublisher` implementations; if there are none, it does nothing. With one registered, for example `AddSingleton<IHealthCheckPublisher, SensorHealthPublisher>()`, it starts timers that run the checks and call `PublishAsync(HealthReport report, CancellationToken)` on every publisher concurrently. `HealthCheckPublisherOptions` controls it: `Delay` (default 5 seconds) before the first run, `Period` (default 30 seconds, at least one second) between runs, `Timeout` (default 30 seconds) for a whole run, checks plus publishers, and `Predicate` to choose which registrations run. A registration's own `Delay` and `Period` override the global ones, and checks with the same pair share a timer. This is how the parking-sensor API raises alerts about a stale sensor feed even when nothing is probing it, at the cost of running the checks a second time.

code

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

public sealed class SensorHealthPublisher(ILogger<SensorHealthPublisher> logger) : IHealthCheckPublisher
{
    public Task PublishAsync(HealthReport report, CancellationToken cancellationToken)
    {
        foreach (var (name, entry) in report.Entries)
        {
            if (entry.Status != HealthStatus.Healthy)
                logger.LogWarning("Health check {Check} is {Status}: {Description}",
                    name, entry.Status, entry.Description);
        }
        return Task.CompletedTask;
    }
}

// Program.cs
builder.Services.AddSingleton<IHealthCheckPublisher, SensorHealthPublisher>();
builder.Services.Configure<HealthCheckPublisherOptions>(o =>
{
    o.Delay = TimeSpan.FromSeconds(10);
    o.Period = TimeSpan.FromMinutes(1);
    o.Predicate = r => r.Tags.Contains("ready");
});

go deeper

for a junior

Know that IHealthCheckPublisher lets an app push its health results on a schedule instead of waiting for a probe.

for a middle

Explain the hosted service that AddHealthChecks adds, that it is idle without publishers, and the Delay, Period, Timeout and Predicate defaults.

for a senior

Account for checks running twice, per-registration schedules splitting reports, and the shared run timeout when designing an alerting publisher.

for a principal

Decide whether health alerting should come from in-process publishers or from external probing and metrics, given duplicate load and what each can observe.

## Push instead of pull A health endpoint is **pull**: something must call it. `IHealthCheckPublisher` adds **push**: the app runs its own checks on a schedule and hands the result to code you write, which can log it, update a metric or notify someone. The interface is one method: - `Task PublishAsync(HealthReport report, CancellationToken cancellationToken)` `HealthReport` carries the overall `Status`, the `TotalDuration` and `Entries`, a dictionary of `HealthReportEntry` values keyed by check name, each with `Status`, `Description`, `Duration`, `Exception`, `Data` and `Tags`. ## Who runs the publishers `AddHealthChecks()` registers two things: the `HealthCheckService` singleton and a hosted service, `HealthCheckPublisherHostedService`, added with `TryAddEnumerable` so it is registered once. - At `StartAsync`, the hosted service collects every registered `IHealthCheckPublisher`. **If there are none, it returns immediately** and never starts a timer, so apps that only use endpoints pay nothing. - With at least one publisher, it starts one `System.Threading.Timer` per distinct `(Delay, Period)` pair. - Each tick runs the selected checks through the same `HealthCheckService` the endpoints use, then calls every publisher's `PublishAsync` **concurrently** and waits for all of them. - On shutdown the timers stop and an in-flight run is cancelled. ## The options and their defaults | `HealthCheckPublisherOptions` member | Default | Meaning | |---|---|---| | `Delay` | 5 seconds | wait before the first run; must not be infinite | | `Period` | 30 seconds | interval between runs; must be at least one second and not infinite (`ArgumentException` otherwise) | | `Timeout` | 30 seconds | bound for one run, checks and publishers together | | `Predicate` | `null` (all checks) | `Func<HealthCheckRegistration, bool>` choosing checks for publishing | When the timeout fires while a publisher is still working, the publisher sees its token cancelled and the hosted service logs an error, event id 104 `HealthCheckPublisherTimeout`. An exception in one publisher is logged; the other publishers in that run still complete, and the next run happens on schedule. ## Per-check schedules `HealthCheckRegistration` has nullable **`Delay`** and **`Period`** properties. When set, they override the global options for that check. The hosted service groups registrations by their effective `(Delay, Period)` pair and runs each group on its own timer, so a cheap sensor-feed check can be published every 10 seconds while the database check runs every 2 minutes. The publisher's `Predicate` is applied inside each group. ## A publisher for the parking-sensor API The operations team wants a warning in the logs, and therefore in alerting, whenever the sensor feed goes stale, even at night when no deployment or probe change is happening: 1. Implement `IHealthCheckPublisher` and log each non-healthy entry with its name, status and description. 2. Register it as a singleton: `builder.Services.AddSingleton<IHealthCheckPublisher, SensorHealthPublisher>()`. 3. Configure `HealthCheckPublisherOptions` with a `Predicate` selecting the `ready` checks and a one-minute `Period`. ## Publisher versus probe | | Health endpoint (`MapHealthChecks`) | Publisher (`IHealthCheckPublisher`) | |---|---|---| | Trigger | an incoming HTTP request | a timer inside the app | | Who sees the result | the caller, as a status code and body | your `PublishAsync` code | | Check selection | `HealthCheckOptions.Predicate` | `HealthCheckPublisherOptions.Predicate` | | Bound | the request's abort token plus registration timeouts | `HealthCheckPublisherOptions.Timeout` plus registration timeouts | | Typical use | orchestrator and load-balancer decisions | logs, metrics and alerts from inside the process | The two complement each other: probes drive routing decisions, while a publisher records history and can alert on states that never cross a probe's threshold, such as a check that has been `Degraded` for an hour. ## Costs and traps - **Checks run twice.** Probes and the publisher each run the checks independently; a database check probed every 10 seconds by three pods and published every 30 seconds by each pod runs more often than either source alone suggests. - **Endpoint predicates do not apply.** Only `HealthCheckPublisherOptions.Predicate` filters what is published. - **Keep `PublishAsync` short and cancellable.** It shares the run's timeout with the checks. - **One report per group.** With per-check periods, a publisher receives several smaller reports rather than one report of everything.

  • An app calls AddHealthChecks but registers no IHealthCheckPublisher. Does the background service still run the checks every 30 seconds?
    No. `HealthCheckPublisherHostedService` is registered, but its `StartAsync` returns immediately when the publisher list is empty and never creates a timer. Checks then run only when an endpoint such as `MapHealthChecks` is called.
  • How would you publish the database check less often than the sensor-feed check?
    Set `Period` (and optionally `Delay`) on the database check's `HealthCheckRegistration`, for example through `Configure<HealthCheckServiceOptions>` by name. Registrations with different effective `(Delay, Period)` pairs get separate timers, so each publisher receives a database-only report on the slower schedule.

A health endpoint is a clinic that only learns how you are when you walk in; a publisher is a wearable that takes your pulse every 30 seconds and messages you when it drops. Wear the device and visit the clinic, and your pulse is simply measured twice.

  • Registering AddHealthChecks always runs every check every 30 seconds in the background.
  • MapHealthChecks endpoint predicates also decide what the publisher reports.
  • HealthCheckPublisherOptions.Period can be set to 500 milliseconds for faster alerts.
  • Publishers are called one after another, so a slow one delays the rest.
  • The publisher reuses the last probe's result instead of running the checks.