@molecule/api-instance-leadership-postgresql

Provider bond · instance-leadership · API (Node) · v1.1.3 · Apache-2.0

PostgreSQL provider for @molecule/api-instance-leadership: one leader across every API instance via a session advisory lock on a dedicated connection, with demotion when the connection is lost.

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

npm · Source on GitHub · Implements @molecule/api-instance-leadership

How it works

@molecule/api-instance-leadership-postgresql is a provider bond on the API (Node) side: it implements the instance-leadership core interface (@molecule/api-instance-leadership) with a concrete vendor or library behind it.

Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.

Works with: @molecule/api-bond, @molecule/api-instance-leadership

Secrets: DATABASE_URL

Reference

PostgreSQL provider for @molecule/api-instance-leadership: elect ONE API instance to run platform-wide singleton work, using a PostgreSQL SESSION advisory lock held on a dedicated connection.

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

setProvider(provider) // reads DATABASE_URL lazily; nothing connects here
acquireLeadership({
  onAcquired: () => startPoolManager(),
  onLost: () => stopPoolManager(),
})

Use this bond whenever the API runs as more than one process or Machine: a host-local lock (a loopback port, a file) elects one leader PER HOST, so every singleton — pool managers, hibernation, retention sweeps, status recorders — runs once per Machine instead of once per platform.

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

provider

Installation

npm install @molecule/api-instance-leadership-postgresql @molecule/api-bond @molecule/api-instance-leadership pg
npm install -D @types/pg

API

Interfaces

PostgresLeaderLockOptions

How to open the dedicated leadership connection.

interface PostgresLeaderLockOptions {
  /**
   * The lock id to hold. This is an arbitrary 64-bit integer that must be
   * unique across everything sharing the database: leadership must never
   * contend with a migration lock or another feature's advisory lock.
   */
  lockId: number

  /** Connection string. Defaults to `process.env.DATABASE_URL`. */
  connectionString?: string

  /**
   * TLS configuration passed to `pg`. Omit to let the driver decide from the
   * connection string (`sslmode=require` still enables TLS).
   */
  ssl?: pg.ConnectionConfig['ssl']

  /**
   * Open a connected client. Injected by a host that owns its own connection
   * settings (e.g. a platform API with a shared SSL derivation helper); the
   * default creates a `pg.Client` from `PostgresLeaderLockOptions.connectionString`.
   *
   * @param connectionString - The resolved connection string.
   * @param ssl - The configured TLS options.
   * @returns A connected `pg.Client`.
   */
  connect?: (connectionString: string, ssl: pg.ConnectionConfig['ssl']) => Promise<pg.Client>
}

PostgresLeadershipProviderOptions

How to build a leadership provider.

interface PostgresLeadershipProviderOptions {
  /**
   * Opens one dedicated lock session per attempt. Use
   * `createPostgresLockFactory` for the production PostgreSQL session,
   * or a fake that shares one "held by" flag in tests.
   */
  createSession: LeaderLockFactory

  /**
   * How often a follower retries, in milliseconds. A function keeps the value
   * lazy so a host can read it from configuration after import. Defaults to
   * 2000; values below 50 are clamped so a misconfiguration cannot spin.
   */
  retryMs?: number | (() => number)

  /**
   * The advisory lock id, used only in log lines (the factory owns the actual
   * lock). Defaults to 0 when omitted.
   */
  lockId?: number
}

Classes

PgLeaderLockSession

The production session: one pg.Client, one advisory lock.

Exported so a host that owns its own connection settings (the platform API's SSL derivation, a Vault-backed URL resolver) can build a session directly and pass it to the provider as its createSession factory.

class PgLeaderLockSession implements LeaderLockSession {
  private lostHandler: (() => void) | null = null
  private lost = false
  private configured = false
  private heartbeat: ReturnType<typeof setInterval> | null = null
  private heartbeatInFlight = false

  /** Bound every lock-session query, including follower retries and shutdown. */
  private async query<R extends pg.QueryResultRow = pg.QueryResultRow>(
    text: string,
    values?: unknown[],
  ): Promise<pg.QueryResult<R>> {
    // node-postgres supports this on individual queries; @types/pg currently
    // lists it only on ClientConfig.
    const config: pg.QueryConfig & { query_timeout: number } = {
      text,
      values,
      query_timeout: 5_000,
    }
    try {
      return await this.client.query<R>(config)
    } catch (error) {
      this.markLost()
      // The client is being closed BECAUSE it just failed; an end() that also
      // fails changes nothing — the query error is rethrown below.
      void this.client.end().catch((_error) => undefined)
      throw error
    }
  }

  /** Demote immediately on a failed heartbeat; PostgreSQL expires a silent holder independently. */
  private markLost = (): void => {
    if (this.lost) return
    this.lost = true
    if (this.heartbeat) clearInterval(this.heartbeat)
    this.heartbeat = null
    this.lostHandler?.()
  }

  /**
   * Track the connection's lifecycle so a lost session demotes the leader.
   *
   * @param client - A connected client owned exclusively by this session.
   * @param lockId - The advisory lock id to hold.
   */
  constructor(
    private readonly client: pg.Client,
    private readonly lockId: number,
  ) {
    // `error` covers a socket/network failure; `end` covers the backend ending
    // the session (a server restart, an idle-session kill). Either way the lock
    // is gone.
    this.client.on('error', (error) => {
      getLogger().warn('Leadership lock connection error', { error })
      this.markLost()
    })
    this.client.on('end', this.markLost)
  }

  /** {@inheritDoc LeaderLockSession.tryLock} */
  async tryLock(): Promise<boolean> {
    if (this.lost) return false
    // TCP may stay half-open for hours after a VM freezes. PostgreSQL's own
    // idle-session timeout releases that orphan's lock even when its process
    // cannot run cleanup. A live holder keeps this dedicated session active.
    if (!this.configured) {
      await this.query("SET idle_session_timeout = '15s'")
      this.configured = true
    }
    const { rows } = await this.query<{ locked: boolean }>(
      'SELECT pg_try_advisory_lock($1) AS locked',
      [this.lockId],
    )
    const acquired = !this.lost && rows[0]?.locked === true
    if (acquired && !this.heartbeat) {
      this.heartbeat = setInterval(() => {
        if (this.lost || this.heartbeatInFlight) return
        this.heartbeatInFlight = true
        void this.query('SELECT 1')
          .catch((error: unknown) => {
            getLogger().warn('Leadership heartbeat failed', { error })
          })
          .finally(() => {
            this.heartbeatInFlight = false
          })
      }, 5_000)
      this.heartbeat.unref?.()
    }
    return acquired
  }

  /** {@inheritDoc LeaderLockSession.release} */
  async release(): Promise<void> {
    if (this.heartbeat) clearInterval(this.heartbeat)
    this.heartbeat = null
    if (!this.lost) {
      try {
        await this.query('SELECT pg_advisory_unlock($1)', [this.lockId])
      } catch (error) {
        // The session is ending either way, and a session lock is released by
        // the backend when it ends — an unlock failure changes nothing.
        getLogger().debug('Leadership advisory unlock failed; the session end releases it', {
          error,
        })
      }
    }
    try {
      await this.client.end()
    } catch (_error) {
      // Already ended.
    }
  }

  /** {@inheritDoc LeaderLockSession.onLost} */
  onLost(handler: () => void): void {
    this.lostHandler = handler
    if (this.lost) handler()
  }
}

Functions

createPostgresLockFactory(options)

Builds a LeaderLockFactory that opens PostgreSQL session locks.

Each call to the factory opens a NEW dedicated connection — a follower retries on its own connection, and a leader reconnects on a fresh one after losing the old.

function createPostgresLockFactory(options: PostgresLeaderLockOptions): LeaderLockFactory
  • options — The lock id, connection settings and optional connect hook.

Returns: A factory the leadership provider calls to open each session.

createProvider(options)

Creates an instance-leadership provider.

function createProvider(options: PostgresLeadershipProviderOptions): InstanceLeadershipProvider
  • options — The lock-session factory and retry interval.

Returns: A provider implementing the core InstanceLeadershipProvider contract.

Constants

provider

A provider that reads its connection settings from DATABASE_URL.

Its lock session is opened lazily, so importing (and bonding) this provider never connects. The lock id is the same one the API platform API has used for its singleton work; an app that shares a database with another leadership user must pass its OWN lockId.

const provider: InstanceLeadershipProvider

Core Interface

Implements @molecule/api-instance-leadership interface.

Bond Wiring

Setup function to register this provider with the core interface:

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

export function setupInstanceLeadershipPostgresql(): void {
  setProvider(provider)
}

Injection Notes

Requirements

Peer dependencies:

  • @molecule/api-bond ^1.0.1
  • @molecule/api-instance-leadership ^1.0.0

Environment Variables

  • DATABASE_URL (required) — PostgreSQL connection string
    • Setup: Use a direct connection or a session-mode pooler; transaction-mode pooling cannot retain advisory locks.

Runtime Dependencies

  • @molecule/api-bond

  • @molecule/api-instance-leadership

  • pg

  • Silent holders expire on the database. PostgreSQL 14+ is required. The dedicated session has a 15-second idle_session_timeout; a leader sends a bounded heartbeat every five seconds. A frozen VM or half-open connection therefore cannot retain leadership for hours. Heartbeat failure demotes the holder and closes its connection. Singleton work must stop promptly in onLost and remain safe to retry after an interruption.

  • A leader that loses its connection demotes itself. The provider stops treating itself as leader and calls onLost; a follower retries every retryMs (default 2 s) and takes over within seconds.

  • prepareThreshold/pooling caveat. The lock MUST be taken on a direct client connection, never through a transaction-mode pooler (PgBouncer in transaction mode), which multiplexes statements from many clients onto a session: a lock "held" there is held by an unrelated session. Use a session-mode pooler or a direct connection.

  • Pick a lock id nobody else uses. Advisory locks share one namespace per database. The exported provider uses 8675310; a second application sharing the same database must pass its own id to createPostgresLockFactory.

  • This bond runs no singleton work itself. It only tells the application which instance leads; the loops belong to the app (onAcquired/onLost).