Leadership and leases

Leadership and leases

How a node takes a stream's writer lease, serves as its leader, and hands the stream on safely.

A stream's leader is the one node that accepts its appends. The leader holds the stream's writer lease, a record bound to its metadata session. A node becomes a stream's leader only after every record the previous leader acknowledged has a reference. A leader releases its lease only after certifying that its own acknowledged records have references; until then it keeps the lease and retries. The lease only names the leader. Safety against a stale node comes from fencing.

Where it lives

CodeWhat it owns
internal/coord/session.goThe sessions keyspace records: liveness, node stats, and AcquireWriter for the lease
internal/coord/placement.goDesignatedLeader: which node should lead a stream
internal/star/writerA node's leaderships: open, admission, idle expiry, departure, limbo, drain
internal/storage/wal/gate.go, flush.goThe open gate, and the release flush with its clean-release record
internal/transport/grpc/dataplaneRouting: NOT_OWNER redirects, and healing an orphaned lease
internal/coord/rebalanceMoving leaderships between nodes

Coordination records

In the code, a running node is a star, keyed by its StarID. All coordination records live in the sessions keyspace and vanish when their session ends:

RecordKeyWhat it holds
Liveness recordcluster/stars/<star>Identity, zone, location, addresses, and the load placement reads
Node stats recordcluster/stats/<star>Fixed-size totals for the admin plane
Writer leasestreams/<id>/leaseThe holding star and when it acquired the lease

The liveness record carries the node's client and fleet addresses and the load figures placement compares: leader count, append and hot-read bytes per second, the saturated and draining flags, storage pressure, and the absorb watermark. The node republishes it every 5 seconds.

The node stats record holds the build version, start time, the draining, drained, and stranded flags, utilization and its bottleneck axis, the metadata store's p99, and metadata operations per hash-ring bucket. It is a separate record so that its updates never rewrite the record placement reads. A node that only audits publishes this record and no liveness record, so placement never sees it.

--oxia-session-timeout (10 s with external oxia, 15 s with embedded oxia) is how fast a failure is detected. A failed star's lease and liveness record stay until that time passes, so every failover waits at least that long. A decommissioned star can never register again.

Choosing a leader

Designate ranks the live nodes for a stream by a rendezvous hash of the stream's ID, skipping nodes that are saturated or draining. The top two are the candidates. The runner-up wins only when it carries significantly less load:

internal/coord/placement.go
func significantlyCooler(candidate, top Star) bool {
	gap := top.LeaderLoad() - candidate.LeaderLoad()
	if gap <= tipFloorBps { // 1 MiB/s
		return false
	}

	mean := (top.LeaderLoad() + candidate.LeaderLoad()) / 2

	return float64(gap) > tipBand*float64(mean) // 0.20
}

The band keeps stale load figures from deciding. Inside it, the hash decides, so many opens at once spread across nodes instead of all choosing the one node that looked cooler a moment ago. When every live node is saturated or draining, the open is refused with ErrAtCapacity.

Opening a stream

alt [released cleanly by the last writer] [the predecessor left without one] open the stream AcquireWriter (create, bound to the session) lease check the fencing token read the clean-release and last-writer records record itself as last writer, spend the record ledger recovery of the predecessor's ledgers record itself as last writer read the reference frontier: the next sequence number ready Client Designated node Metadata store Object storage
  1. Route. A node that is not the designated leader answers NOT_OWNER with the address to use, and the client follows it.
  2. Acquire the lease. AcquireWriter creates streams/<id>/lease with NotExists, bound to the node's session. If the node already holds it, the acquire attaches to the existing lease. If another live node holds it, the open is redirected there. Nobody can take a lease from a live holder: a dead holder's session expiry is the only takeover. While the metadata store is unavailable, the acquire retries from 50 ms up to 1 s apart, for at most 10 seconds.
  3. Check the fencing token. The producer's token must match the stream's, if the stream has one.
  4. Pass the open gate. The WAL's gate recovers the previous leader's ledgers or passes on its clean-release record, then writes this node as the stream's last writer. See The open gate.
  5. Resume. The next sequence number is the reference frontier the gate certified, or the trim watermark when that is higher. A stream whose records were all trimmed and reclaimed has no references left, so its frontier reads 0 while its watermark stands. If the result is below what this node itself has acknowledged, it is raised to that, because handing out a number twice would corrupt the stream. The node then logs writer: open cursor below the acked tail; clamping.

Any failure after step 2 releases the lease before the open returns, even when the open's context was cancelled.

Releasing leadership

Every way a leadership ends goes through the same departure:

CauseWhen
closedThe last producer closed a stream whose producer policy is fenced. Such a stream has no idle timeout.
idleAn any stream had no producer for its idle timeout, 30 s by default
handoffRebalance moved the stream to another node
drainThe node is draining
deletedThe stream was deleted
fencedA newer fencing token replaced the producer
shutdownThe node is closing

Each initiator first claims the departure by removing the leadership from the node's map, so the work runs once whichever cause comes first. The claimed leadership then runs finish, with a 30-second budget:

  1. It waits for the batches in flight to resolve.
  2. It runs the release flush: one span row per stream over the slots still resident in the leader's memory. This covers the stream's newest records without closing the shared ledger, which other streams still use.
  3. Its last write is the clean-release record at streams/<id>/release: this star, its epoch, and the acknowledged frontier.
  4. The lease is released.
internal/storage/wal/flush.go
if acked <= frontier {
	// Everything acknowledged is ref-covered: certify it as the
	// flush's final write.
	return certify(ctx, cfg, epoch, id, acked)
}

The next leader passes its gate on that record when the record's star is the recorded last writer, and spends it before its first append. A record from a star that has since lost the stream vouches for nothing.

A departure without a clean-release record is an abandonment. The next open then judges the predecessor's ledgers: a superseded ledger is recovered, a live star's open head defers the open with a retryable error, and a dead star's head is recovered. See Ledger recovery.

When the finish fails

If finish cannot certify coverage, for example because the metadata store is slow, the leadership goes into limbo. The node keeps the lease and the write state, logs writer: finish incomplete; lease retained until coverage certifies, and runs finish again every 5 seconds. Opens of the stream fail meanwhile with ErrCoveragePending (FAILED_PRECONDITION), which clients retry. When the retry succeeds, the node logs writer: retained lease released; coverage certified. A node that closes with a leadership still in limbo abandons it: the lease ends with the session, and recovery covers the rest.

Orphaned leases

A lost answer to AcquireWriter can leave a node holding a lease with no leadership behind it. When an open reaches that node, the data plane tells the two cases apart:

  • If the node is draining, or the stream's leadership is in limbo, the lease is held on purpose. The node waits a short, bounded time for its departure to release the lease, then sends the open to the node placement chooses.
  • Otherwise the lease is orphaned. The node serves the open, and its own AcquireWriter attaches to the lease and builds the leadership.

nova.dataplane.orphaned.lease counts these repairs and normally stays at zero. The node logs dataplane: orphaned lease found; serving the open so the same-owner acquire re-attaches it once per stream per window, with the lease's age.

Crash points

Crash afterState left behindWhat happens next
The lease, before the open gateA lease on a dead sessionThe lease expires with the session; the next open acquires it
The last-writer record, before the first appendThis node recorded as the last writerThe next open judges this node's ledgers; nothing was acknowledged
Acknowledgements, before absorbAcknowledged records only in the ledgerThe next open recovers this node's ledger
The release flush, before the clean-release recordSpan rows covering everything; no recordThe next open judges this node: a live head defers, a dead or superseded one is recovered
The clean-release record, before the lease releaseThe record and a lease on the sessionA live node retries the release; a dead one's lease expires. The next open passes on the record.

Concurrency

  • The lease is advisory. Two nodes that both believe they lead are kept safe by the ledger fence, which stops the stale one at its next slot.
  • Losing the session. A node whose metadata session expires logs novad: registration lost; exiting to discard stale writer roles and exits without a graceful close. A graceful release could certify stale roles after another node had already taken their leases.
  • Departure runs once. Removal from the node's map, under its lock, is the claim; every later initiator finds the leadership gone.
  • The open gate records first. A node writes itself as last writer before admitting its first append, so a crash from then on always leaves a predecessor to judge.

Bounds and signals

BoundValue
Idle timeout of an any stream30 s
One finish attempt30 s
Limbo retryEvery 5 s
Lease acquire retry50 ms doubling to 1 s, for at most 10 s
Placement tipA gap above 1 MiB/s and above 20% of the two candidates' mean load
SignalWhat it shows
nova.writer.limbo.streams, nova.writer.limbo.ageLeaderships in limbo, and the oldest one's age
nova.writer.lease.release.failedLease releases that failed
nova.dataplane.orphaned.leaseOrphaned leases repaired

Tests

  • internal/star/writer: TestOpenHealsAnOrphanedLease, TestFailedOpenReleasesTheLeaseDespiteACancelledContext, TestPanicMidBuildReleasesTheLease, TestReopenDuringDepartureFinishIsRefused, TestExpelAndIdleDepartOnce, TestSupersedeParksUncertifiableDepartureInLimbo, TestFencedSupersedeFinishesTheDeposedLeadership.
  • internal/storage/wal: TestOpenGatePassesOnEvidence, TestOpenIgnoresAMarkTheLastWriterDidNotWrite, TestOpenSpendsAStaleMark, TestFlushStreamConvergesOnTheAbsorbersCommittedPrefix, TestReleaseFlushAcrossARollCrashEnumerationConverges.
  • tlaplus/StreamLeadership.tla and tlaplus/PlainStream.tla model leadership, the clean-release record, and the vacant stream.

See also

On this page