Floating seats that release themselves when a client crashes
How a self-hosted Keyright deployment hands out a bounded number of concurrent seats, keeps each one alive with periodic heartbeats, and reclaims a seat whose client died without checking out — including the real races at the cap boundary, clock skew on lease expiry, and the heartbeat-versus-release ordering, with the C# the SDK and the issuing service each run.
A floating licence is a promise with a hole in it. You sell ten concurrent seats, the SDK dutifully checks one out when the application starts, and everything works until the day a client process is killed — power loss, a force-quit, a container evicted mid-task — without ever telling the server it was done. The seat it held is now a ghost: counted against your ceiling, claimed by nobody, and impossible to distinguish from a real user who simply stepped away. Do nothing and your ten-seat licence slowly starves as ghosts accumulate. Reclaim too eagerly and you yank a seat out from under someone whose laptop merely slept for ninety seconds.
The real question is how an issuing service hands out a bounded number of seats and safely reclaims the dead ones, without a persistent connection to every client and without ever letting the live count drift above the cap. Keyright does it with a lease: a seat is not a flag you set and clear, it is a short-lived grant with a deadline, kept alive by heartbeats and reclaimed by expiry. That one design choice turns an unanswerable question — is this client still alive? — into an answerable one — has this lease been renewed recently enough? This post is how the lease lifecycle works, and where the races hide.
A seat is a lease, not a flag
The naive model stores one boolean per seat and a count. Checkout flips a bit and increments; release flips it back. It fails the moment a client dies without releasing, because the bit stays set forever. There is no bounded way to recover, only heuristics that are wrong in both directions.
The lease model stores, per active seat, a small record with a deadline:
{
"leaseId": "lease_7e2a9c",
"licenseId": "KR-9QX2-7F3M",
"seatHolder": "host-7e2a9c:pid-4821",
"issuedAt": "2026-11-21T09:12:04.118Z",
"expiresAt": "2026-11-21T09:14:04.118Z",
"renewals": 0
}
A seat is live if and only if a lease for it exists and now() is before its expiresAt, as judged by the service clock. That is the whole definition. A crashed client stops renewing; its expiresAt slides into the past; the seat becomes reclaimable with no special crash detection anywhere. The deadline does the work a heartbeat-presence check never could, because it needs no second message to confirm death — the absence of a renewal is the signal.
Checkout, and the cap-boundary race
Checkout is where correctness is won or lost. The temptation is to write it as two steps: count the live leases, and if under the cap, insert a new one. That is a textbook time-of-check-to-time-of-use bug. Two clients both read “nine live” and both insert the tenth — now eleven seats are held against a cap of ten.
The SDK call is deliberately simple; all the hard logic lives on the service:
using Keyright.Client;
var seats = new SeatClient(new SeatClientOptions
{
ServiceUri = new Uri("https://licensing.internal.acme.example"),
LicenseKey = licenseKey,
SeatHolder = SeatHolder.ForThisProcess(), // host + pid + boot id
});
// Blocks only on the round-trip; throws SeatCapReachedException on 409.
await using SeatLease lease = await seats.CheckoutAsync(cancellationToken);
// The lease keeps itself alive in the background until disposed.
RunApplication();
On the service, checkout is a single atomic conditional write. It inserts the lease only if the number of live leases for this licence is still below the cap at the instant of the write — the count and the insert are one indivisible operation, not two. Expressed as the predicate the storage layer enforces:
// Service-side. Runs as ONE atomic operation, serialised per licenseId.
public CheckoutResult Checkout(string licenseId, SeatHolder holder, int cap, TimeSpan ttl)
{
var now = _clock.UtcNow;
// Count only leases that are still live by the SERVICE clock.
// Expired leases do not count — they are reclaimed implicitly here.
int liveCount = _leases.CountWhere(licenseId, l => l.ExpiresAt > now);
if (liveCount >= cap)
return CheckoutResult.CapReached(liveCount, cap);
var lease = new Lease
{
LeaseId = LeaseId.New(),
LicenseId = licenseId,
Holder = holder,
IssuedAt = now,
ExpiresAt = now + ttl,
};
// Commit succeeds ONLY IF liveCount is still < cap at write time.
// If a racing writer committed first, this returns Conflict and we retry.
return _leases.InsertIfLiveCountBelow(lease, cap, now)
? CheckoutResult.Granted(lease)
: CheckoutResult.CapReached(cap, cap);
}
The load-bearing line is InsertIfLiveCountBelow. It is a compare-and-set: the write is accepted only if the live-count predicate it was conditioned on still holds at commit time. When two requests race for the last seat, the storage layer orders them. The first sees nine live and commits the tenth. The second is evaluated against the now-committed state, sees ten, and is rejected. The loser gets a CapReached result and never receives a lease token — so it never believes it holds a seat. Notice that expired leases are excluded from liveCount, which means every checkout also performs an implicit reclaim: the ghost of a crashed client does not count against the cap the moment its deadline has passed.
Heartbeats, and why they are conditional
Once granted, the lease must be kept alive. The SeatLease returned by CheckoutAsync owns a background loop that renews the lease at a fraction of the TTL — by default every third of the way through, so a two-minute lease is renewed roughly every forty seconds. Renewing early is not wasteful; it is the margin that absorbs a slow timer, a delayed request, or one lost renewal without the lease ever actually lapsing.
The critical property is that a heartbeat is conditional. It is not “set expiresAt to now + TTL for this seat”; it is “extend this exact lease if it is still live”. The renewal carries the leaseId, and the service refuses it if that lease is gone:
// Service-side renewal. Conditional on the lease still existing AND being live.
public RenewResult Renew(string leaseId, TimeSpan ttl)
{
var now = _clock.UtcNow;
// Atomic: extend only if the lease is present and not yet expired.
bool extended = _leases.ExtendIfLive(leaseId, newExpiry: now + ttl, now: now);
return extended
? RenewResult.Renewed(now + ttl)
: RenewResult.Lost; // released, revoked, or already swept
}
// SDK-side loop. A lost renewal is surfaced, never swallowed.
private async Task HeartbeatLoop(CancellationToken ct)
{
var interval = _ttl / 3;
while (!ct.IsCancellationRequested)
{
await Task.Delay(interval, ct);
var result = await _transport.RenewAsync(_leaseId, ct);
if (result.Kind == RenewKind.Lost)
{
_lostSeat.TrySetResult(); // application observes SeatLost
return; // stop renewing a seat we no longer hold
}
_expiresAt = result.NewExpiry;
}
}
ExtendIfLive is the counterpart to InsertIfLiveCountBelow: another compare-and-set, this time conditioned on the lease being present and unexpired. It closes the resurrection race. Picture a renewal already in flight when the application calls release, or an admin revokes the seat. The release deletes the lease; a millisecond later the in-flight heartbeat arrives. An unconditional “touch” would happily recreate the row and push the live count above the cap with a seat nobody is using. Because the renewal is conditional, it finds no live lease to extend, returns Lost, and the SDK stops the loop rather than resurrecting a dead seat.
Release, expiry, and the ordering that matters
There are two ways a seat comes back. The clean way is release: await using disposes the SeatLease, which sends one final call deleting the lease and freeing the seat immediately — no waiting for a deadline. The lossy-but-safe way is expiry: a client that never gets to release (because it crashed) simply stops renewing, and its lease lapses.
Expiry is evaluated lazily. The service does not run a timer per lease waiting to fire; it compares now() against expiresAt whenever a seat is next inspected — on the next checkout for that licence (where expired leases are excluded from the count, as above) and on a periodic low-frequency sweep that tidies abandoned rows so the store does not grow without bound. Lazy evaluation is what keeps the cost of ten thousand idle leases at zero: nothing wakes up for a lease that no one is contending.
The ordering that matters is heartbeat-versus-release, and the rule is simple: release is a delete, renewal is a conditional extend, and whichever the store commits first wins deterministically. If release commits first, the later heartbeat finds no lease and returns Lost. If a heartbeat commits first, it merely pushes the deadline out by a TTL — and the release that follows still deletes the lease outright, freeing the seat regardless of how far the deadline had been extended. There is no interleaving in which a seat ends up both released and alive, because release does not care about the deadline and renewal cannot recreate a deleted lease.
When this breaks, honestly
Floating seats buy you bounded fairness, not perfection, and three limits are worth stating plainly.
First, the reclaim window is the TTL, and nothing shortens it. A crashed client holds its seat until the deadline passes. Choosing the TTL is a real trade-off: short TTLs reclaim ghosts fast but multiply heartbeat traffic and punish brief network drops; long TTLs are gentle on flaky links but let a dead client squat longer. There is no setting that reclaims instantly and tolerates a sleeping laptop, because those are the same uncertainty viewed from two sides.
Second, offline tolerance is bounded by exactly that window. A client that loses the network keeps working until its lease would have expired; reconnect in time and the next heartbeat heals it, miss the window and the seat is gone and must be re-checked-out, which can fail if the cap filled in the meantime. Floating licensing is not unlimited offline use — it is offline use bounded by the TTL, and that is the honest shape of it.
Third, all of this rests on the service clock, and only the service clock. The client’s expiresAt is advisory; every authorisation decision is the service comparing its own now() to a deadline it stored. That is what makes client clock skew a non-event — but it also means a service whose own clock jumps is the one thing that can corrupt lease timing, which is why the deadline, the renewal, and the sweep all read a single monotonic service clock rather than any value a client supplies.
Takeaway
The trick to floating seats is refusing to answer the unanswerable question. You cannot reliably detect that a client crashed, so you never try. You hand out a lease with a deadline, keep it alive with conditional heartbeats, and let absence reclaim what death left behind. The cap holds because checkout is one atomic conditional write, never a read-then-write; seats never resurrect because renewal is conditional on a live lease; and expiry needs no crash detection because the missing heartbeat is the detection. Configure the TTL for your tolerance of ghosts versus your tolerance of false reclaims, wire the SDK’s await using so clean exits release instantly, and the ten seats you sold stay ten — no more, and no fewer than are genuinely alive. See the concurrent-seat options in the Keyright docs and the licensing model on the Keyright product page.
Try Nebula.NET
Harden your .NET code in minutes — start with the free edition.