Skip to content
← All posts
· Delta1 Labs LicensingKeyright

Computing peak seat usage for true-up billing

At renewal you need to know how many floating seats a customer actually used at once — not the count today, and not the sum of every activation. This deep-dive derives the exact number from a lease event log with a sweep-line, handles leases that straddle the billing window and leases the reaper closed implicitly, and shows why a time-weighted p95 bills more honestly than the raw peak.

A vendor sells a floating pool: fifty concurrent seats, billed annually, true-up at renewal. Twelve months later the question on the invoice is deceptively simple — how many seats did they actually use? The naive answers are both wrong. Count the seats active right now and you get whatever the clock happened to catch, usually a quiet number. Sum every activation across the year and you bill a thousand, because one seat that cycles through two hundred users looks like two hundred seats. Neither is the quantity the contract rations.

Key takeaway: The number a floating contract is written against is peak concurrency — the largest set of leases that were ever open at the same instant over the billing window. You compute it exactly, not by sampling, with a sweep-line over the lease event log: sort the acquire and release events by time, walk them keeping a running count, and remember the high-water mark. The subtleties are all at the edges — leases that straddle the window boundary, and leases the reaper closed implicitly — and a time-weighted percentile usually bills more honestly than the raw maximum.

The real question: how many leases overlapped?

Keyright records floating-seat activity as a lease log. Every check-out is an acquire; every check-in, expiry, or reaper sweep is a release. For true-up, the raw material is a list of intervals — one per lease — each with a start and an end:

public readonly record struct LeaseInterval(DateTimeOffset Start, DateTimeOffset End);

Peak concurrency is the maximum number of these intervals that overlap at any single point in time. You could answer it by sampling — count active leases every minute and take the max — but sampling misses a peak that lives between two ticks, and a customer disputing a true-up is exactly the audience that will notice you guessed. The exact answer is cheap, so compute the exact answer.

The mechanism: a sweep-line over lease events

The trick is to stop thinking about intervals and think about events. Each lease contributes two: a +1 at its start and a -1 at its end. Sort every event by timestamp, walk the list left to right carrying a running sum, and the sum at any moment is the number of leases open at that moment. The largest value the sum ever reaches is the peak.

Five leases over the billing window → peak concurrency = 4lease Alease Blease Clease Dlease E01234peak = 4JanDecA release at the same instant as an acquire sorts first, so a seat handed straight from one user to the next counts as one, not two.
The sweep-line. The step curve is the running lease count; its maximum — four, where leases A, B, C and D overlap — is the peak concurrency the true-up bills against.

Two details make the walk correct. First, clamp every lease to the billing window before you emit its events — a lease that began in the previous period still occupies a seat on January 1st, and a lease still open at year end occupies one through December 31st. Second, when a release and an acquire land on the same instant, process the release first; otherwise a seat handed straight from one user to the next reads as two overlapping leases for one tick.

public static int PeakConcurrency(
    IEnumerable<LeaseInterval> leases,
    DateTimeOffset windowStart,
    DateTimeOffset windowEnd)
{
    var events = new List<(DateTimeOffset At, int Delta)>();
    foreach (var l in leases)
    {
        // Clamp to the billing window: a lease open across a boundary
        // still holds a seat for the part that falls inside the period.
        var start = l.Start < windowStart ? windowStart : l.Start;
        var end   = l.End   > windowEnd   ? windowEnd   : l.End;
        if (end <= start) continue;            // no overlap with this window
        events.Add((start, +1));
        events.Add((end,   -1));
    }
    // Ties: -1 (release) before +1 (acquire), so a back-to-back
    // handoff of one seat never reads as two.
    events.Sort((a, b) =>
        a.At != b.At ? a.At.CompareTo(b.At) : a.Delta.CompareTo(b.Delta));

    int current = 0, peak = 0;
    foreach (var e in events)
    {
        current += e.Delta;
        if (current > peak) peak = current;
    }
    return peak;
}

That is the whole algorithm: O(n log n) for the sort, one linear pass, no sampling, and the answer is exact. A year of a fifty-seat pool is a few hundred thousand events at most — milliseconds.

The edge that actually bites: leases the reaper closed

The code above assumes every lease has a clean End. In a real floating system, many do not. A laptop that goes to sleep, a process that is killed, a container that is evicted — none of these send a check-in. The lease simply stops heartbeating, and the server’s reaper reclaims the seat once the lease TTL elapses with no heartbeat. (That reaping mechanism is its own topic; see the heartbeat lease reaping post.)

For billing, a reaped lease did not occupy a seat all the way until the reaper noticed. It occupied one until the last heartbeat, plus the grace you are willing to grant. Charging a customer for the full TTL after a crashed process would inflate every peak. So the effective end of a lease is its explicit release if it has one, and otherwise its last heartbeat plus the TTL:

public static LeaseInterval ToInterval(LeaseRow row, TimeSpan leaseTtl)
{
    DateTimeOffset end = row.ReleasedAt             // clean check-in
        ?? row.LastHeartbeatAt + leaseTtl;          // reaped: held until TTL lapsed
    return new LeaseInterval(row.AcquiredAt, end);
}

Get this wrong in the generous direction and every flaky client pads the peak; get it wrong in the stingy direction and you under-bill real usage. The TTL you already chose for reaping is the defensible answer — it is the window during which the server genuinely treated the seat as held.

Billing on p95, not the raw peak

The absolute peak is honest but brittle. One all-hands where three contractors logged in for five minutes can push a fifty-seat customer to fifty-three, and billing a permanent three-seat increase off a five-minute spike is a renewal argument you will lose. A time-weighted percentile bills on sustained demand instead of the worst instant.

Compute it from the same event stream. Walk the sorted events, and for each gap between consecutive events accumulate the gap’s duration into a bucket keyed by the concurrency level during that gap. You end up with “seconds spent at each level,” and the p95 is the lowest level under which 95% of the window’s time accumulates:

public static int PercentileConcurrency(
    IReadOnlyList<(DateTimeOffset At, int Delta)> sortedEvents,
    double percentile)
{
    var secondsAtLevel = new SortedDictionary<int, double>();
    int current = 0;
    for (int i = 0; i + 1 < sortedEvents.Count; i++)
    {
        current += sortedEvents[i].Delta;
        double seconds = (sortedEvents[i + 1].At - sortedEvents[i].At).TotalSeconds;
        if (seconds > 0)
        {
            secondsAtLevel.TryGetValue(current, out var acc);
            secondsAtLevel[current] = acc + seconds;
        }
    }
    double total  = secondsAtLevel.Values.Sum();
    double cutoff  = total * percentile;
    double running = 0;
    foreach (var (level, seconds) in secondsAtLevel)   // ascending
    {
        running += seconds;
        if (running >= cutoff) return level;
    }
    return secondsAtLevel.Count == 0 ? 0 : secondsAtLevel.Keys.Max();
}

Report both. The p95 anchors the true-up; the raw peak is the honest ceiling you keep on record in case a customer asks what the busiest instant looked like.

Pulling the report

None of this is something the customer should assemble by hand. Keyright exposes the lease history through the admin API, and the CLI wraps the sweep-line so an operator gets the finished numbers:

keyright report seats \
  --product acme-suite \
  --from 2026-01-01 --to 2026-12-31 \
  --metric peak,p95 --tz America/New_York
{
  "product": "acme-suite",
  "window": { "from": "2026-01-01", "to": "2026-12-31" },
  "entitled": 50,
  "peak": 53,
  "p95": 47,
  "peakAt": "2026-09-18T14:32:07-04:00",
  "overageBasis": "p95"
}

The --tz flag matters more than it looks: “peak concurrency during the billing year” is bounded by the customer’s local midnight-to-midnight, and computing it in UTC smears their December 31st across two of your days. Resolve the window in the customer’s zone, then clamp.

Caveats

Floating only. This measures concurrency, which is meaningful only for a floating pool. A named-user entitlement bills on distinct identities over the period — a COUNT(DISTINCT user), not a sweep — and a node-locked license bills on bound machines. Run the right query for the licensing model; the sweep-line answers the floating question specifically.

Clock trust across nodes. In a multi-node deployment the lease timestamps come from whichever node served the heartbeat. A few seconds of skew between nodes will not move a peak that is sustained for minutes, but it can create or erase a one-second phantom overlap. Bill on the p95, which is immune to a single-tick artifact, and treat the raw peak as indicative rather than as the invoice line.

Reaped-lease TTL is a policy, not a fact. The effective end of a crashed lease is a choice — last heartbeat plus TTL. It is defensible because the server treated the seat as held for exactly that span, but it is still your policy, so document it in the contract. A customer who sees “peak 53” should be able to learn that a reaped lease counts until its TTL lapses.

The report is only as good as the log. If heartbeats are lost or lease events are dropped, the sweep-line computes the peak of what it has, not of what happened. Durable, ordered lease events are the foundation; the arithmetic on top is the easy part.

Takeaway

Floating-seat true-up is not a snapshot and not a sum — it is the maximum overlap of lease intervals over the billing window, and you get it exactly with a sweep-line: emit a +1 and -1 per lease, clamp to the window, sort with releases before acquires, and track the running high-water mark. Close reaped leases at their last heartbeat plus TTL so a crashed client does not inflate the bill, anchor the invoice on a time-weighted p95 rather than a brittle single-instant peak, and resolve the window in the customer’s own time zone. Keyright keeps the lease history and ships the report seats command so the number is defensible before it ever reaches an invoice; the Community Edition is free and self-hosted, so you can model a floating pool and read its true-up report end to end before you commit. The full admin-API surface is in the Keyright docs.

Try Nebula.NET

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