DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Originally published at delta1labs.com

Borrowing a floating seat to work offline

A floating lease is built to give a seat up the instant a client stops talking. A crashed app, a closed laptop, a yanked cable — all look the same to the issuing service, and all end the same way: the lease expires and the seat returns to the pool. That is exactly what you want for a shared lab, and exactly what you do not want for a consultant boarding a long flight. For that laptop, silence is not a crash. It is the plan. And a lease would quietly hand the seat to someone else the moment the plane left the gate.

The fix is not a longer lease. It is a different operation: a borrow. The client checks out a seat for a fixed window — three days, say — and leaves with a signed, self-contained token it can verify entirely offline. The service holds that seat reserved for the whole window and returns it automatically at the due date, whether or not the laptop ever comes back. It is a library loan for a floating seat: take the book, keep it until it is due, and it is returned for you on the due date even if you never set foot in the library again.

The real question

A lease answers "is anyone still using this seat right now?" by listening for heartbeats. A borrow has to answer a harder question with no heartbeats at all: "is this offline client still inside its window?" Neither the client nor the server can phone the other during the borrow. So the mechanism has to make both sides agree, independently, on exactly when the borrow ends — and it does that with a single shared value, the due date, baked into a signed token on the client and into the reservation on the server.

Borrow versus lease

It is worth being precise about what changes relative to an ordinary floating lease.

Floating lease Borrowed seat
Keeps the seat by Heartbeating before the TTL Holding a signed window, no contact
On client silence Seat reclaimed fast (TTL) Seat stays reserved to the due date
Needs the service Continuously, to renew Only to check out and to return
Offline validity Until the next renewal is due Verified locally for the whole window
Returned by Release, or TTL expiry on silence Early signed check-in, or auto-return at due date
Best for Shared, connected, intermittent use Deliberate disconnection, travel, field work

The lease optimises for recycling seats quickly; the borrow optimises for surviving a planned disconnection without losing the seat or over-granting it.

The borrow window

A borrow is one interval with two independent enforcers. On the client, a signed token verifies offline and fails closed at dueAt. On the server, the seat is reserved from borrowedAt to dueAt and rejoins the pool at the same instant. Early return collapses both sides ahead of time.





A borrow is one interval, enforced twice: the client's signed token and the server's reservation share a single due date, so both end together even with no network in between.

Checking out a seat

Initialize the client exactly as for an online lease — the same verify-only public key and the URL of your self-hosted instance — then check out a seat for a window instead of acquiring a short-lived lease. CheckoutSeatAsync takes the window you want and returns a BorrowedSeat carrying the signed token and the due date the server granted (which may be shorter than you asked, if policy caps it).

var client = KeyrightClient.Initialize(new KeyrightOptions
{
    Product         = "acme-studio",
    PublicKeyBase64 = config["Keyright:PublicKey"],   // verify-only, not a secret
    ServiceUrl      = config["Keyright:ServiceUrl"],   // your self-hosted instance
});

BorrowedSeat borrow;
try
{
    // Ask for three days offline; the server may grant less.
    borrow = await client.CheckoutSeatAsync(userKey, TimeSpan.FromDays(3));
}
catch (SeatsExhaustedException ex)
{
    return Gate.Deny($"No borrowable seats free right now ({ex.SeatsInUse}/{ex.MaxSeats} in use).");
}
catch (BorrowPolicyException ex)
{
    // e.g. requested window exceeds the max, or this client already holds a borrow.
    return Gate.Deny(ex.Message);
}

// Persist the signed token locally — this is what makes offline verification possible.
await TokenStore.SaveAsync(borrow.Token);
LicenseFeatures.Enable(borrow);
Enter fullscreen mode Exit fullscreen mode

That checkout is the one and only moment the client needs the network for the whole trip. The POST sends the requested window and a stable client instance id; the response is the signed token plus the live pool snapshot:

POST /v1/seats/checkout HTTP/1.1
Host: licensing.example.com
Idempotency-Key: 2a7f-acme-studio-inst-91a7
Content-Type: application/json

{
  "product": "acme-studio",
  "licenseKey": "ACME-STU-7F3K-...",
  "clientInstanceId": "inst-91a7",
  "requestedSeconds": 259200,
  "metadata": { "user": "r.okafor", "host": "lab-ws-14" }
}
Enter fullscreen mode Exit fullscreen mode
{
  "borrowId": "brw_6c1d04",
  "borrowedAt": "2026-12-01T09:00:00Z",
  "dueAt": "2026-12-04T09:00:00Z",
  "grantedSeconds": 259200,
  "seatsInUse": 18,
  "maxSeats": 25,
  "borrowsInUse": 4,
  "maxBorrows": 8,
  "token": "eyJwIjoiYWNtZS1zdHVkaW8iLCJicnci..."
}
Enter fullscreen mode Exit fullscreen mode

The token is not an opaque session id; it is the whole borrow, signed. Decoded, it holds the product, the license key id, the seat and borrow ids, borrowedAt, dueAt, the client instance id, and a signature over all of it. Because it is signed with the same key the client already trusts, the client can verify it with no further contact.

Verifying the borrow offline

Every start — on the plane, in the field, with the radio off — the client reloads the token and verifies it against the embedded public key. There is no network call in this path at all.

public bool TryResumeBorrow(out BorrowedSeat? seat)
{
    seat = null;
    if (!TokenStore.TryLoad(out string? raw)) return false;

    BorrowToken token = BorrowToken.Parse(raw!);

    // 1. Signature must verify against the pinned public key.
    if (!token.VerifySignature(_publicKey))
        return false;

    // 2. The window must still be open. notAfter == dueAt.
    var now = _clock.UtcNow;
    if (now < token.BorrowedAt - Leeway || now >= token.DueAt)
        return false;   // fail closed: before it started, or past due

    // 3. It must be this machine's borrow, not a token copied from elsewhere.
    if (token.ClientInstanceId != _instanceId)
        return false;

    seat = new BorrowedSeat(token);
    return true;
}
Enter fullscreen mode Exit fullscreen mode

The three checks are the entire offline enforcement. The signature proves the token was minted by your issuing service and not forged. The dueAt comparison is the auto-expiry: the instant the clock passes the due date, verification fails and licensed features switch off — no server round trip required to end the borrow. The instance-id check stops a borrowed token from being lifted onto another machine to clone the seat.

Auto-return at the due date

Here is the symmetry that makes a borrow safe. The server does not wait to hear from the client. It records the reservation as [borrowedAt, dueAt) and, when counting live usage, treats any borrow whose dueAt is in the past as already returned.

// Server-side: a borrowed seat counts against the pool only while its window is open.
int BorrowsHeld(string product, DateTimeOffset now) =>
    _borrows.Count(b => b.Product == product
                     && b.ReturnedAt is null
                     && b.DueAt > now);     // past-due borrows auto-return: they stop counting
Enter fullscreen mode Exit fullscreen mode

Because the client's token carries the same dueAt, the two sides flip together. At 09:00:00 on the due date the client's VerifySignature/dueAt check starts failing and the server's count stops including that borrow — simultaneously, with no message passing between them. A laptop that fell in a lake on day two still releases its seat on day three, right on schedule. This is the behaviour a lease cannot give you offline: a lease assumes silence means death and reclaims early; a borrow assumes silence means working and holds the seat for exactly the window it promised.

Returning early

The due date is the safety net, not the preferred path. When a trip is cut short and the client is online again, it should hand the seat back immediately with a signed check-in so the pool tightens for everyone else.

public async Task ReturnBorrowAsync(BorrowedSeat borrow, CancellationToken ct)
{
    LicenseFeatures.Disable();
    try
    {
        // A signed receipt proves it is this client returning its own borrow.
        await _client.ReturnSeatAsync(borrow, ct);   // POST /v1/seats/{borrowId}/return
        TokenStore.Clear();
    }
    catch (TransientException)
    {
        // Still offline? No harm: the seat auto-returns at dueAt anyway.
        // We've already disabled features locally, so nothing is over-used.
    }
}
Enter fullscreen mode Exit fullscreen mode

Notice the early return is purely an optimisation. If the check-in never reaches the server — the client is still offline, or the message is lost — the seat is not stranded, because dueAt reclaims it regardless. The server treats the return idempotently: a receipt for a borrow the due date already reclaimed is a no-op, and a duplicate receipt returns the same acknowledgement rather than erroring.

Keeping the pool healthy

A borrowed seat is a real seat removed from circulation for its whole window, so borrowing has to be rationed or it starves your online users. Keyright enforces that server-side with three caps, all independent of the client:

  • Maximum window. Reject (or clamp) a requestedSeconds above your ceiling, so no single borrow parks a seat for a month. The response's grantedSeconds tells the client what it actually got.
  • Borrowable fraction. Cap how many of the pool's seats may be out on loan at once (maxBorrows in the snapshot above). Reserve the majority for live leases so a connected user is never blocked by seats sitting in drawers.
  • Per-client limit. One open borrow per client instance, so a single machine cannot hoard several windows.

Surface the two counts the checkout returns — seatsInUse/maxSeats and borrowsInUse/maxBorrows — in an admin view. "Six of eight borrow slots out, back by Thursday" is the difference between a policy you can reason about and seats that mysteriously vanish.

Caveats and when it breaks

Offline enforcement means client-clock enforcement, and that is the honest limit. Once the laptop is disconnected, nothing stops a determined user from rolling the clock back to stay inside the window. The small Leeway above absorbs ordinary skew, not deliberate tampering; for that, pair the borrow with a monotonic high-water-mark so a rewound clock is detected on the next online contact — see the anti-rollback mechanism. Keep windows short: a three-day borrow is a far smaller blast radius than a thirty-day one.

The second trade is no mid-window revocation. The whole value of a borrow is that the client needs no further contact, which means a key you revoke while a seat is borrowed stays usable until its due date. That is the deliberate price of offline autonomy. Revocation takes effect at the next checkout, so short windows bound how long a revoked key can linger. If you need instant kill, borrowing is the wrong model — keep those clients on an online lease.

Finally, a borrow is not a floating lease with a long TTL. A long TTL still reclaims on silence; it just reclaims slowly, which means a real crash parks a seat for the whole TTL and a planned disconnection still risks losing it to a missed renewal. The borrow is a distinct operation precisely because it promises the opposite of what a lease promises when a client goes quiet.

Takeaway

Borrowing turns a planned disconnection from a problem into a first-class operation. The client checks out a seat once, carries a signed token it verifies entirely offline, and the issuing service reserves that seat for the exact window it granted. One shared due date does the hard part: the token stops verifying and the seat rejoins the pool at the same instant, with no round trip, so a client that never reconnects is handled as cleanly as one that returns early. Use a lease for shared, connected work and a borrow for the laptop that is about to go dark on purpose — cap the window, cap the fraction of the pool on loan, and let the due date return every seat on time.

Top comments (0)