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/postgresSetup
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 });A pass-through provider; it omits close.
src/provider.ts
import type { PgNotifyProvider } from "@queuert/postgres";
import type postgres from "postgres";
export const createPostgresJsNotifyProvider = ({
sql,
}: {
sql: postgres.Sql;
}): PgNotifyProvider => {
return {
publish: async (channel, messages) => {
await sql`SELECT pg_notify(${channel}, message) FROM json_array_elements_text(${JSON.stringify(messages)}::text::json) AS message`;
},
subscribe: async (channel, onMessage) => {
const subscription = await sql.listen(channel, onMessage);
return async () => {
await subscription.unlisten();
};
},
};
};src/index.ts
await using drivers = new AsyncDisposableStack();
// Create postgres-js connection
const sql = drivers.adopt(postgres(pg.connectionString, { max: 10 }), async (sql) => sql.end());
// Create the notify provider using postgres-js
const notifyProvider = createPostgresJsNotifyProvider({ sql });
// Create the notify adapter
await using notifyAdapter = createPgNotifyAdapter({ notifyProvider });A pass-through provider; it omits close.
src/provider.ts
import type { PgNotifyProvider } from "@queuert/postgres";
import type { SQL } from "bun";
export const createBunSqlNotifyProvider = ({ sql }: { sql: SQL }): PgNotifyProvider => {
return {
publish: async (channel, messages) => {
await sql`SELECT pg_notify(${channel}, message) FROM json_array_elements_text(${JSON.stringify(messages)}::text::json) AS message`;
},
subscribe: async (channel, onMessage) => {
const subscription = await sql.listen(channel, onMessage);
return async () => {
await subscription.unlisten();
};
},
};
};src/index.ts
// Create Bun.SQL connection
await using sql = new SQL(pg.connectionString, { max: 10 });
// Create the notify provider using Bun.SQL
const notifyProvider = createBunSqlNotifyProvider({ sql });
// 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
- notifyProvider requiredPgNotifyProviderSee Notify provider.
- string · default "queuert"Prefix for the three channel names.
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 optionalOnly 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);
});
}
});src/provider.spec.ts
describe("postgresql/notify-postgres-js provider conformance", () => {
let pg: AcquiredPostgres;
let sql: postgres.Sql;
let context: NotifyAdapterConformanceContext;
beforeAll(async () => {
pg = await acquirePostgres("postgres:18", import.meta.url);
sql = postgres(pg.connectionString, { max: 10 });
context = createPgNotifyProviderConformanceContext({
createNotifyProvider: async () => createPostgresJsNotifyProvider({ sql }),
});
}, 60_000);
afterAll(async () => {
await sql.end();
await pg[Symbol.asyncDispose]();
});
for (const conformanceCase of pgNotifyProviderConformanceCases) {
test(conformanceCase.title, async () => {
await conformanceCase.run(context);
});
}
});src/provider.spec.ts
describe("postgresql/notify-bun-sql provider conformance", () => {
let pg: AcquiredPostgres;
let sql: SQL;
let context: NotifyAdapterConformanceContext;
beforeAll(async () => {
pg = await acquirePostgres("postgres:18", import.meta.url);
sql = new SQL(pg.connectionString, { max: 10 });
context = createPgNotifyProviderConformanceContext({
createNotifyProvider: async () => createBunSqlNotifyProvider({ sql }),
});
}, 60_000);
afterAll(async () => {
await sql.close();
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 scheduledpayload · job type namePublished when jobs become pending. Wakes idle workers.
- {prefix}_chainc chain completedpayload · chain idPublished when a chain completes. Wakes clients awaiting chain results.
- {prefix}_atls attempt lostpayload · job idPublished when a running job's attempt is lost. Notifies workers of attempt loss.
Examples
@queuert/postgres · notify
- GitHub PostgreSQL LISTEN/NOTIFY via @queuert/postgres with the pg (node-postgres) client.
$ pnpm --filter example-postgresql-notify-pg startsrc/provider.tssrc/index.ts - GitHub PostgreSQL LISTEN/NOTIFY via @queuert/postgres with the postgres-js client.
$ pnpm --filter example-postgresql-notify-postgres-js startsrc/provider.tssrc/index.ts - GitHub PostgreSQL LISTEN/NOTIFY via @queuert/postgres using Bun's built-in SQL client — no external PostgreSQL dependencies.
$ pnpm --filter example-postgresql-notify-bun-sql startsrc/provider.tssrc/index.ts