Enforcing a usage quota per license
Seat counts answer "how many people," and most licensing stops there. But a growing number of products sell something you cannot count by seat: a cap on API calls per month, on records processed, on active projects, on documents rendered. The unit is consumption, not identity, and a seat check says nothing about it. You can staple a maxApiCalls number onto the license, but a number in a payload is not enforcement — enforcement is the machinery that counts real usage against it, honestly, even when the customer is offline and motivated to cheat.
This post is about that machinery for a single quota: express the cap in the signed license, count against it with a local counter that is monotonic and tamper-evident, act differently at a soft warning than at a hard cap, and reconcile with the issuing service without putting it on the critical path of every call.
The real question
A quota looks trivial — increment a counter, compare to a limit. The difficulty is entirely in the adversarial and disconnected cases. The counter lives on a machine the customer controls. They can edit the file it is stored in, copy an old snapshot back over it to erase a month of usage, delete it outright, or roll the clock back to pretend the period never ended. None of that forges a signature, so signature-plus-limit checks sail straight through.
So the question is not "how do I count?" It is: how do I keep a count the customer cannot quietly reset, fast enough to check on every call, and correct even when the machine has been offline for a week?
Expressing the quota in the license
The quota is part of the signed payload, next to the entitlements and expiry, so it cannot be edited after issuance. It names the meter, the ceiling, the period, where the soft warning sits, and what to do at the hard cap.
public sealed record MeterQuota { public required string Meter { get; init; } // "api-calls", "records", "projects" public required long Limit { get; init; } // units allowed per period public required QuotaPeriod Period { get; init; } // Monthly, Daily, Perpetual public double SoftAt { get; init; } = 0.80; // warn at this fraction of Limit public required OnExceed OnExceed { get; init; } // what happens at 100% } public enum OnExceed { Block, Throttle, Overage } OnExceed is the whole policy choice in one enum. Block fails closed — once the cap is hit, further metered operations are denied. Throttle keeps serving but slows down. Overage keeps serving and records the excess for billing. The counter and the thresholds are identical in all three; only the action at the ceiling changes.
A monotonic, sealed local counter
The counter has to satisfy four properties at once: it survives a restart (it is persisted), it only ever moves up within a period (monotonic), an edit to its stored value is detectable (tamper-evident), and rolling the file back to an older copy cannot silently reset it (a server-confirmed floor). Here is the record it persists.
internal sealed record CounterRecord { public required string Meter { get; init; } public required string PeriodId { get; init; } // identifies the active period public required long Used { get; init; } // monotonic within the period public required long Floor { get; init; } // last server-confirmed count public required long Generation { get; init; } // ++ on every sealed write public required byte[] Mac { get; init; } // HMAC over the canonical fields } The Mac is an HMAC-SHA256 over the canonical fields, keyed with a machine-bound key, so a hand-edited Used no longer verifies. Floor is the count the issuing service last confirmed; loading always clamps Used up to it, which is what defeats a rollback to an older file. Reading and sealing look like this.
public CounterRecord Load(string meter) { if (!TryReadFile(meter, out var rec)) return Fresh(meter); // never seen: start this period at 0 // An edited row does not recompute: in fail-closed mode this is tampering. if (!CryptographicOperations.FixedTimeEquals(rec.Mac, Mac(rec))) throw new LicenseTamperException($"usage counter for '{meter}' failed integrity check"); // A restored older snapshot verifies fine, but cannot read below the floor. return rec.Used < rec.Floor ? rec with { Used = rec.Floor } : rec; } private void Seal(CounterRecord rec) { var record = rec with { Mac = Mac(rec) }; AtomicWrite(record); // write temp + File.Move(overwrite): a crash cannot corrupt it } private byte[] Mac(CounterRecord r) { using var h = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, _macKey); h.AppendData(Encoding.UTF8.GetBytes(r.Meter)); h.AppendData(Encoding.UTF8.GetBytes(r.PeriodId)); Span<byte> buf = stackalloc byte[16]; BinaryPrimitives.WriteInt64BigEndian(buf[..8], r.Used); BinaryPrimitives.WriteInt64BigEndian(buf[8..], r.Floor); h.AppendData(buf); return h.GetHashAndReset(); } Recording usage is a locked read-modify-seal. The count only ever grows within a period, so there is no code path that lowers it.
public MeterReading Record(string meter, long amount) { lock (_gate) { var rec = Load(meter); long used = checked(rec.Used + amount); // monotonic: only ever up Seal(rec with { Used = used, Generation = rec.Generation + 1 }); return Evaluate(_quota, used); } } private static MeterReading Evaluate(MeterQuota q, long used) { if (used >= q.Limit) return new(used, q.Limit, QuotaState.AtLimit); if (used >= (long)(q.Limit * q.SoftAt)) return new(used, q.Limit, QuotaState.Warning); return new(used, q.Limit, QuotaState.Ok); } Soft cap versus hard cap
The soft threshold and the hard cap do different jobs. The soft cap at 80% is a courtesy: warn the customer before they hit the wall, because a quota that stops a task mid-flight with no warning is a support ticket and a churn risk. The hard cap at 100% is enforcement, and what it does is the quota owner's declared policy, not something the enforcement code decides.
public async Task<bool> TryConsumeAsync(string meter, long amount, CancellationToken ct) { // Project the cost first so a hard Block can deny without recording the unit. long projected = _counter.Peek(meter) + amount; if (projected > _quota.Limit && _quota.OnExceed == OnExceed.Block) { _events.OnLimitReached(meter, _quota.Limit); return false; // fail closed: no work, no count } var reading = _counter.Record(meter, amount); // monotonic, sealed if (reading.State == QuotaState.Warning) _events.OnApproachingLimit(reading); // 80% — still allowed return _quota.OnExceed switch { OnExceed.Throttle when reading.State == QuotaState.AtLimit => await _throttle.AdmitAsync(ct), // keep serving, but slowly _ => true, // Ok / Warning / Overage: allowed }; } The ordering matters. A Block quota checks the projected count and refuses before recording, so a denied call never consumes a unit it was not allowed to use. Throttle and Overage do record — the usage happened — and then either slow the caller or let the overage flow through to billing. In every branch the default is the safe one: an unknown meter, a missing quota, or a failed integrity check all end up denying, not allowing.
Reconciling with the issuing service
The local counter is fast and works offline, but it is not the source of truth — a product with several machines on one license needs their usage summed somewhere authoritative. Reconciliation is that sync, and it runs on a timer, not per call. The client reports what it has consumed since last time; the server adds it to the authoritative total and hands back the current figure, which the client adopts and seals as its new floor.
public async Task ReconcileAsync(string meter, CancellationToken ct) { var local = _counter.Snapshot(meter); var ack = await _client.ReportUsageAsync( new UsageReport(meter, local.PeriodId, local.Used), ct); if (ack.PeriodId != local.PeriodId) _counter.StartPeriod(meter, ack.PeriodId); // server rolled the period: reset to 0 else _counter.Reconcile(meter, authoritative: ack.Used); // Used = max(local, ack); Floor = ack.Used } Two things fall out of this. First, the period reset is server-driven: the client does not decide the month ended by reading its own clock — the server confirms the new PeriodId and only then does the local count start fresh. That closes the clock-rollback hole, where a user winds the date back to escape a period boundary. Second, Floor = ack.Used is what makes a file rollback unprofitable: after reconciliation the client knows the server has already recorded that much, so reloading an older snapshot can never read below it.
The offline window, and where it breaks
Between reconciliations the client enforces entirely on its own, which is the point — no network on the hot path. The honest cost is a bounded window. A customer who goes offline right after a reconcile, burns through the period, then restores the file snapshot from just after that reconcile, reclaims the usage accrued in between. The floor stops them going back further than the last confirmed count, but it cannot stop them replaying the gap. You bound that gap by how often you reconcile: an hourly sync limits the exposure to an hour's worth of the meter; a daily sync, to a day's.
The HMAC key is the other load-bearing part. If it is a constant baked into the assembly, a determined attacker extracts it and forges a lower sealed count. Bind it to the machine and keep the metered checks hard to pull apart — protecting your licensing checks covers that — so the seal is worth what it claims to be. As with every client-side meter, this is a controlled trust extension for legitimate disconnected use, not an unbreakable guarantee; the authoritative count always lives on a server you control.
Doing this with Keyright
Keyright carries the quota as a first-class part of the signed license, alongside seats, feature flags and numeric limits. You declare the meter, limit, period, soft threshold and OnExceed policy; the SDK (.NET, Node, Python, Java) keeps the monotonic HMAC-sealed counter, enforces the soft and hard caps, and reconciles on a schedule you set — fail-closed throughout, and correct across the offline window. Because it is the same license that already handles your trials, seats and entitlements, a usage cap is part of the license rather than a billing system bolted on beside it. If you meter more than one resource at once, pair this with independent credit pools.
The Community Edition is free and self-hosted, so you can model a metered product and wire the counter end to end before you commit — see the pricing or read the Keyright docs for the exact metering surface.
Takeaway: A quota in the payload is a promise; the enforcement is the counter behind it. Sign the cap, count against it with a monotonic sealed counter that survives restart and clamps up to a server-confirmed floor, warn at the soft threshold and apply your declared policy at the hard one, and reconcile periodically so the server stays authoritative without sitting on the hot path. Then the number in the license finally means what it says.
原文:https://www.a8q9.cn/en/article/enforcing-a-usage-quota-per-license-94bba6.html