PostgreSQL Notify Adapter

Wake workers with PostgreSQL LISTEN/NOTIFY: no extra service, drivers pg, postgres.js and Bun SQL.

createPgNotifyAdapter uses PostgreSQL's built-in LISTEN/NOTIFY mechanism. No additional infrastructure beyond your existing PostgreSQL database — it is already included in @queuert/postgres.

Install

Terminal

npm install @queuert/postgres

Setup

Each example's notify provider and adapter:

The provider owns a dedicated LISTEN client taken from the pool, so it implements close.

src/provider.ts

import type { PgNotifyProvider } from "@queuert/postgres";
import type { Pool, PoolClient } from "pg";

export const createPgPoolNotifyProvider = ({ pool }: { pool: Pool }): PgNotifyProvider => {
  let listenClient: PoolClient | null = null;
  let connectingPromise: Promise<PoolClient> | null = null;
  let closed = false;

  const handlers = new Map<string, (message: string) => void>();
  let queryQueue: Promise<void> = Promise.resolve();

  const enqueueQuery = async (fn: () => Promise<unknown>): Promise<void> => {
    const result = queryQueue.then(fn, fn);
    queryQueue = result.then(
      () => {},
      () => {},
    );
    return result.then(() => {});
  };

  const releaseListenClient = (): void => {
    if (listenClient) {
      listenClient.removeAllListeners("notification");
      listenClient.release();
      listenClient = null;
    }
  };

  const ensureListenClient = async (): Promise<PoolClient> => {
    if (closed) throw new Error("Provider is closed");
    if (listenClient) return listenClient;
    if (connectingPromise) return connectingPromise;

    connectingPromise = pool.connect().then((client) => {
      connectingPromise = null;
      if (closed) {
        client.release();
        throw new Error("Provider is closed");
      }
      listenClient = client;
      listenClient.on("notification", (msg: { channel: string; payload?: string }) => {
        handlers.get(msg.channel)?.(msg.payload ?? "");
      });
      return listenClient;
    });

    return connectingPromise;
  };

  return {
    publish: async (channel, messages) => {
      if (closed) throw new Error("Provider is closed");
      const client = await pool.connect();
      try {
        await client.query("SELECT pg_notify($1, message) FROM unnest($2::text[]) AS message", [
          channel,
          messages,
        ]);
      } finally {
        client.release();
      }
    },
    subscribe: async (channel, onMessage) => {
      const client = await ensureListenClient();
      handlers.set(channel, onMessage);
      await enqueueQuery(async () => client.query(`LISTEN "${channel}"`));
      return async () => {
        handlers.delete(channel);
        try {
          await enqueueQuery(async () => client.query(`UNLISTEN "${channel}"`));
        } finally {
          if (handlers.size === 0) {
            releaseListenClient();
          }
        }
      };
    },
    close: async (): Promise<void> => {
      closed = true;
      releaseListenClient();
      handlers.clear();
    },
  };
};

src/index.ts

await using drivers = new AsyncDisposableStack();

// Create PostgreSQL connection pool
const pool = drivers.adopt(
  new Pool({ connectionString: pg.connectionString, max: 10 }),
  async (pool) => pool.end(),
);

// Create the notify provider using pg
const notifyProvider = createPgPoolNotifyProvider({ pool });

// Create the notify adapter
await using notifyAdapter = createPgNotifyAdapter({ notifyProvider });

The notify adapter and your clients are held with await using. A client that is not disposable itself is adopted by a drivers AsyncDisposableStack. Disposal runs in reverse order, so when the scope ends the notify adapter closes before your clients, in the shutdown order.

Configuration

createPgNotifyAdapter options

Notify provider

A PgNotifyProvider bridges your PostgreSQL client with the adapter. Each Setup tab is a complete provider for its driver; to use another client, implement the same members:

PgNotifyProvider

  • Sends a batch of messages to a named channel in one statement.
  • Listens on a channel and invokes a callback when messages arrive. Returns a dispose function to unsubscribe.
  • close optional
    Only needed when the provider owns resources (e.g. a dedicated LISTEN client). notifyAdapter.close() invokes it.

Testing your provider

pgNotifyProviderConformanceCases from @queuert/postgres/conformance check a provider you write: they are every case a notify adapter must pass, run against the context createPgNotifyProviderConformanceContext({ createNotifyProvider }) returns: each case builds its own notify adapter over a new provider from your factory and closes both when it ends. The suite drives no test runner: your test file owns the connections in its own hooks and registers one test per case. Every example's src/provider.spec.ts is a working template:

src/provider.spec.ts

describe("postgresql/notify-pg provider conformance", () => {
  let pg: AcquiredPostgres;
  let pool: Pool;
  let context: NotifyAdapterConformanceContext;

  beforeAll(async () => {
    pg = await acquirePostgres("postgres:18", import.meta.url);
    pool = new Pool({ connectionString: pg.connectionString, max: 10 });
    context = createPgNotifyProviderConformanceContext({
      createNotifyProvider: async () => createPgPoolNotifyProvider({ pool }),
    });
  }, 60_000);

  afterAll(async () => {
    await pool.end();
    await pg[Symbol.asyncDispose]();
  });

  for (const conformanceCase of pgNotifyProviderConformanceCases) {
    test(conformanceCase.title, async () => {
      await conformanceCase.run(context);
    });
  }
});

The full API is in the conformance reference.

Channels

The adapter uses three notification channels (configurable prefix, default queuert):

  • {prefix}_sched job scheduled
    payload · job type name
    Published when jobs become pending. Wakes idle workers.
  • {prefix}_chainc chain completed
    payload · chain id
    Published when a chain completes. Wakes clients awaiting chain results.
  • {prefix}_atls attempt lost
    payload · job id
    Published when a running job's attempt is lost. Notifies workers of attempt loss.

Examples

@queuert/postgres · notify

esc

Search guides, integrations and every exported symbol.

↑ ↓ to navigate↵ to open