@molecule/api-scheduler-postgresql

Provider bond · scheduler · API (Node) · v1.1.4 · Apache-2.0

PostgreSQL-coordinated scheduler provider for @molecule/api-scheduler: in-process timers that take a per-task advisory lock so a scheduled task runs ONCE across every API instance.

npm install @molecule/api-scheduler-postgresql

npm · Source on GitHub · Implements @molecule/api-scheduler

How it works

@molecule/api-scheduler-postgresql is a provider bond on the API (Node) side: it implements the scheduler core interface (@molecule/api-scheduler) 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-scheduler

Secrets: DATABASE_URL

Reference

PostgreSQL-coordinated scheduler provider for @molecule/api-scheduler: in-process timers that take a per-task session advisory lock, so a scheduled task runs ONCE across every API instance instead of once per instance.

import { schedule, setProvider, start } from '@molecule/api-scheduler'
import { createProvider } from '@molecule/api-scheduler-postgresql'

setProvider(createProvider()) // reads DATABASE_URL lazily
schedule({ name: 'nightly-sweep', intervalMs: 3_600_000, handler: sweep })
start()

The default scheduler (@molecule/api-scheduler-default) runs every task on every instance. With one API process that is correct; behind a load balancer it means N executions per interval — harmless for a sweep that is idempotent, corrupting for anything that mutates shared state. This provider keeps the same timer model (intervals, stagger, getStatus) and adds the lock.

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-scheduler-postgresql @molecule/api-bond @molecule/api-scheduler pg
npm install -D @types/pg

API

Interfaces

PostgresTaskRunLock

One run lock backed by a dedicated PostgreSQL connection.

interface PostgresTaskRunLock extends SchedulerTaskRunLock {
  /** {@inheritDoc SchedulerTaskRunLock.close} */
  close(): Promise<void>
}

PostgresSchedulerOptions

Options for the PostgreSQL-coordinated scheduler provider.

interface PostgresSchedulerOptions {
  /**
   * Stagger offset in milliseconds between task starts, to avoid a thundering
   * herd on boot. Defaults to 2000. Each task's delay is
   * `(index % enabledTaskCount) * staggerMs`.
   */
  staggerMs?: number
  /**
   * The advisory-lock class id. Advisory locks are per database and share one
   * namespace, so this MUST differ from other advisory-lock users (the
   * migration runner and instance leadership each use their own).
   * Defaults to `8675311`.
   */
  lockClassId?: number

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

  /**
   * Open and connect a client. Injected by a host that owns its connection
   * settings (and by tests); the default creates a `pg.Client` from the
   * connection string.
   */
  connect?: (connectionString: string) => Promise<pg.Client>

  /**
   * Whether a failing lock lookup skips the run (the default, safe) or lets it
   * proceed uncoordinated. Leave this `false`: a skipped sweep is retried on
   * the next tick, while two concurrent runs can corrupt shared state.
   */
  runUncoordinatedOnLockError?: boolean

  /**
   * A pre-built run lock. Injected by tests (and by a host that already owns a
   * lock connection); when omitted the provider builds a PostgreSQL one.
   */
  lock?: SchedulerTaskRunLock
}

Functions

advisoryKeyForTask(taskName)

Derive a stable 31-bit advisory-lock key from a task name.

The name is the contract shared by every instance: the same task must map to the same key in every process, so the hash is fixed rather than salted. FNV-1a over UTF-16 code units, masked to 31 bits (the second key of pg_try_advisory_lock(classId, objectId) is a signed int4).

function advisoryKeyForTask(taskName: string): number
  • taskName — The scheduler task name.

Returns: A non-negative 31-bit integer.

createPostgresTaskRunLock(options)

Build a run lock over a dedicated PostgreSQL connection.

The connection is opened lazily on the first run and re-opened after a failure. A lock query that cannot reach the database returns false (the run is skipped) unless runUncoordinatedOnLockError is set.

function createPostgresTaskRunLock(options: {
  connectionString?: string
  lockClassId?: number
  runUncoordinatedOnLockError?: boolean
  /**
   * Open and connect a client. Injected by tests (and by a host that owns its
   * connection settings); the default creates a `pg.Client` from the
   * connection string.
   *
   * @param connectionString - The resolved connection string.
   * @returns A connected client.
   */
  connect?: (connectionString: string) => Promise<pg.Client>
}): PostgresTaskRunLock
  • options — Connection string, advisory-lock class id and failure policy.

Returns: The run lock.

createProvider(options)

Creates a scheduler provider that runs each task once across every instance.

function createProvider(options?: PostgresSchedulerOptions): SchedulerProvider
  • options — Stagger, connection and lock configuration.

Returns: A SchedulerProvider whose runs are coordinated by a per-task PostgreSQL advisory lock.

Core Interface

Implements @molecule/api-scheduler interface.

Injection Notes

Requirements

Peer dependencies:

  • @molecule/api-bond ^1.0.1
  • @molecule/api-scheduler ^1.1.1

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-scheduler

  • pg

  • A skipped tick is not a run. Only the instance that wins the lock records lastRunAt/totalRuns; the others log at debug and wait for the next tick. A status read on a follower therefore shows the task's last run on THIS instance.

  • The lock is held for the whole run, not a lease with a TTL: a slow run cannot overlap its successor. If the holder's connection dies mid-run, PostgreSQL releases the lock and another instance may start the task while the first is still finishing — keep handlers idempotent.

  • If the lock store is unreachable the run is SKIPPED (logged at warn), because two concurrent runs are worse than one missed sweep. Set runUncoordinatedOnLockError only for a task that is safe to double-run.

  • Advisory locks share one namespace per database. lockClassId defaults to 8675311; a host that uses other advisory locks (the migration runner uses 8675309, instance leadership 8675310) must pass a distinct class id.

  • Transaction-mode poolers break session locks. Connect directly or through a session-mode pooler (PgBouncer pool_mode=session).