Leader Election
Some roles must belong to one process at a time. Two copies of a scheduler send duplicate emails, and two importers load the same file twice. Leader election picks one process to own the role and lets another process take over when the owner dies. Common examples are schedulers and cluster-wide maintenance jobs.
With Kahuna, the role is a distributed lock, and the lock owner is the leader. The lock lease prevents permanent ownership if the leader crashes. The fencing token protects downstream systems from stale leaders.
Acquire Leadership
All candidates use the same loop. The process that acquires the lock leads, and the other processes continue to try. This means that a standby takes over as soon as the leader releases the lock or its lease expires.
- .NET
- TypeScript
async Task Campaign(KahunaClient client, CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
KahunaLock leadership = await client.GetOrCreateLock(
"leaders/billing-scheduler",
expiry: TimeSpan.FromSeconds(15),
wait: TimeSpan.FromSeconds(3),
retry: TimeSpan.FromMilliseconds(200),
durability: LockDurability.Persistent,
cancellationToken: stoppingToken
);
// Another process is leader. The 3 second wait paces the next attempt.
if (!leadership.IsAcquired)
continue;
try
{
await LeadWhileHealthy(leadership, stoppingToken);
}
finally
{
// Release the lock if this process still holds it. When another process
// already took over, the release can fail; that is expected here.
try { await leadership.TryUnlock(CancellationToken.None); }
catch (KahunaException) { }
}
}
}
async function campaign(client: KahunaClient, signal: AbortSignal): Promise<void> {
while (!signal.aborted) {
const leadership = await client.acquireLock("leaders/billing-scheduler", {
expiry: 15_000,
wait: 3000,
retry: 200,
durability: "persistent",
signal
});
// Another process is leader. The 3 second wait paces the next attempt.
if (!leadership.acquired) {
continue;
}
try {
await leadWhileHealthy(leadership, signal);
} finally {
// Release the lock if this process still holds it. When another process
// already took over, the release fails; that is expected here.
await leadership.release().catch(() => false);
}
}
}
When the leader stops cleanly, the finally block releases the lock, and a standby can take over on its next attempt. The loop releases the lock explicitly and doesn't use await using. A release of a lock that another process already owns can raise an error, and with await using that error would end the loop. If the leader crashes, the lock isn't released. A standby will take over after the lease expires, up to 15 seconds later.
Renew While Healthy
The leader extends the lease periodically and stops leading as soon as it cannot. A failed extension raises an exception (KahunaException in .NET, KahunaError in TypeScript), for example when the lease already expired and another process owns the lock.
- .NET
- TypeScript
async Task LeadWhileHealthy(KahunaLock leadership, CancellationToken stoppingToken)
{
long fencingToken = leadership.FencingToken;
while (!stoppingToken.IsCancellationRequested)
{
try
{
(bool extended, long token) = await leadership.TryExtend(TimeSpan.FromSeconds(15), stoppingToken);
if (!extended || token != fencingToken)
return;
}
catch (KahunaException)
{
// The lease expired and another process may own the lock, or Kahuna is unreachable.
return;
}
await DoLeaderWork(fencingToken, stoppingToken);
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
import { isKahunaError, type KahunaLock } from "kahuna-client";
import { setTimeout as sleep } from "node:timers/promises";
async function leadWhileHealthy(leadership: KahunaLock, signal: AbortSignal): Promise<void> {
const fencingToken = leadership.fencingToken;
while (!signal.aborted) {
try {
const extended = await leadership.extend(15_000, { signal });
if (!extended.extended || extended.fencingToken !== fencingToken) {
return;
}
} catch (error) {
// The lease expired and another process may own the lock, or Kahuna is unreachable.
if (isKahunaError(error)) return;
throw error;
}
await doLeaderWork(fencingToken, signal);
await sleep(5000, undefined, { signal });
}
}
The lease protects the role if each pass of the loop finishes before the lease expires (15 seconds here). A pass is the leader work plus the delay. A long GC pause or a slow call can make a pass take longer. In this case, the lease expires and a standby becomes leader. The old leader will continue to work until its next extension fails. Keep each unit of leader work well within the lease. Also, make side effects carry the fencing token. The resource can then discard work from a leader that was replaced.
Use Fencing Tokens
External writes from the leader should carry the fencing token. The downstream system should reject writes with an older token than the latest committed token for that resource.
- .NET
- TypeScript
await db.SaveCheckpoint(
jobName: "billing-scheduler",
checkpoint: checkpointValue,
fencingToken: leadership.FencingToken
);
await db.saveCheckpoint({
jobName: "billing-scheduler",
checkpoint: checkpointValue,
fencingToken: leadership.fencingToken
});
A paused leader can lose its lease and resume later as if it owns the role. In this case, the new leader's higher token lets the resource reject the late write from the old leader. For more information, see Fencing Tokens.
Operational Notes
- Keep the lease long enough to tolerate normal GC pauses and network jitter.
- Renew at a fraction of the lease duration, for example at 5-second intervals for a 15-second lease.
- Use persistent lock durability for leadership that must survive process or node failures.
- Always use the fencing token when the leader writes to external systems.