DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Edited on Originally published at delta1labs.com

Licensing a headless .NET worker service

A desktop app with an invalid license can pop a dialog: "Your license has expired — click here to renew." A BackgroundService running as a Windows service or inside a container has no one to show that dialog to. It starts unattended at boot, restarts unattended after a crash, and runs for weeks. If licensing is an afterthought, you end up with one of two failures: a worker that happily processes work forever because nothing ever checks, or a worker that refuses to start — and keeps crash-looping — the first time the license server is briefly unreachable.

Neither is acceptable. The real question is: how do you enforce a license in a process with no UI, no interactive user, and an uptime measured in weeks, while tolerating the transient outages that are normal for anything networked?

The answer rests on one property: the license is a signed artifact the SDK verifies locally. Verification is offline — a public key embedded in your binary proves the license is authentic and reads its expiry and entitlements without any call to the issuing service. The server is consulted only to learn about new facts: a renewal, or a revocation. That split is what lets a worker survive an outage, and it shapes the whole design.

The shape of the problem

Three checkpoints matter, and they are not the same check:

  1. Startup gate — refuse to start a clearly unlicensed process, but do it from the cached license, offline, so a network hiccup never blocks boot.
  2. Periodic re-validation — while the process runs for days, a license can expire or be revoked. A timer inside the run loop re-checks on an interval you choose deliberately.
  3. Surface — nobody is watching a console, so license state has to leave the process some other way: a structured log line and a health check an orchestrator can read.


License lifecycle in a headless worker






The worker verifies a cached signed license offline at startup, re-validates on a timer inside the run loop, and routes the result into one of three branches — all surfaced through logs and a health check rather than a dialog.

Wiring it into the generic host

Everything hangs off Host.CreateApplicationBuilder. Register the license client as a singleton (it caches the parsed license), add the worker, and add a health check that reads the same cached state.

var builder = Host.CreateApplicationBuilder(args);

builder.Services.AddSingleton<ILicenseClient>(sp =>
    new LicenseClient(new LicenseOptions
    {
        // the signed license file shipped/provisioned with the service
        LicensePath = builder.Configuration["License:Path"]!,
        // bounded offline grace once the cached license is past expiry
        OfflineGrace = TimeSpan.FromDays(3),
        // how often the run loop re-checks
        RevalidateInterval = TimeSpan.FromHours(6),
    }));

builder.Services.AddHostedService<LicensedWorker>();

builder.Services.AddHealthChecks()
    .AddCheck<LicenseHealthCheck>("license");

await builder.Build().RunAsync();
Enter fullscreen mode Exit fullscreen mode

The startup gate — without blocking the host

IHostedService.StartAsync is the first checkpoint, and it is also the first trap. If you await client.ValidateAsync() against the issuing service here, every cold start now depends on the network being up at that instant — a transient outage turns into a crash loop, because the host treats a throw from StartAsync as a failed start.

The fix follows directly from offline verification: at startup, verify the cached license synchronously. That requires no network — it is a signature check and an expiry comparison against the embedded public key.

public sealed class LicensedWorker : BackgroundService
{
    private readonly ILicenseClient _license;
    private readonly ILogger<LicensedWorker> _log;

    public LicensedWorker(ILicenseClient license, ILogger<LicensedWorker> log)
        => (_license, _log) = (license, log);

    public override async Task StartAsync(CancellationToken ct)
    {
        // offline: verify signature + read claims from the cached license
        LicenseState state = _license.VerifyCached();

        if (!state.IsValid && !state.IsInGrace)
        {
            _log.LogCritical("License invalid at startup: {Reason}. Refusing to start.",
                state.Reason);
            throw new InvalidOperationException("No valid Keyright license.");
        }

        _log.LogInformation(
            "License OK. Tier={Tier} Expires={Expiry:o} Entitlements={Count}",
            state.Tier, state.ExpiresUtc, state.Entitlements.Count);

        await base.StartAsync(ct);
    }
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Note what we do not do: there is no await on a server round-trip. VerifyCached() is pure local verification. A freshly provisioned worker with a genuinely missing or corrupt license file still refuses to start — which is correct — but a worker that holds a valid cached license boots instantly even if the issuing service is unreachable.

The run loop — re-validate on a timer

A worker that boots once and never re-checks cannot react to a revocation or an expiry that happens on day nine of a long run. ExecuteAsync owns the long-lived loop, so the periodic re-validation lives there, driven by a PeriodicTimer.

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    using var timer = new PeriodicTimer(_license.RevalidateInterval);

    do
    {
        // the online refresh — allowed to fail without killing the worker
        LicenseState state = await _license.ValidateAsync(stoppingToken);

        if (state.IsValid)
        {
            if (state.HasEntitlement("worker.process"))
                await ProcessBatchAsync(stoppingToken);
            else
                _log.LogWarning("Entitlement worker.process absent; skipping batch.");
        }
        else if (state.IsInGrace)
        {
            _log.LogWarning(
                "License unverified; running on offline grace, {Days:F1} day(s) left.",
                state.GraceRemaining.TotalDays);
            await ProcessBatchAsync(stoppingToken);   // policy: keep working, bounded
        }
        else
        {
            // fail closed: cache is past the grace window, or revoked
            _log.LogCritical("License {Reason}; stopping work.", state.Reason);
            break;
        }
    }
    while (await timer.WaitForNextTickAsync(stoppingToken));
}
Enter fullscreen mode Exit fullscreen mode

ValidateAsync is the one call allowed to touch the network, and it is written to degrade, not throw: if the server is unreachable it returns the cached state, which is still signature-valid until its own expiry. Only when the cached license is itself past expiry — and past the bounded grace window — or has been revoked does the worker fail closed and stop processing.

Surfacing state with a health check

A break out of the loop stops the work, but an orchestrator still sees a "running" process. Give it something to read. The health check reports the same cached LicenseState, so a Kubernetes liveness/readiness probe or a Windows service monitor can act on it.

public sealed class LicenseHealthCheck(ILicenseClient license) : IHealthCheck
{
    public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext ctx, CancellationToken ct = default)
    {
        LicenseState s = license.VerifyCached();  // offline, cheap
        var data = new Dictionary<string, object>
        {
            ["tier"] = s.Tier,
            ["expiresUtc"] = s.ExpiresUtc,
            ["graceDaysLeft"] = s.GraceRemaining.TotalDays,
        };

        return Task.FromResult(s switch
        {
            { IsValid: true }  => HealthCheckResult.Healthy("licensed", data),
            { IsInGrace: true } => HealthCheckResult.Degraded("offline grace", data: data),
            _ => HealthCheckResult.Unhealthy(s.Reason, data: data),
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

Now the three states map onto the three health results an operator already understands — Healthy, Degraded, Unhealthy — and the structured log gives the audit trail nobody was present to see.

Caveats and when it breaks

Fail-closed vs. fail-open is your decision, not the SDK's. A worker that gates access to protected functionality should fail closed the instant the license is invalid. A batch job whose only downside is deferred billing may rightly prefer the grace window so a license-server blip never takes down a production pipeline. The code above shows the grace branch; deleting it is a one-line change to fail closed. Decide deliberately and write it down.

A grace window anchored to the wall clock can be cheated. Rolling the system clock back makes "three days" last forever. Anchor "last known good" to the latest timestamp you have ever observed — persisted across restarts — and compute remaining grace against that, not against DateTime.Now alone. It is not tamper-proof, but it stops the trivial attack.

Revocation is only as fresh as your interval. A revoked license keeps working until the next ValidateAsync tick. A six-hour interval means up to six hours of exposure. Shorten it for sensitive workloads; do not set it so low that you hammer the service on every container in a large fleet.

Never block StartAsync on the network. It is worth repeating because it is the single most common bug in this pattern. Startup reads the cache; the loop reconciles with the server. Invert that and your service crash-loops the first time the network is slow.

Takeaway

Licensing a headless worker is not about finding a place to show a dialog — there isn't one. It is about moving the checks to where they belong: an offline, cached-license gate at startup that never blocks on the network, a deliberate re-validation timer in the run loop, and a health check plus structured logs as the only surface a process with no screen has. Because Keyright licenses are signed and verified locally, a worker survives the transient outages that are normal in production instead of crash-looping on them — and you still decide, explicitly, whether an expired cache means keep working briefly or stop now.

The free Community Edition is enough to build and test this end to end. See Keyright and the documentation.

Top comments (0)