Coordination overview
Это содержимое пока не доступно на вашем языке.
Sometimes the cluster needs a single-holder guarantee that membership-only mechanisms can’t provide:
- The
ClusterSingletonshould never spawn two instances during a network partition. - The sharding coordinator on the leader side of a partition shouldn’t issue allocations if another side might also have a leader.
The Lease API gives you that guarantee. A lease is a
distributed lock with a TTL — at most one process holds it at
a time, with a backend (Kubernetes, etcd, your own) providing the
single-holder constraint.
The contract
Section titled “The contract”interface Lease { acquire(): Promise<boolean>; release(): Promise<void>; checkAlive(): boolean; onLost(handler: (reason: string) => void): () => void;}Four methods:
acquire()— try to claim the lease. Resolvestrueon success,falseon contention (someone else has it).release()— voluntarily drop ownership. No-op if not held.checkAlive()— cheap, local “do I still own this lease?” check.trueonly until the TTL runs out since the last write the backend accepted, whether or not a renewal has run since.onLost(handler)— register a callback fired if ownership is lost unexpectedly (TTL expired without renewal, another holder took over).
The backend implements the contract. The framework’s built-in
KubernetesLease uses K8s native Lease resources;
InMemoryLease is the test / dev option.
When you need a lease
Section titled “When you need a lease”Two production scenarios:
| Scenario | Why a lease helps |
|---|---|
| Cluster singleton | Prevents dual-leadership during partition. See Singleton with lease. |
| Sharding coordinator | Prevents two coordinators making conflicting allocations. See Sharding with lease. |
For most clusters, a downing strategy is enough. Leases are the paranoid-safe option:
- Downing strategy alone: cluster picks a winner during partition; most apps are fine.
- Downing strategy + lease: an additional check that prevents edge-case dual-leadership even if downing misfires.
If you can afford the operational cost (K8s namespace permissions, etcd cluster, etc.), enable leases for any singleton or sharding setup where dual-execution would cause real damage — double-charging a customer, double-publishing a stream event.
Lease lifecycle
Section titled “Lease lifecycle”The flow:
- Some actor (typically a singleton manager) calls
lease.acquire(). - Backend tries to record this owner. Success → returns
true. - While holding, the backend renews every
renewalIntervalMs(typicallyttl / 3). - If renewal fails (network blip, backend down, lease taken
over) — or only comes round after the TTL already ran out —
onLostfires with the reason. From the deadline on,checkAlive()already readsfalse. - The actor releases ownership-dependent state immediately.
The TTL is critical — a holder that crashes without release
loses the lease automatically when the TTL expires. Other
contenders can then acquire.
Settings
Section titled “Settings”type LeaseOptionsType = { name: string; // unique lease identifier owner: string; // this holder's identifier (pod name / UUID) ttlMs: number; // auto-expire after this many ms of no-renewal renewalIntervalMs?: number; // default ttl/3 with a floor, at most ttl/2 acquireRetries?: number; // max attempts per acquire() acquireRetryDelayMs?: number; // delay between attempts};| Setting | Typical values |
|---|---|
ttlMs | 15-30 s. Short enough to recover from a crashed holder, long enough to tolerate gossip / renewal delays. |
renewalIntervalMs | ~ttl / 3, the default. A renewal that only comes round after the TTL ran out gives the lease up, so keep it well under the TTL. |
acquireRetries | 3-10 for production. |
acquireRetryDelayMs | 100-1000 ms. |
Backends
Section titled “Backends”| Backend | Use |
|---|---|
InMemoryLease | Tests and dev. One isolate — a process, or one worker thread of it; not actually distributed, and not selectable from configuration. |
KubernetesLease | Production on K8s. Uses K8s native Lease CRDs. Selectable from configuration as backend = kubernetes. |
A singleton, a sharded type’s coordinator and lease-majority can also get a
lease without one being passed in code: name the backend under
actor-ts.coordination.lease and turn on the consumer’s switch, and the
framework builds the lease — named after the consumer, owned by the node.
See leases the framework builds.
For non-K8s production deployments, you’d implement the Lease
interface against your coordination service (etcd, Consul,
Zookeeper). The interface is small — ~50 lines of glue.
A minimal example
Section titled “A minimal example”import { StartSingletonOptions } from 'actor-ts/cluster';import { KubernetesLease, KubernetesLeaseOptions } from 'actor-ts/coordination';
const kubernetesLeaseOptions = KubernetesLeaseOptions.create() .withName('my-app-singleton-lease') .withOwner(process.env.POD_NAME!) .withTtlMs(30_000) .withRenewalIntervalMs(10_000) .withNamespace(process.env.K8S_NAMESPACE!);const lease = new KubernetesLease( kubernetesLeaseOptions,);
const startSingletonOptions = StartSingletonOptions.create() .withTypeName('job-scheduler') .withActor(JobScheduler) .withLease(lease); // ← split-brain protectioncluster.singleton.start(startSingletonOptions);The singleton manager will:
- Try to acquire the lease before spawning the singleton.
- Renew it while alive.
- Release it on graceful shutdown.
- Respond to
lease.onLost(...)by stopping its singleton.
Where to next
Section titled “Where to next”- Lease API — the full interface contract.
- InMemoryLease — the dev / test backend.
- KubernetesLease — the K8s-native production backend.
- Singleton with lease — using a lease for singleton uniqueness.
- Downing strategies — the complementary partition resolver.
