Skip to content
← All posts
· Delta1 Labs LicensingKeyright

Hot-reloading license upgrades at runtime

A customer renews or upgrades mid-shift and your service keeps serving the old plan until someone restarts it. This post wires Keyright license state into .NET's change-token and IOptionsMonitor infrastructure so a widened plan fans out to every gate, worker, and cached policy the moment the SDK sees it — no restart, no polling in your gate code — while keeping time-based expiry a per-call decision, not a config change.

A customer upgrades from Standard to Pro at 2pm, or renews a lapsed subscription, or buys the scheduled-export add-on. Their license is now wider than it was this morning. Your service, running since the last deploy, does not know. It keeps returning 402 on the export endpoint the customer just paid for, keeps the background worker idle, keeps enforcing the old seat cap — until someone restarts the process and it reads the license fresh at startup. “Buy the upgrade, then restart the app” is a bad sentence to put in a purchase confirmation email.

The usual fix is to re-read the license on every request, and for a gate decision that is correct: you want expiry picked up the instant it happens, so the authorization check should evaluate the license per call. But not every consumer of a license is request-scoped. A background worker that should spin up when the customer gains an entitlement has no request to hang a check on. A connection pool sized to a licensed seat limit is built once. A compiled authorization policy is cached. These are push consumers — they need to be told, once, when the plan changes — and polling the license from each of them is the wrong shape.

Key takeaway: Model the license plan — what the license grants — as an IOptionsMonitor<LicensePlan>, rebuilt from the SDK’s offline Validate(). Drive its change token from a background RefreshAsync loop that signals only when the plan actually widens or narrows. Then every push consumer subscribes with OnChange and reacts to a renewal or upgrade with no restart, while request-scoped gates keep evaluating expiry per call. The grant is hot-reloaded config; whether the grant is active now stays a per-call decision.

The two clocks in a license

A license carries two kinds of state that change on completely different clocks. The grant — edition, the set of entitlements, numeric limits — changes only when the lease changes: a renewal, an upgrade, a revocation. That is a discrete, rare event. The activation at an instant — is this entitlement past its expiry right now, is the lease inside its grace window — changes continuously with the wall clock and is re-derived on every call.

Conflating them is the mistake. If you reload the whole license as config on a timer, you pick up expiry late (whenever the timer next ticks) and you reload constantly for nothing. If you only ever read per request, your non-request consumers never learn about an upgrade. The clean design routes each clock to the infrastructure built for it: the discrete grant goes through .NET’s change-token machinery, and the continuous activation stays a per-call Validate().

Refresh loopRefreshAsync ~15 minLicenseChangeSignalfires on plan changeIOptionsMonitor<LicensePlan>recompute + swap cacheWorker supervisorSeat-limited poolFeature gatesOnChange fan-out — no restartPer-call Validate()expiry at now — bypasses tokentime clock

Modelling the grant as options

LicensePlan is a plain options class describing what the license grants. It deliberately holds no per-instant state — no “is active now” flags — because those belong on the other clock.

public sealed class LicensePlan
{
    public string Edition { get; set; } = "Community";
    public IReadOnlySet<string> Entitlements { get; set; } = ImmutableHashSet<string>.Empty;
    public IReadOnlyDictionary<string, int> Limits { get; set; } = ImmutableDictionary<string, int>.Empty;

    public bool Grants(string entitlement) => Entitlements.Contains(entitlement);
    public int Limit(string name) => Limits.TryGetValue(name, out var v) ? v : 0;
}

An IConfigureOptions<LicensePlan> builds it from the SDK’s offline Validate(). This is the factory IOptionsMonitor runs on first access and re-runs whenever the plan’s change token fires.

public sealed class ConfigureLicensePlan(IKeyrightClient client) : IConfigureOptions<LicensePlan>
{
    public void Configure(LicensePlan plan)
    {
        LicenseInfo info = client.Validate();          // local, offline, no network
        plan.Edition      = info.Edition;
        plan.Entitlements = info.Entitlements.ToImmutableHashSet();
        plan.Limits       = info.Limits;
    }
}

Note what Configure reads: the set of entitlements the license carries and the numeric limits, not whether each one is unexpired at this second. The grant is the ceiling.

The change token that fires on a plan change

The piece that makes IOptionsMonitor reactive is an IOptionsChangeTokenSource<LicensePlan>. Its job is to hand out an IChangeToken that the monitor registers on; when we fire that token, the monitor drops its cached LicensePlan, rebuilds it with the factory, and invokes every OnChange listener. We back the token with a swappable CancellationTokenSource.

public sealed class LicenseChangeSignal
{
    private CancellationTokenSource _cts = new();

    public IChangeToken Token => new CancellationChangeToken(_cts.Token);

    public void Signal()
    {
        // Install a fresh source for the NEXT token, then cancel the one consumers hold.
        CancellationTokenSource stale = Interlocked.Exchange(ref _cts, new CancellationTokenSource());
        stale.Cancel();      // fires every token already handed out
        stale.Dispose();
    }
}

public sealed class LicensePlanChangeTokenSource(LicenseChangeSignal signal)
    : IOptionsChangeTokenSource<LicensePlan>
{
    public string Name => Options.DefaultName;
    public IChangeToken GetChangeToken() => signal.Token;
}

The ordering in Signal() is the subtle part. The monitor is holding a token created over the current _cts. We swap a brand-new source into _cts first, then cancel the old one — firing the token the monitor holds. The monitor reacts by calling GetChangeToken() again, which now returns a token over the new source, so it is re-armed for the next change. This is the same shape the framework’s own ConfigurationChangeTokenSource uses for appsettings.json reloads.

Wire it all up at startup:

builder.Services.AddSingleton<LicenseChangeSignal>();
builder.Services.AddSingleton<IConfigureOptions<LicensePlan>, ConfigureLicensePlan>();
builder.Services.AddSingleton<IOptionsChangeTokenSource<LicensePlan>, LicensePlanChangeTokenSource>();
builder.Services.AddOptions<LicensePlan>();   // enables IOptionsMonitor<LicensePlan>

Signalling only on a real change

The background loop is the only part that talks to the network. It refreshes the lease on an interval and signals the token only when the plan fingerprint actually moves — otherwise every refresh would needlessly rebuild the options and wake every subscriber.

public sealed class LicenseRefreshLoop(
    IKeyrightClient client, LicenseChangeSignal signal, ILogger<LicenseRefreshLoop> log)
    : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        string current = Fingerprint(client.Validate());
        using var timer = new PeriodicTimer(TimeSpan.FromMinutes(15));

        while (await timer.WaitForNextTickAsync(ct))
        {
            await client.RefreshAsync(ct);         // online if reachable, else cached lease
            string next = Fingerprint(client.Validate());
            if (next == current) continue;         // same grant — do not disturb anyone

            current = next;
            signal.Signal();                       // ← one call fans out to every consumer
            log.LogInformation("License plan changed; reloaded in place without restart.");
        }
    }

    static string Fingerprint(LicenseInfo i) =>
        $"{i.Edition}|{string.Join(',', i.Entitlements.Order())}|{i.Limit("seats")}";
}

RefreshAsync degrades gracefully: when the issuing service is briefly unreachable it serves the cached lease, so a network blip never flips the plan. The fingerprint deliberately excludes expiry timestamps — a plan whose only change is “one minute closer to expiry” is not a plan change.

Consuming the hot-reloaded plan

A push consumer subscribes once and converges to whatever plan it is handed. Here a supervisor starts or stops a background export worker as the entitlement comes and goes — the behaviour that makes an upgrade take effect without a restart.

public sealed class ExportWorkerSupervisor : IHostedService
{
    private readonly IDisposable? _subscription;
    private readonly ExportWorker _worker;

    public ExportWorkerSupervisor(IOptionsMonitor<LicensePlan> plan, ExportWorker worker)
    {
        _worker = worker;
        Apply(plan.CurrentValue);                 // initial state at startup
        _subscription = plan.OnChange(Apply);     // every subsequent reload
    }

    private void Apply(LicensePlan plan)          // idempotent: converge, don't toggle
    {
        if (plan.Grants("acme.scheduled-export")) _worker.Enable();
        else                                       _worker.Disable();
    }

    public Task StartAsync(CancellationToken ct) => Task.CompletedTask;
    public Task StopAsync(CancellationToken ct)  { _subscription?.Dispose(); return Task.CompletedTask; }
}

A request-scoped gate reads CurrentValue for the grant but still evaluates expiry per call — this is where the two clocks meet.

public sealed class ExportEndpoint(IOptionsMonitor<LicensePlan> plan, IKeyrightClient license)
{
    public IResult Handle(ExportRequest req)
    {
        // Cheap: does the plan grant this at all? Reloaded in place on upgrade.
        if (!plan.CurrentValue.Grants("acme.export"))
            return Results.StatusCode(StatusCodes.Status402PaymentRequired);

        // Per-call: granted, but is it active right now? Catches expiry to the second.
        if (!license.Validate().IsEnabled("acme.export"))
            return Results.StatusCode(StatusCodes.Status402PaymentRequired);

        return Results.Ok(RunExport(req));
    }
}

If you drop the second check, an entitlement that lapsed at noon would still pass until the next refresh fingerprinted a change — which, for a plain expiry, it never would, because expiry is not a grant change. The grant tells you the ceiling; the per-call Validate() tells you whether you are under it at this instant.

Caveats and when it breaks

Expiry is not a config event. The single most common bug is trying to make the plan reload at the exact second an entitlement expires. It cannot: the change token fires on discrete lease changes, and a steadily-advancing clock produces none. Keep time-based decisions per call.

OnChange can fire more than once. IOptionsMonitor debounces but does not promise exactly-once delivery, and two token sources can fire close together. That is why Apply recomputes desired state from the plan rather than toggling — enabling an already-enabled worker must be a no-op.

Dispose the subscription. OnChange returns an IDisposable; a captured subscription that outlives its target leaks and keeps firing into a dead object. Dispose it in StopAsync or the containing IDisposable.

Scoped options are per-request snapshots. Inject IOptionsMonitor<LicensePlan>, not IOptions<LicensePlan>. IOptions resolves once and never updates; IOptionsSnapshot is scoped and recomputes per request but has no OnChange. Only the monitor gives you both a current value and the push callback.

A downgrade is a plan change too. Signalling fires on any fingerprint move, including a revocation that collapses the license to Community Edition. That is correct and desirable — the same machinery that lights up a paid feature on upgrade turns it off on revocation, in place, without waiting for a restart. Make sure your Apply handlers fail closed on the narrowed plan.

Wiring license state into the options system is a small amount of code that buys a real property: a customer who upgrades sees the upgrade take effect in the running process, and a customer whose license lapses loses access on the same path, with the discrete grant on the change-token clock and the continuous activation on the per-call clock. For the capability model the plan carries, see entitlements and feature flags; for keeping the signature verification off the hot path underneath all of this, see caching license verification; and for how a renewal reaches the SDK in the first place, see converting a trial to a paid license.

Try Nebula.NET

Harden your .NET code in minutes — start with the free edition.