@agendajs/postgres-backend

中文文档
3.0.7发布于 2026/10/31MITTypeScriptES Module构建来源已验证近 30 天下载 1.8万

PostgreSQL backend for Agenda job scheduler with LISTEN/NOTIFY support

原始使用文档
文档目录19 节
  1. Features
  2. Installation
  3. Usage
  4. Basic Usage
  5. Configuration Options
  6. Using an Existing Pool
  7. How It Works
  8. Storage
  9. Real-Time Notifications
  10. Distributed Locking
  11. Database Indexes
  12. Job Logging
  13. Automatic Usage
  14. Standalone Usage
  15. Manual Schema Management
  16. Testing
  17. Available Scripts
  18. Requirements
  19. License

@agendajs/postgres-backend

PostgreSQL backend for Agenda job scheduler with LISTEN/NOTIFY support for real-time job processing.

Features

  • Full PostgreSQL storage backend for Agenda jobs
  • Real-time job notifications using PostgreSQL LISTEN/NOTIFY
  • Automatic schema creation with optimized indexes
  • Connection pooling via pg library
  • TypeScript support with full type definitions

Installation

npm install @agendajs/postgres-backend
# or
pnpm add @agendajs/postgres-backend
# or
yarn add @agendajs/postgres-backend

Usage

Basic Usage

import { Agenda } from 'agenda';
import { PostgresBackend } from '@agendajs/postgres-backend';

// Create agenda with PostgreSQL backend
const agenda = new Agenda({
  backend: new PostgresBackend({
    connectionString: 'postgresql://user:pass@localhost:5432/mydb'
  })
});

// Define jobs
agenda.define('send-email', async (job) => {
  const { to, subject, body } = job.attrs.data;
  await sendEmail(to, subject, body);
});

// Start processing
await agenda.start();

// Schedule jobs
await agenda.every('5 minutes', 'send-email', { to: '[email protected]', subject: 'Hello', body: 'World' });
await agenda.schedule('in 10 minutes', 'send-email', { to: '[email protected]', subject: 'Hi', body: 'There' });

Configuration Options

import { PostgresBackend } from '@agendajs/postgres-backend';

const backend = new PostgresBackend({
  // PostgreSQL connection string (required unless pool/poolConfig is provided)
  connectionString: 'postgresql://user:pass@localhost:5432/mydb',

  // Or use pool configuration (creates a new pool)
  poolConfig: {
    host: 'localhost',
    port: 5432,
    database: 'mydb',
    user: 'user',
    password: 'pass',
    max: 20 // max pool size
  },

  // Table name for jobs (default: 'agenda_jobs')
  tableName: 'agenda_jobs',

  // Channel name for LISTEN/NOTIFY (default: 'agenda_jobs')
  channelName: 'agenda_jobs',

  // Name to identify this Agenda instance (stored as lastModifiedBy)
  name: 'worker-1',

  // Whether to create the table and indexes on connect (default: true)
  ensureSchema: true,

  // Sort order for job queries
  sort: {
    nextRunAt: 'asc',
    priority: 'desc'
  }
});

Using an Existing Pool

If your application already has a PostgreSQL connection pool, you can pass it directly. The pool will not be closed when Agenda disconnects:

import { Pool } from 'pg';
import { PostgresBackend } from '@agendajs/postgres-backend';

// Your app's existing pool
const pool = new Pool({ connectionString: 'postgresql://...' });

const backend = new PostgresBackend({ pool });

// After agenda.stop(), your pool is still usable

How It Works

Storage

The backend stores jobs in a PostgreSQL table with the following structure:

  • id - UUID primary key
  • name - Job name
  • priority - Job priority (higher = more urgent)
  • next_run_at - When the job should run next
  • type - Job type ('normal' or 'single')
  • locked_at - Lock timestamp for distributed execution
  • data - JSONB payload for job data
  • And other metadata fields...

Real-Time Notifications

Unlike MongoDB, PostgreSQL has built-in pub/sub via LISTEN/NOTIFY. When a job is saved, a notification is published to all listening Agenda instances, triggering immediate job processing without waiting for the next poll interval.

This means:

  • Lower latency for job execution
  • Reduced database polling overhead
  • Efficient cross-process coordination

Distributed Locking

The backend uses PostgreSQL's FOR UPDATE SKIP LOCKED to atomically lock jobs for processing, preventing duplicate execution across multiple Agenda instances.

Database Indexes

When ensureSchema: true (default), the following indexes are created:

-- Main index for finding and locking next job
CREATE INDEX agenda_jobs_find_and_lock_idx
  ON agenda_jobs (name, next_run_at, priority DESC, locked_at, disabled)
  WHERE disabled = FALSE;

-- Index for single jobs (upsert operations)
CREATE UNIQUE INDEX agenda_jobs_single_job_idx
  ON agenda_jobs (name) WHERE type = 'single';

-- Index for locked_at (stale lock detection)
CREATE INDEX agenda_jobs_locked_at_idx
  ON agenda_jobs (locked_at) WHERE locked_at IS NOT NULL;

-- Index for next_run_at queries
CREATE INDEX agenda_jobs_next_run_at_idx
  ON agenda_jobs (next_run_at) WHERE next_run_at IS NOT NULL;

Job Logging

PostgresBackend includes a built-in PostgresJobLogger that stores structured job lifecycle events in a dedicated table (agenda_logs by default). The logger is lightweight and only creates its table on first use.

Automatic Usage

When you enable logging in Agenda, the backend's built-in logger is used automatically:

const agenda = new Agenda({
  backend: new PostgresBackend({ connectionString: 'postgresql://...' }),
  logging: true  // Uses PostgresJobLogger automatically
});

Standalone Usage

You can also use PostgresJobLogger independently — for example, to log to PostgreSQL while using a different backend for storage:

import { PostgresJobLogger } from '@agendajs/postgres-backend';
import { Pool } from 'pg';

const logger = new PostgresJobLogger({
  pool: new Pool({ connectionString: 'postgresql://...' }),
  logTableName: 'agenda_logs'       // Optional: table name (default: 'agenda_logs')
});

// Use with any backend
import { MongoBackend } from '@agendajs/mongo-backend';
const agenda = new Agenda({
  backend: new MongoBackend({ mongo: db }),
  logging: logger
});

See the Agenda README for full logging documentation.

Manual Schema Management

If you prefer to manage the schema yourself (set ensureSchema: false):

import { getCreateTableSQL, getCreateIndexesSQL } from '@agendajs/postgres-backend';

const tableName = 'agenda_jobs';

// Create table
await pool.query(getCreateTableSQL(tableName));

// Create indexes
for (const sql of getCreateIndexesSQL(tableName)) {
  await pool.query(sql);
}

Testing

Tests require a PostgreSQL database. The easiest way is to use Docker:

# Start PostgreSQL container and run tests
pnpm test:docker

# Or manually:
pnpm docker:up        # Start PostgreSQL container
pnpm test:postgres    # Run tests
pnpm docker:down      # Stop container

You can also use an existing PostgreSQL database:

POSTGRES_TEST_URL=postgresql://user:pass@localhost:5432/agenda_test pnpm test

Available Scripts

ScriptDescription
pnpm testRun tests (requires PostgreSQL or Docker)
pnpm test:postgresRun tests with local Docker PostgreSQL
pnpm test:dockerStart container, run tests, stop container
pnpm docker:upStart PostgreSQL container
pnpm docker:downStop PostgreSQL container
pnpm docker:logsView container logs

Requirements

  • Node.js >= 18.0.0
  • PostgreSQL >= 12 (for gen_random_uuid() support)
  • Agenda >= 6.0.0

License

MIT

版本与发布记录

@agendajs/postgres-backend 共发布 11 个版本,首次发布于 2026/01/26;过去 12 个月发布了 11 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.0.7latest2026/10/317 天前
3.0.62026/07/213 个月前
3.0.52026/05/095 个月前
3.0.42026/04/027 个月前
3.0.32026/02/168 个月前
3.0.22026/02/148 个月前

其他发布通道:alpha → 1.0.0-alpha.0。

关于 @agendajs/postgres-backend 的常见问题

@agendajs/postgres-backend 是什么?

PostgreSQL backend for Agenda job scheduler with LISTEN/NOTIFY support

如何安装 @agendajs/postgres-backend?

在项目目录运行 npm install @agendajs/postgres-backend,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:agenda(6.2.7)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@agendajs/postgres-backend 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@agendajs/postgres-backend 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@agendajs/postgres-backend 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@agendajs/postgres-backend 可以商用吗?

@agendajs/postgres-backend 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@agendajs/postgres-backend 的下载量有多少?

根据 npm 官方下载统计,@agendajs/postgres-backend 在 2026/10/05 – 2026/11/03 这 30 天内被下载 18,311 次,日均约 610 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@agendajs/postgres-backend 还在维护吗?

最新版本 3.0.7 发布于 2026/10/31(7 天前);至今共发布 11 个版本,其中过去 12 个月发布了 11 个;首次发布于 2026/01/26。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。