@molecule/api-instance-leadership

Core interface · instance-leadership · API (Node) · v1.1.1 · Apache-2.0

Instance-leadership core interface for molecule.dev: elect one API instance to run platform-wide singleton work, with demotion and takeover when the holder's connection is lost.

npm install @molecule/api-instance-leadership

npm · Source on GitHub

How it works

@molecule/api-instance-leadership is the instance-leadership core interface on the API (Node) side: the API your app calls, with no vendor inside.

Choose the implementation by bonding one of its 1 provider: @molecule/api-instance-leadership-postgresql.

Providers (1): @molecule/api-instance-leadership-postgresql

Works with: @molecule/api-bond

Reference

Instance-leadership core interface for molecule.dev: elect ONE API instance to run platform-wide singleton work, and hand leadership over within seconds when the holder's connection is lost.

Bond a provider — @molecule/api-instance-leadership-postgresql — at startup, then start leader-only work from acquireLeadership():

import { acquireLeadership, isLeader } from '@molecule/api-instance-leadership'
import { provider } from '@molecule/api-instance-leadership-postgresql'
import { setProvider } from '@molecule/api-instance-leadership'

setProvider(provider)

acquireLeadership({
  onAcquired: () => startPoolManager(),
  onLost: () => stopPoolManager(),
})

Only the code you run inside onAcquired is leader-only. Every instance still serves HTTP traffic, processes queue messages, and answers readiness probes. Reach for this package when a job must run once across the whole platform — pre-warm pool managers, retention sweeps, status recorders, periodic billing — not for anything request-driven.

Use isLeader() for facts that must be decided at call time (e.g. skipping a duplicate periodic tick); use onAcquired/onLost to start and stop the loops themselves.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Type

core

Installation

npm install @molecule/api-instance-leadership @molecule/api-bond

API

Interfaces

LeaderLockSession

One dedicated lock session, as a provider bond sees it.

A session must be backed by a connection the provider owns exclusively: the lock lives and dies with that connection, so an operator never has to tune a TTL and a crashed instance never leaves a stale lock row behind.

interface LeaderLockSession {
  /**
   * Ask the shared store for the lock WITHOUT blocking.
   *
   * @returns `true` when this session now holds it.
   */
  tryLock(): Promise<boolean>

  /**
   * Release the lock (a no-op when this session does not hold it) and close
   * the connection.
   */
  release(): Promise<void>

  /**
   * Register the "this connection is gone" handler. Called at most once, when
   * the connection errors or the store ends the session.
   *
   * @param handler - Invoked on connection loss.
   */
  onLost(handler: () => void): void
}

AcquireLeadershipOptions

What InstanceLeadershipProvider.acquire needs from the application.

interface AcquireLeadershipOptions {
  /**
   * Start the singleton subsystems. Invoked once per acquisition — including a
   * RE-acquisition after a connection loss, so it must be safe to call again
   * after `AcquireLeadershipOptions.onLost` stopped everything.
   */
  onAcquired: () => void | Promise<void>

  /**
   * Stop the singleton subsystems. Invoked when a leader loses its lock
   * connection, BEFORE the provider tries to re-acquire: the store has (or is
   * about to) release the lock, another instance may already be taking over,
   * and two live leaders is exactly what leadership exists to prevent.
   */
  onLost?: () => void | Promise<void>
}

InstanceLeadershipProvider

The contract every instance-leadership provider implements.

Application code reaches the bonded provider through the accessors in @molecule/api-instance-leadership (setProvider, getProvider, isLeader, acquireLeadership, releaseLeadership) rather than importing a bond.

interface InstanceLeadershipProvider {
  /**
   * Whether THIS instance currently holds the leadership lock.
   *
   * @returns `true` from the moment the lock is acquired until it is lost or
   * released.
   */
  isLeader(): boolean

  /**
   * The current leadership phase.
   *
   * @returns The `LeadershipState`.
   */
  state(): LeadershipState

  /**
   * Start contending for the lock, retrying forever in the background. Never
   * rejects and never blocks — the caller starts its singleton subsystems from
   * `AcquireLeadershipOptions.onAcquired`.
   *
   * Calling `acquire()` again while already contending or leading is a no-op.
   *
   * @param options - What to start on acquisition and stop on loss.
   */
  acquire(options: AcquireLeadershipOptions): void

  /**
   * Stop contending and release the lock, so another instance can take over
   * immediately instead of waiting for this process to exit.
   *
   * @returns Resolves once the lock release and the connection close settle.
   */
  release(): Promise<void>
}

Types

LeadershipState

The leadership phase of one instance.

  • follower — the instance is contending for the lock but does not hold it.
  • leader — the instance holds the lock and runs the singleton work.
  • stopped — release() was called; the instance no longer contends.
type LeadershipState = 'follower' | 'leader' | 'stopped'

LeaderLockFactory

Creates a fresh lock session.

Injected rather than imported so a host application can reuse its own database connection settings, and so tests can drive several simulated instances through one fake store.

type LeaderLockFactory = () => Promise<LeaderLockSession>

Functions

setProvider(provider)

Registers an instance-leadership provider as the active singleton. Called by a bond package during application startup.

function setProvider(provider: InstanceLeadershipProvider): void
  • provider — The provider implementation to bond.

getProvider()

Retrieves the bonded instance-leadership provider, throwing if none is wired.

function getProvider(): InstanceLeadershipProvider

Returns: The bonded instance-leadership provider.

hasProvider()

Checks whether an instance-leadership provider is currently bonded.

function hasProvider(): boolean

Returns: true if a provider is bonded.

isLeader()

Whether THIS instance currently holds platform leadership.

function isLeader(): boolean

Returns: false when no provider is bonded or this instance is a follower.

leadershipState()

The current leadership phase of this instance.

function leadershipState(): LeadershipState

Returns: The bonded provider's state, or 'follower' when none is bonded.

acquireLeadership(options)

Starts contending for platform leadership through the bonded provider.

function acquireLeadership(options: AcquireLeadershipOptions): void
  • options — What to start on acquisition and stop on loss.

releaseLeadership()

Releases platform leadership through the bonded provider so another instance can take over immediately.

function releaseLeadership(): Promise<void>

Returns: Resolves once the release settles; a no-op when no provider is bonded.

Available Providers

ProviderPackage
PostgreSQL@molecule/api-instance-leadership-postgresql

Injection Notes

Requirements

Peer dependencies:

  • @molecule/api-bond ^1.0.1

Runtime Dependencies

  • @molecule/api-bond

  • The lock must live in a store every instance shares. A host-local lock (a loopback port, a file) elects one leader PER HOST, so every singleton runs twice — the failure this package exists to prevent.

  • onLost is not optional in practice for a real leader. A provider may lose the lock while the process keeps running (a database connection that errors); the instance demotes itself and another may already be leading. Stop the loops in onLost, or two copies run.

  • Re-acquisition is possible. onAcquired runs again after a loss, so it must be safe to call after onLost stopped everything.

  • Followers retry forever in the background. acquireLeadership() never rejects and never blocks; a database that is down at boot just means this instance stays a follower until it is reachable.

  • No provider bonded ⇒ isLeader() is false. A single-instance app can use this package unchanged (it never leads until a bond exists) or omit it and run its singleton work directly.