npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@wisemen/pgboss-nestjs-job

v8.0.0

Published

This package provides NestJS integration for PgBoss job queuing and processing.

Readme

PGBoss NestJS

This package provides NestJS integration for PgBoss job queuing and processing.

Upgrading

PgBoss 12.40.0 uses database schema version 48. If you disable automatic migrations with migrate: false, migrate the existing queue database before starting the upgraded workers.

Tracing

Scheduling jobs creates a PRODUCER span named send <queue>. Its W3C trace context is stored in the existing serialized job payload. Processing a job starts a new root CONSUMER span named after the job class and links it to the propagated producer context:

producer trace:  ... -> send <queue>
                           |
                           | span link
                           v
consumer trace:        <JobClass> -> handler/database spans

Each job execution therefore has an independent trace ID. Jobs queued without trace context, or with invalid trace context, still start an unlinked root consumer span.

Job Monitoring API

Register JobsApiModule.forRootAsync(...) in an HTTP-facing module to expose the GET /jobs and GET /jobs/:jobId monitoring endpoints. Queue names are static because they define request validation and Swagger metadata; resolve the application datasource through dependency injection.

import { Module } from '@nestjs/common'
import { DataSource } from 'typeorm'
import { JobsApiModule } from '@wisemen/pgboss-nestjs-job'

@Module({
  imports: [
    JobsApiModule.forRootAsync({
      queueNames: ['system', 'notifications'],
      inject: [DataSource],
      useFactory: (dataSource: DataSource) => ({ dataSource })
    })
  ]
})
export class ApiModule {}

Use controllers.index and controllers.detail to configure a route, Swagger tag/version, disable an endpoint, or provide application-specific decorators such as permissions.

Metrics

Register PgbossMetricsModule in the application that exposes metrics. Provide the queues that should be reported (including queues with no pending jobs) and the TypeORM data source that contains the pgboss schema.

@Module({
  imports: [
    PgbossMetricsModule.forRootAsync({
      inject: [DataSource],
      useFactory: (dataSource: DataSource) => ({
        dataSource,
        queueNames: ['email', 'notifications']
      })
    })
  ]
})
export class MetricsModule {}

Scheduling Jobs

To schedule jobs, you can use the PgBossScheduler which provides methods to schedule jobs to be processed by workers.

1. Create a job data type:

export interface MyJobData extends BaseJobData {
  uuid: string;
  // other data here
}

@PgBossJob("queue-name")
export class MyJob extends BaseJob<MyJobData> {
  constructor(uuid: string) {
    super({ uuid });
  }
}

2. Schedule the job using the PgBossScheduler:

import { PgBossScheduler } from "@wisemen/pgboss-nestjs-job";

@Injectable()
export class MyService {
  constructor(private readonly jobScheduler: PgBossScheduler) {}
  async scheduleMyJob(data: MyJobData, options?: PgBossScheduleOptions) {
    await this.jobScheduler.scheduleJob(new MyJob(data), options);
  }
}

3. Import the PgBossSchedulerModule:

You must provide database connection options to the PgBossSchedulerModule when importing it into your module.

@Module({
  imports: [
    PgBossSchedulerModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        connectionString: configService.getOrThrow("DATABASE_URI"),
      }),
    }),
  ],
  providers: [MyService],
})
export class SomeModule {}

Worker Setup

In order to process jobs, you need to set up a worker application that listens to a specific queue and handles the jobs.

1. Create an entrypoint that creates an NestJs application context instance that contains the PgBossWorkerModule.

The PgBossWorkerModule accepts various configuration options to customize its behavior.

  • dataBaseOptions (required): Database connection options for PgBoss.
  • queueName (required): The name of the queue to listen to.
  • concurrency (optional): The number of jobs to process concurrently (default is 1).
  • pollInterval (optional): The interval (in milliseconds) to poll for new jobs (default is 1000 ms).
  • batchSize (optional): The number of jobs to fetch in each batch (default is 1).
  • fetchRefreshThreshold (optional): The threshold to refresh job fetching (default is 5000 ms).
  • bouncerModule (optional): A module that provides a QueueBouncer to control job fetching.
@Module({
  imports: [
    AppModule.forRoot(),
    PgBossWorkerModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        dataBaseOptions: {
          connectionString: configService.getOrThrow("DATABASE_URI"),
        },
        queueName,
        concurrency, // The number of jobs to process concurrently
        batchSize, // The number of jobs to fetch
        fetchRefreshThreshold, // Refresh threshold to fetch jobs
        pollInterval, // The interval (in milliseconds) to poll for new jobs
        bouncerModule, // An optional bouncer which will prevent jobs from being fetched (see QueueBouncer section below)
      }),
    }),
  ],
})
class WorkerModule {}

class Worker extends WorkerContainer {
  async bootstrap(): Promise<INestApplicationContext> {
    return await NestFactory.createApplicationContext(WorkerModule);
  }
}

const _worker = new Worker();

QueueBouncer

Some workers / queues only need to run when some external service is online. The QueueBouncer base class is used by workers to determine wether they should poll for jobs or not by calling the canProceed method on the bouncer. This method typically performs the health check on an external service.

The queuebouncer is provided to the worker by creating and exportin a provider for the QueueBouncer class. An example module can be:

@Module({
  imports: [CuoptClientModule],
  providers: [{
    provide: QueueBouncer,
    useClass: CuoptWorkerBouncer
  }],
  exports: [QueueBouncer]
})
export class CuoptWorkerBouncerModule {}

When no bouncer is set, the package will default to AllowBouncer which never blocks a worker / queue from polling for jobs.

An example of a bouncer for an external cuopt system.

@Injectable()
export class CuoptWorkerBouncer extends QueueBouncer {
  private isCuoptRunning: boolean;
  private lastPolledAt: Date;
  private pollPromise: Promise<boolean> | undefined;

  constructor(private cuopt: CuoptClient) {
    super();
  }

  async canProceed(): Promise<boolean> {
    if (dayjs().diff(this.lastPolledAt, "seconds") > 2) {
      await this.pollCuopt();
    }

    return this.isCuoptRunning;
  }

  private async pollCuopt() {
    if (this.pollPromise !== undefined) {
      await this.pollPromise;
      return;
    }

    this.pollPromise = this.cuopt.isReady();

    try {
      this.isCuoptRunning = await this.pollPromise;
    } catch {
      this.isCuoptRunning = false;
    } finally {
      this.lastPolledAt = new Date();
    }
  }
}

Rate-limited queues

When a queue's jobs call an external API that is rate limited, give the queue a rate-limit bouncer. It reuses the QueueBouncer fetch-gate above — when the limit is reached the worker simply stops polling, so jobs wait in created instead of failing and burning retries — and keeps its state in Redis (shared across worker instances) on a Redis client your app owns and connects.

Use one dedicated queue per rate-limited API (the queue name is the limit key). Register the module once at the app root. It accepts anything exposing a node-redis client as .client; the package never opens or closes the connection itself, so the app connects it on startup and closes it on shutdown.

Option 1: reuse the app's @wisemen/nestjs-cache Redis client. A RedisCacheClient already exposes .client, so it can be returned as-is:

import { Cache, type RedisCacheClient } from '@wisemen/nestjs-cache'
import { PgbossRateLimitModule } from '@wisemen/pgboss-nestjs-job'

PgbossRateLimitModule.forRootAsync({
  imports: [DefaultCacheModule], // the app's configured CacheModule
  inject: [Cache],
  useFactory: (cache: RedisCacheClient) => cache
})

The Cache provider must be the Redis one. An in-memory cache has no .client, so the store reports itself unavailable and every bouncer falls back to its onStoreUnavailable policy.

Option 2: pass a node-redis client directly.

import { createClient } from 'redis'
import { PgbossRateLimitModule } from '@wisemen/pgboss-nestjs-job'

const redisClient = createClient({ url: process.env.REDIS_URL })
await redisClient.connect()

PgbossRateLimitModule.forRoot({ client: redisClient })

Or resolve it from DI when the client is already provided elsewhere:

PgbossRateLimitModule.forRootAsync({
  imports: [RedisConnectionModule],
  inject: [REDIS_CLIENT],
  useFactory: (client: RedisClientType) => ({ client })
})

Then pick the strategy — the base class that matches how much you know about the limit — and declare a bouncer for the queue:

// STATIC — a known budget (N requests per window)
@Bouncer(QueueName.STRIPE)
export class StripeBouncer extends StaticRateLimitBouncer {
  protected readonly options = { limit: 100, windowSeconds: 60 }
}

// HEADERS — the API reports its own budget via X-RateLimit-* / Retry-After
@Bouncer(QueueName.CUOPT)
export class CuoptBouncer extends HeaderRateLimitBouncer {
  protected readonly options = {} // optional custom header names
}

// FAILURE — nothing is known up front; back off only after a 429 / error
@Bouncer(QueueName.FLAKY)
export class FlakyBouncer extends FailureBackoffBouncer {
  protected readonly options = { backoffSeconds: 30, maxBackoffSeconds: 300 }
}

Register the bouncer as a provider in its queue's module (same as any QueueBouncer). The RedisRateLimitStore is injected automatically.

Feed usage back from the transport. All three strategies learn from the actual HTTP traffic, so wrap the @wisemen/node-fetch client that talks to the API with useRateLimiting. A client talks to exactly one rate-limited API, so bind that queue's bouncer directly — inject it (it is a provider) and pass it in:

constructor (private readonly bouncer: StripeBouncer) {
  this.client = createClient({ baseUrl: 'https://api.stripe.com' })
  useRateLimiting(this.client, this.bouncer)
}

The interceptor drives the bound bouncer on every call: static counts one request per call, header mirrors the reported budget, failure backs off on a throttled response or transport error. A throttled response records the cooldown and throws RateLimitError so the job is retried after the cooldown clears. Because it counts every request through the client, all real API usage counts against the budget, not only calls made from that queue's jobs.

Retries are what make the cooldown work, and pg-boss already provides them: every queue defaults to retryLimit: 2, which jobs inherit unless they override it — so a throttled job gets three attempts out of the box. Two things to know:

  • A busy queue may want more. Each attempt is spent on a throttle it may hit again once the cooldown clears, so a queue that is throttled often can exhaust three attempts and fail the job. Raise it per queue (createQueue/updateQueue with retryLimit, optionally retryBackoff) or per job via its options.
  • Never set retryLimit: 0 on a rate-limited queue. pg-boss retries only while retry_count < retry_limit, so with 0 the first throttle fails the job for good. The cooldown is still recorded — the API stays protected — but the job is lost unless the queue has a dead-letter queue.

Not every API answers with a 429. Throttling is 429 by default, but SAP and friends report it as a 503, a 500, sometimes even a 400. Name the statuses that mean "slow down" in the options and every strategy — plus the interceptor that throws RateLimitError — follows:

@Bouncer(QueueName.SAP)
export class SapBouncer extends StaticRateLimitBouncer {
  protected readonly options = { limit: 50, windowSeconds: 60, throttleStatuses: [503, 500] }
}

throttleStatuses replaces the default rather than adding to it, so include 429 explicitly if the API uses both. When a status code alone cannot say it, override the decision instead — it is the single point every strategy consults:

@Bouncer(QueueName.SAP)
export class SapBouncer extends StaticRateLimitBouncer {
  protected readonly options = { limit: 50, windowSeconds: 60 }

  override isThrottleResponse (status: number, headers: Record<string, string | undefined>): boolean {
    return status === 400 && headers['x-sap-throttled'] === 'true'
  }
}

The response body is deliberately not available here — the interceptor must not consume the stream. An API that only signals throttling in its payload should throw RateLimitError from its own client code.

Nor does every API call the cooldown header Retry-After. Name it once and every strategy honours it — including the interceptor that puts it on the error:

@Bouncer(QueueName.SAP)
export class SapBouncer extends StaticRateLimitBouncer {
  protected readonly options = { limit: 50, windowSeconds: 60, retryAfterHeader: 'x-retry-after' }
}

The value must be delta-seconds; a non-numeric or non-positive value is ignored and the strategy falls back to its own cooldown (DEFAULT_COOLDOWN_SECONDS for static and header, backoffSeconds for failure). An HTTP-date Retry-After is therefore not honoured — parse it in a isThrottleResponse override if you need it.

A throttled job says why it failed. RateLimitError carries the bouncer, the queue and the limit it hit, and the worker persists them to the job row's output:

{ "error": { "name": "RateLimitError", "bouncer": "StripeBouncer",
             "queue": "stripe", "limit": "100 per 60s",
             "signal": { "status": 429, "throttled": true } } }

These are enumerable own properties deliberately: the worker persists a failure as fail(..., { error }), so message and stack are dropped by JSON encoding and only fields like these survive. describeLimit() produces the limit string — override it on a bouncer to report something more specific.

Choose what happens when Redis is down. Rate limiting fails open by default: if Redis cannot answer, the gate allows and the queue runs at pg-boss speed. That keeps queues moving, but for an API that bans rather than throttles (OSRM and friends) flooding it is worse than stalling. Such a queue can opt to fail closed:

@Bouncer(QueueName.OSRM)
export class OsrmBouncer extends StaticRateLimitBouncer {
  protected readonly options = {
    limit: 20,
    windowSeconds: 60,
    onStoreUnavailable: StoreUnavailablePolicy.BLOCK
  }
}

The choice is per queue, because it depends on the API: BLOCK holds the queue for as long as Redis is unreachable (jobs stay queued and resume afterwards), ALLOW (default) keeps it running unprotected. Note this is only about Redis being unreachable — a reachable Redis always enforces the real limit.

The check happens once per poll, so a connection that drops mid-poll can let that one batch through even under BLOCK; the next poll sees Redis is gone and holds. Exposure is bounded by batchSize × workers, the same bound as counter lag below.

Notes:

  • Fail-open by default: if Redis is unavailable, bouncers allow work through rather than wedge the queue — see onStoreUnavailable above to invert that.
  • Keep rate-limit bouncers default-scoped (singleton) — do not mark them TRANSIENT/REQUEST.
  • The header strategy treats the reset header as epoch seconds; APIs that send delta-seconds need a custom adapter.
  • Enforcement is per-queue (no per-tenant sub-keys), and a poll can fetch a batch before the counter updates, so overshoot is bounded by batchSize × workers — lower batchSize on hot queues if needed.