DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Originally published at delta1labs.com

Draining features on a license downgrade

A subscription renewal fails at 02:00. Your licensing service flips the account from Pro to Community Edition on its next poll. The desktop app — or the worker service — is still running, mid-export, with twelve Pro-only pipelines in flight. What should happen?

Two obvious answers are both wrong. Hard-cutting every Pro feature the instant the new license arrives aborts work the customer legitimately started while still paid, and in a service it fails a batch of requests that were already accepted. Ignoring the change until the next restart leaks a paid capability for hours or days. Neither is defensible.

The real question

License verification is well understood: fetch a signed license, check the signature and expiry, read the entitlements. The hard part of a downgrade is not detecting it — Keyright's SDK already surfaces the new license through IOptionsMonitor<T> the moment it changes. The hard part is reconciling a running process from the old entitlement set to the new one without either breaking in-flight work or over-granting.

Think of it as a state transition, not a check. Each entitlement that shrinks or disappears needs a decision: revoke it immediately, or stop admitting new use and let existing use drain out.

Classifying the delta

Start by diffing two license snapshots. A snapshot is the already-verified, immutable view the SDK hands you — entitlement keys and their quotas. Every entitlement falls into one of three buckets.

public enum EntitlementAction { Keep, RevokeHard, Drain }

public readonly record struct EntitlementDelta(
    string Key, EntitlementAction Action, int? OldQuota, int? NewQuota);

public static IReadOnlyList<EntitlementDelta> Diff(
    LicenseSnapshot current, LicenseSnapshot next)
{
    var deltas = new List<EntitlementDelta>();
    foreach (var e in current.Entitlements)
    {
        if (!next.TryGet(e.Key, out var n))
        {
            // Gone entirely: drain it if it is drainable, otherwise cut it.
            deltas.Add(new(e.Key,
                e.Drainable ? EntitlementAction.Drain : EntitlementAction.RevokeHard,
                e.Quota, null));
        }
        else if (n.Quota < e.Quota)
        {
            // Still present but the ceiling dropped: drain down to the new cap.
            deltas.Add(new(e.Key, EntitlementAction.Drain, e.Quota, n.Quota));
        }
        // Equal or larger quota is an upgrade for that line — nothing to drain.
    }
    return deltas;
}
Enter fullscreen mode Exit fullscreen mode

The Drainable flag lives in your product's entitlement definition, not in the key. A feature that holds a long-lived resource — an open export pipeline, a streaming session — is drainable. A feature that gates a discrete action the user has not yet taken — "may export at all" — is a hard revoke, because there is nothing in flight to protect.

A downgrade is a transition, not a check: each shrunk entitlement is classified, then drained or cut.

The gate you can actually shrink

The draining case hides a sharp edge. The obvious way to cap a concurrent feature is a SemaphoreSlim initialized to the quota. But SemaphoreSlim has no way to lower its maximum — Release only adds permits, and there is no Acquire-without-waiting that permanently removes one. When Pro's twelve pipelines must become Community's two, you cannot take ten permits away from a semaphore while callers hold them.

So the gate is a small counting primitive whose limit is mutable, and lowering the limit below current usage simply stops new admissions until the overcommit drains off:

public sealed class AdjustableConcurrencyGate
{
    private readonly object _sync = new();
    private int _limit;
    private int _inUse;

    public AdjustableConcurrencyGate(int limit) => _limit = limit;

    public bool TryEnter()
    {
        lock (_sync)
        {
            if (_inUse >= _limit) return false;
            _inUse++;
            return true;
        }
    }

    public void Exit()
    {
        lock (_sync)
        {
            if (_inUse > 0) _inUse--;
        }
    }

    // Lowering the limit below _inUse does NOT evict holders. It stops
    // admitting until _inUse drains back under the new limit.
    public void SetLimit(int limit)
    {
        lock (_sync) { _limit = Math.Max(0, limit); }
    }

    public int Overcommit
    {
        get { lock (_sync) { return Math.Max(0, _inUse - _limit); } }
    }
}
Enter fullscreen mode Exit fullscreen mode

Overcommit is the number of leases still running above the new cap. It is a genuinely useful signal: you can surface it in a health check or log it, so support can see that the process is over its new tier but draining rather than violating.

Wiring it to the license change

Keyright delivers license changes through IOptionsMonitor<LicenseSnapshot>. Register a reconciler that owns the gates and reacts to each change by applying the delta:

public sealed class FeatureReconciler : IDisposable
{
    private readonly ConcurrentDictionary<string, AdjustableConcurrencyGate> _gates = new();
    private readonly IDisposable? _subscription;
    private volatile LicenseSnapshot _active;

    public FeatureReconciler(IOptionsMonitor<LicenseSnapshot> monitor)
    {
        _active = monitor.CurrentValue;
        _subscription = monitor.OnChange(Reconcile);
    }

    private void Reconcile(LicenseSnapshot next)
    {
        foreach (var delta in Diff(_active, next))
        {
            switch (delta.Action)
            {
                case EntitlementAction.RevokeHard:
                    _gates.TryRemove(delta.Key, out _);          // next admit fails
                    break;
                case EntitlementAction.Drain:
                    if (_gates.TryGetValue(delta.Key, out var gate))
                        gate.SetLimit(delta.NewQuota ?? 0);       // stop admitting; drain
                    break;
            }
        }
        _active = next;                                           // publish atomically
    }

    public bool TryUseFeature(string key, out IDisposable? lease)
    {
        lease = null;
        var snapshot = _active;                                   // volatile read
        if (!snapshot.Grants(key)) return false;                  // hard-off or revoked
        var gate = _gates.GetOrAdd(key,
            _ => new AdjustableConcurrencyGate(snapshot.QuotaOf(key)));
        if (!gate.TryEnter()) return false;                       // at (or over) cap
        lease = new Lease(gate);
        return true;
    }

    public void Dispose() => _subscription?.Dispose();

    private sealed class Lease(AdjustableConcurrencyGate gate) : IDisposable
    {
        public void Dispose() => gate.Exit();
    }
}
Enter fullscreen mode Exit fullscreen mode

The ordering in Reconcile matters: apply the deltas to the gates before publishing _active = next. A hard-revoked feature then fails its snapshot.Grants(key) check and never reaches the gate, while a drained feature is still granted but its gate already holds the lower limit. Every new call goes through TryUseFeature; callers that already hold a Lease keep running until they dispose it.

Usage at the call site stays ordinary:

if (!reconciler.TryUseFeature("pipeline.parallel_export", out var lease))
    return Results.Problem("Your plan's concurrent-export limit is in use.",
        statusCode: StatusCodes.Status402PaymentRequired);
using (lease) { await RunExportAsync(ct); }
Enter fullscreen mode Exit fullscreen mode

Caveats

You cannot reclaim what you already handed out. A customer with twelve running pipelines keeps all twelve until they finish; only the thirteenth is refused. That is the correct behavior — the work was admitted while the license allowed it — but it means a downgrade is not instantaneous for drainable features, and a pathological long-lived lease can hold overcommit open indefinitely. Put a maximum lease lifetime on anything truly unbounded.

Give drains a reasonable grace rather than racing the clock. If the downgrade is a lapsed renewal that the customer may fix within the hour, a short grace window (covered in the transient-outage grace post) avoids churning features off and back on. And log every reconciliation: which entitlements changed, the overcommit at the moment of the change, and when it drained to zero. During a dispute, that record is the difference between "we cut the customer off" and "we let their in-flight work finish and then enforced the new tier."

A hard legal termination is the exception: classify that entitlement as RevokeHard so the gate disappears immediately, accepting that one already-running operation may complete. If even that is unacceptable, the operation must cooperate — poll the active snapshot at checkpoints and abort itself.

Takeaway

A downgrade is a state transition, not a yes/no check. Diff the old and new snapshots, classify each shrunk entitlement as keep, drain, or hard-revoke, and route draining features through a concurrency gate whose limit you can lower under live load. In-flight work finishes, new use is held to the new tier, and you keep an audit trail that shows you did both. Keyright's SDK hands you the license change; the reconciliation is a few dozen lines on top of it. See the entitlement model and Keyright for where snapshots come from.

Top comments (0)