Skip to Content

Run workers

Start delivery explicitly, supervise it, shut it down without losing in-flight work, and know what each failure does.

Nothing is sent until a worker runs. A worker is a process you start: it claims due deliveries, resolves each endpoint, signs and sends the request, and records the attempt. You own the process, its database pool, and its supervision.

The smallest worker

worker.ts
import { pool, webhooks } from './webhooks.js'

const stop = new AbortController()
process.once('SIGTERM', () => stop.abort())
process.once('SIGINT', () => stop.abort())

await webhooks.check() // fails fast if migrations are missing
await webhooks.worker.run({ signal: stop.signal }) // returns after a clean shutdown
await pool.end()

Run it as its own process next to your app. The worker reference lists every option. After a batch that made an attempt, run() starts the next batch at once; after an empty batch it waits pollIntervalMs (default 1 second). Run as many workers as you like: they coordinate through PostgreSQL leases, share the per-endpoint limits, and cover every scope in their database and schema.

runOnce() processes one bounded batch and returns counts, for schedulers and tests:

const result = await webhooks.worker.runOnce()
// { claimed, succeeded, retried, failed, stale }

To deliver from a scheduled function instead of a long-running process, see serverless and cron.

A supervised worker process

The package ships a complete entrypoint. It validates configuration, listens for signals, checks the schema, runs, and exits nonzero on failure after closing its pool.

examples/operations/worker.ts
import { createWebhooks } from 'good-webhooks'
import { Pool } from 'pg'
import { errorDetails, readOperationsConfig } from './config.ts'

const stop = new AbortController()
let pool: Pool | undefined
let failed = false
let phase = 'configuration'
const requestStop = () => stop.abort()
const fail = (error: unknown, at: string) => {
  failed = true
  process.exitCode = 1
  console.error(
    JSON.stringify({ event: 'webhooks.worker.failed', phase: at, ...errorDetails(error) }),
  )
  stop.abort()
}

// Register process handlers before reading configuration or starting database I/O.
process.on('SIGTERM', requestStop)
process.on('SIGINT', requestStop)

try {
  const config = readOperationsConfig('worker')
  pool = new Pool(config.database)
  // The pool is lazy. This listener exists before the first connection is opened.
  pool.on('error', (error) => fail(error, 'pool'))
  // Pool errors cover idle connections. Transactions also need a checked-out client listener.
  const clientError = (error: Error) => fail(error, 'database')
  pool.on('acquire', (client) => client.on('error', clientError))
  pool.on('release', (_error, client) => client.off('error', clientError))
  const webhooks = createWebhooks({
    database: pool,
    ...config.webhooks,
    // Hook events carry IDs and outcomes, never payloads or secrets.
    hooks: {
      onAttempt: (attempt) =>
        console.log(JSON.stringify({ event: 'webhooks.attempt', ...attempt })),
      onEndpointPaused: (pause) =>
        console.log(JSON.stringify({ event: 'webhooks.endpoint.paused', ...pause })),
    },
  })
  phase = 'startup'
  await webhooks.check()
  if (!stop.signal.aborted) {
    console.log(JSON.stringify({ event: 'webhooks.worker.started' }))
    phase = 'run'
    // Unexpected failures stop the process. A supervisor owns restart backoff.
    await webhooks.worker.run({
      signal: stop.signal,
      pollIntervalMs: config.pollIntervalMs,
      shutdownGraceMs: 30_000,
    })
  }
} catch (error) {
  fail(error, phase)
} finally {
  stop.abort()
  try {
    await pool?.end()
  } catch (error) {
    fail(error, 'close')
  }
  process.off('SIGTERM', requestStop)
  process.off('SIGINT', requestStop)
  if (!failed) console.log(JSON.stringify({ event: 'webhooks.worker.stopped' }))
}

Configure it through the environment:

VariableRequiredDefault
DATABASE_URLyes
WEBHOOK_ENCRYPTION_KEYyes
WEBHOOK_SCHEMApublic
WEBHOOK_POLL_INTERVAL_MS1000
WEBHOOK_DB_CONNECT_TIMEOUT_MS5000
WEBHOOK_DB_STATEMENT_TIMEOUT_MS10000
WEBHOOK_ALLOW_LOCALHOST
  • DATABASE_URL: the PostgreSQL connection string.
  • WEBHOOK_ENCRYPTION_KEY: the key that encrypted the registered endpoints.
  • WEBHOOK_SCHEMA: must match the migrations and the producer.
  • WEBHOOK_POLL_INTERVAL_MS: the wait after an empty batch.
  • WEBHOOK_DB_CONNECT_TIMEOUT_MS: the database connection timeout.
  • WEBHOOK_DB_STATEMENT_TIMEOUT_MS: the statement timeout. The client query timeout is one second longer.
  • WEBHOOK_ALLOW_LOCALHOST: true permits loopback HTTP receivers. Use it in development only.

Run it from a checkout with node packages/good-webhooks/examples/operations/worker.ts, or copy it and replace the event map with yours. It logs JSON lines without payloads or secrets: webhooks.worker.started, webhooks.worker.failed, and webhooks.worker.stopped, plus webhooks.attempt and webhooks.endpoint.paused from its hooks. The library itself writes no logs. For Better Auth management, see add delivery to Better Auth.

Never generate a fresh encryption key on startup. A wrong but well-formed key fails when the worker first decrypts an endpoint secret, not necessarily at startup.

Shut down cleanly

Abort the signal to stop. The worker stops claiming, gives requests already being sent up to shutdownGraceMs (30 seconds by default), cancels the rest, records every outcome, and then run() resolves. Await it before closing the pool, and give your supervisor a kill deadline that covers the grace period, the final writes, and pool closure.

A cancelled request may still have reached the receiver. It is retried, which is one reason receivers deduplicate.

Bound database waits

The example configuration sets connection, statement, and idle-in-transaction timeouts, and ten pool connections per process:

examples/operations/config.ts
import { events } from '../basic/events.ts'

function required(env: NodeJS.ProcessEnv, name: string): string {
  const value = env[name]
  if (!value?.trim()) throw new Error(`${name} is required.`)
  return value
}

function integer(
  env: NodeJS.ProcessEnv,
  name: string,
  fallback: number,
  min: number,
  max: number,
): number {
  const raw = env[name]
  const value = raw === undefined ? fallback : /^\d+$/.test(raw) ? Number(raw) : NaN
  if (!Number.isSafeInteger(value) || value < min || value > max) {
    throw new Error(`${name} must be an integer between ${min} and ${max}.`)
  }
  return value
}

/** Importing this module reads no environment, opens no connection, and starts no worker. */
export function readOperationsConfig(
  role: 'worker' | 'cleanup' | 'run-once',
  env: NodeJS.ProcessEnv = process.env,
) {
  const connectionString = required(env, 'DATABASE_URL')
  try {
    const url = new URL(connectionString)
    if (!['postgres:', 'postgresql:'].includes(url.protocol) || !url.hostname) throw new Error()
  } catch {
    throw new Error('DATABASE_URL must be a PostgreSQL connection URL.')
  }
  const encryptionKey = required(env, 'WEBHOOK_ENCRYPTION_KEY')
  const localhost = env.WEBHOOK_ALLOW_LOCALHOST
  if (localhost !== undefined && localhost !== 'true' && localhost !== 'false') {
    throw new Error('WEBHOOK_ALLOW_LOCALHOST must be true or false.')
  }
  const statementTimeout = integer(env, 'WEBHOOK_DB_STATEMENT_TIMEOUT_MS', 10_000, 100, 120_000)
  return {
    database: {
      connectionString,
      application_name: `webhooks-example-${role}`,
      max: 10,
      connectionTimeoutMillis: integer(env, 'WEBHOOK_DB_CONNECT_TIMEOUT_MS', 5_000, 100, 60_000),
      statement_timeout: statementTimeout,
      query_timeout: statementTimeout + 1_000,
      idle_in_transaction_session_timeout: statementTimeout,
      idleTimeoutMillis: 30_000,
    },
    webhooks: {
      events,
      encryptionKey,
      schema: env.WEBHOOK_SCHEMA ?? 'public',
      allowLocalhost: localhost === 'true',
    },
    pollIntervalMs: integer(env, 'WEBHOOK_POLL_INTERVAL_MS', 1_000, 10, 60_000),
    cleanupMaxBatches: integer(env, 'WEBHOOK_CLEANUP_MAX_BATCHES', 20, 1, 1_000),
    cleanupMaxDurationMs: integer(env, 'WEBHOOK_CLEANUP_MAX_DURATION_MS', 30_000, 100, 3_600_000),
    runOnceMaxDurationMs: integer(env, 'WEBHOOK_RUN_ONCE_MAX_DURATION_MS', 30_000, 100, 3_600_000),
  }
}

/** Log operational errors without dumping configuration, payloads, or signing material. */
interface ErrorDetails {
  name: string
  message: string
  code?: string
  causes?: ErrorDetails[]
}
export function errorDetails(error: unknown): ErrorDetails {
  const details = singleErrorDetails(error)
  if (error instanceof AggregateError)
    details.causes = error.errors.slice(0, 10).map(singleErrorDetails)
  return details
}

function singleErrorDetails(error: unknown): ErrorDetails {
  return {
    name: error instanceof Error ? error.name : 'Error',
    message: error instanceof Error ? error.message : 'Unexpected non-Error failure.',
    ...(error !== null &&
    typeof error === 'object' &&
    'code' in error &&
    typeof error.code === 'string'
      ? { code: error.code }
      : {}),
  }
}

Budget pool connections across producers, workers, and cleanup jobs. A client-side timeout does not guarantee server-side cancellation.

What failures do

Without onError, an internal failure rejects run() and the process exits; let your supervisor restart it with backoff. If you pass onError to log and continue, watch that deliveries keep moving. Receiver failures are not internal failures; they follow the retry policy, and an endpoint that keeps failing is paused automatically. The worker reports errors thrown by hooks like internal failures, after it records the outcome.

For metrics and logs per attempt, pass an onAttempt hook to the engine. It receives the outcome, status, error, and duration of every attempt.

Every failure below ends with the delivery retried under the same event ID, or the process exiting for a supervisor to restart. Each case is checked by a test.

  • Worker killed mid-request: the attempt is abandoned when its lease expires, and another worker retries the delivery.
  • Worker killed after the receiver accepted: the same happens. The receiver sees the same event.id twice, and its deduplication absorbs it.
  • Receiver hangs: the request is cancelled at timeoutMs and retried on schedule.
  • Database connection drops: run() rejects. The half-finished attempt is recovered when its lease expires.
  • Database unreachable or locked at startup: check() fails within your connection or statement timeout, before anything is claimed.
  • Wrong encryption key: the worker exits without consuming an attempt.
  • SIGTERM during a request: the request gets shutdownGraceMs to finish, its outcome is recorded, and run() resolves.
  • SIGKILL: leases are left behind and recovered by the next worker after leaseMs.
  • Schema older or newer than the package: check() throws SCHEMA_MISMATCH naming the SQL to apply.

A worker claims a delivery by writing an attempt with a lease before sending. If it dies, the lease expires after leaseMs (60 seconds by default) and the next batch recovers it. Lease tokens are fenced: a late worker whose lease expired cannot record a result, so two workers never both record success for one attempt.

These behaviors are verified on a single PostgreSQL instance with local receivers. They do not cover database failover or throughput limits. Workers never prune history; schedule cleanup separately.

Watch the backlog

A single failed attempt is normal. Alert when the queue stops draining instead. deliveries.stats() reports one scope's backlog:

backlog.ts
import { webhooks } from './webhooks.js'

const { deliveries, oldestPendingAgeMs, attemptsLastHour } = await webhooks.deliveries.stats()

Alert on two numbers:

  • deliveries.pending keeps growing across checks.
    • Workers are stopped or too slow for the volume.
  • oldestPendingAgeMs passes the delay you accept.
    • Some delivery has waited longer than its receiver can tolerate.

pending also holds deliveries waiting for a retry and deliveries behind a paused endpoint. With the default schedule a delivery to a failing receiver stays pending for more than a day, so set the age threshold with that in mind. attemptsLastHour shows whether workers are making attempts at all.

Each call covers one scope. Poll it about once a minute from a status check, not on every request: it reads the scope's whole retained history. See the cost. For per-attempt metrics, use the OpenTelemetry recipe.

On this page