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

@bernierllc/queue-manager

v1.6.0

Published

Robust message queue management with multiple backends, job processing, and failure handling

Readme

@bernierllc/queue-manager

Robust message queue management with multiple backends, job processing, priority handling, and automatic retry logic.

Installation

npm install @bernierllc/queue-manager

Built-in backends: 'memory' (in-process) and PostgresBackend (durable, see Durable Queue with Postgres).

Usage

Basic Queue Setup

import { QueueManager, JobPriority } from '@bernierllc/queue-manager';

// Create a queue with memory backend
const queue = new QueueManager('email-queue', {
  backend: 'memory',
  concurrency: 5,
  retryPolicy: {
    maxAttempts: 3,
    backoff: { type: 'exponential', delay: 1000, maxDelay: 30000 }
  }
});

// Register a job processor
queue.process('send-email', async (job) => {
  const { to, subject, body } = job.data;
  await sendEmail(to, subject, body);
  return { sent: true };
});

// Add a job to the queue
await queue.add('send-email', {
  to: '[email protected]',
  subject: 'Welcome',
  body: 'Welcome to our service!'
}, {
  priority: JobPriority.HIGH
});

Priority Handling

import { QueueManager, JobPriority } from '@bernierllc/queue-manager';

const queue = new QueueManager('tasks', { backend: 'memory' });

// Add jobs with different priorities
await queue.add('task', { type: 'urgent' }, { priority: JobPriority.CRITICAL });
await queue.add('task', { type: 'important' }, { priority: JobPriority.HIGH });
await queue.add('task', { type: 'routine' }, { priority: JobPriority.NORMAL });
await queue.add('task', { type: 'background' }, { priority: JobPriority.LOW });

// Jobs are processed in priority order (CRITICAL > HIGH > NORMAL > LOW)

Delayed Jobs

// Schedule a job to run after 1 hour
await queue.add('reminder', {
  message: 'Time to review'
}, {
  delay: 3600000 // 1 hour in milliseconds
});

// Schedule with custom retry policy
await queue.add('api-call', {
  endpoint: '/users',
  method: 'POST'
}, {
  delay: 5000,
  attempts: 5,
  backoff: {
    type: 'exponential',
    delay: 2000,
    maxDelay: 60000
  }
});

Bulk Job Addition

// Add multiple jobs efficiently
const jobs = await queue.addBulk([
  { type: 'process-user', data: { userId: 1 }, options: { priority: JobPriority.HIGH } },
  { type: 'process-user', data: { userId: 2 } },
  { type: 'process-user', data: { userId: 3 } }
]);

console.log(`Added ${jobs.length} jobs`);

Event Handling

// Listen to queue events
queue.on('job:waiting', (job) => {
  console.log(`Job ${job.id} added to queue`);
});

queue.on('job:active', (job) => {
  console.log(`Processing job ${job.id}`);
});

queue.on('job:completed', (job) => {
  console.log(`Job ${job.id} completed`);
});

queue.on('job:failed', (job) => {
  console.error(`Job ${job.id} failed: ${job.error}`);
});

queue.on('job:progress', (job) => {
  console.log(`Job ${job.id} progress: ${job.progress}%`);
});

Queue Statistics

// Get queue statistics
const stats = await queue.getStats();
console.log('Queue Stats:', {
  waiting: stats.waiting,
  active: stats.active,
  completed: stats.completed,
  failed: stats.failed,
  delayed: stats.delayed,
  totalProcessed: stats.totalProcessed,
  throughput: stats.throughput
});

Job Management

// Get a specific job, with its current status
const job = await queue.getJob('job-id-123');

// Cancel a waiting or running job
await queue.cancel('job-id-123');

// Requeue a failed or cancelled job (reason is required)
await queue.retry('job-id-123', { reason: 'upstream fixed' });

// Counts by state and oldest waiting age, per job type
const metrics = await queue.getQueueMetrics();

// Clean up old completed jobs (older than 24 hours)
const removed = await queue.clean(86400000, JobStatus.COMPLETED);
console.log(`Removed ${removed} old jobs`);

Concurrency Control

// Process up to 10 jobs concurrently
const queue = new QueueManager('high-throughput', {
  backend: 'memory',
  concurrency: 10
});

queue.process('task', async (job) => {
  // Job processing logic
  await processTask(job.data);
});

Manual Queue Control

// Create queue with manual start
const queue = new QueueManager('manual-queue', {
  backend: 'memory',
  autoStart: false // Don't auto-start processing
});

// Add jobs
await queue.add('task', { data: 'test' });

// Start processing when ready
await queue.start();

// Pause processing
await queue.pause();

// Resume processing
await queue.resume();

// Stop processing and close connections
await queue.close();

Error Handling with Dead Letter Queue

const queue = new QueueManager('critical-tasks', {
  backend: 'memory',
  retryPolicy: {
    maxAttempts: 3,
    backoff: { type: 'exponential', delay: 1000, maxDelay: 30000 }
  }
});

// Jobs that fail after all retries stay in this queue as JobStatus.FAILED, keeping the last error
queue.process('task', async (job) => {
  if (job.data.shouldFail) {
    throw new Error('Task failed');
  }
  return { success: true };
});

queue.on('job:failed', async (job) => {
  const current = await queue.getJob(job.id);
  if (current?.status === JobStatus.FAILED) alert(`dead-lettered ${job.id}: ${current.error}`);
});

// After fixing the cause, requeue it
await queue.retry(jobId, { reason: 'fixed the template' });

Durable Queue with Postgres

PostgresBackend stores jobs in a Postgres table so they survive restarts and can be shared by many workers. It needs PostgreSQL 13+ and has no runtime dependency on pg: pass anything with query(sql, params) => Promise<{ rows, rowCount }>, such as a pg.Pool, a PoolClient, or PostgreSQLClient.getPool() from @bernierllc/postgres-client. The caller owns the pool; close() does not end it.

1. Apply the migration with your own migration tool. It is idempotent and ships in the package:

node_modules/@bernierllc/queue-manager/migrations/001_queue_jobs.sql

2. Create the queue:

import { Pool } from 'pg';
import { QueueManager, PostgresBackend, PermanentJobError } from '@bernierllc/queue-manager';

const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const queue = new QueueManager('email', {
  backend: new PostgresBackend({ db: pool, queue: 'email', leaseMs: 30_000 }),
  concurrency: 4,
  retryPolicy: { maxAttempts: 5, backoff: { type: 'exponential', delay: 1000, maxDelay: 60_000 } },
  logger // anything with error(message, error, metadata)
});

queue.process('send', async job => {
  if (!job.data.to) throw new PermanentJobError('no recipient'); // no retries
  await send(job.data, { idempotencyKey: job.id });                // handlers must be idempotent
});

3. Enqueue, optionally inside your own transaction so the job exists only if the transaction commits:

const client = await pool.connect();
try {
  await client.query('BEGIN');
  await client.query('INSERT INTO orders ...');
  await queue.add('send', { to }, { db: client, idempotencyKey: `order-${id}`, correlationId: requestId });
  await client.query('COMMIT');
} catch (error) {
  await client.query('ROLLBACK');
  throw error;
} finally {
  client.release();
}

Delivery semantics

  • At least once. A claim takes a lease of leaseMs (default 30s); the manager renews it every leaseMs / 3 while the handler runs. If a worker dies, the lease expires and another worker claims the job again. Handlers must be idempotent.
  • Claiming uses FOR UPDATE SKIP LOCKED, highest priority first, then earliest runAt. A worker only claims job types it has a processor for.
  • Fenced settles. Each claim gets a fresh leaseToken. complete, fail and lease renewal only apply while that token is still current, so a worker whose lease expired or whose job was cancelled gets LEASE_LOST instead of overwriting the new state. The token is a compare-and-swap guard on the queue row, not a monotonic fencing token: side effects a stale worker already made elsewhere are not prevented, which is why handlers must be idempotent.
  • Attempts count once per claim. Failures retry after the retryPolicy backoff (computed by @bernierllc/retry-policy) until maxAttempts, then the job moves to FAILED with its last error kept. A lease that expires on the final attempt also ends FAILED ('lease expired'). Jobs are never deleted except by clean(), which only removes finished jobs.
  • idempotencyKey dedupes enqueue only: a second add with the same key on the same queue returns the existing job. It is not a request-level idempotency store.
  • Times come from the database clock (now()), so worker clock skew does not matter.

Error codes

All errors are QueueManagerError with code and context (jobId, queue, ...), and database failures carry the driver error as cause.

| Code | Meaning | |------|---------| | LEASE_LOST | The job was reclaimed, cancelled or already settled; this worker no longer owns it | | INVALID_STATE | cancel/retry on a job in a state that does not allow it | | NOT_FOUND | No job with that id | | INVALID_INPUT | Bad argument, e.g. blank retry reason or mismatched queue name | | UNSUPPORTED | The backend does not implement the operation | | OPERATION_FAILED | The database call failed; see cause |

The manager never swallows a failure: handler errors, claim errors, renewal errors and refused settles all go to logger.error(message, error, { queue, jobId, type }) and are emitted as queue:error (or job:lease-lost).

Upgrading from 1.5

  • A custom retryPolicy.backoff now takes effect (before, delays were always exponential from 1s, capped at 30s, which is still the default).
  • JobStatus.CANCELLED is a new status; exhaustive switch statements over JobStatus need a case for it.
  • A worker only claims job types it has a processor for. Before, a job with no processor was failed; now it waits for a worker that can run it.
  • MemoryBackend.add rejects a db option, since it cannot join a database transaction.

API Reference

QueueManager

Constructor

constructor(name: string, options: QueueOptions)

Creates a new queue manager instance.

Parameters:

  • name - Unique queue name
  • options - Queue configuration options

Methods

add(type: string, data: T, options?: JobOptions): Promise<Job<T>>

Add a single job to the queue.

Parameters:

  • type - Job type identifier for processor routing
  • data - Job payload data
  • options - Optional job configuration (priority, delay, attempts, etc.)

Returns: Promise resolving to the created job

addBulk(jobs: Array<{type: string, data: T, options?: JobOptions}>): Promise<Job<T>[]>

Add multiple jobs to the queue efficiently.

Parameters:

  • jobs - Array of job specifications

Returns: Promise resolving to array of created jobs

process(type: string, processor: JobProcessor<T>): void

Register a processor for a specific job type.

Parameters:

  • type - Job type to process
  • processor - Async function that processes the job
start(): Promise<void>

Start processing jobs from the queue.

pause(): Promise<void>

Pause job processing (current jobs complete, new jobs wait).

resume(): Promise<void>

Resume job processing after pause.

close(): Promise<void>

Stop processing and close backend connections.

getJob(id: string): Promise<Job | null>

Retrieve a specific job by ID, with its current status.

Parameters:

  • id - Job ID

Returns: Promise resolving to job or null if not found

cancel(id: string): Promise<void>

Move a waiting, delayed or active job to CANCELLED. A handler still running on it is refused when it settles (LEASE_LOST, logged and emitted as job:lease-lost). Throws INVALID_STATE for a job already finished and NOT_FOUND for an unknown id.

retry(id: string, options: { reason: string }): Promise<void>

Re-queue a FAILED or CANCELLED job with attempts reset to 0. reason is required (INVALID_INPUT when blank) and stored as job.retryReason; the last error is kept.

getQueueMetrics(): Promise<QueueMetrics[]>

One row per job type: counts by state and the age of the oldest due waiting job.

interface QueueMetrics {
  queue: string;
  type: string;
  counts: { waiting: number; delayed: number; active: number; completed: number; failed: number; cancelled: number };
  oldestWaitingAgeMs: number | null;
}

getJob, cancel, retry and getQueueMetrics throw UNSUPPORTED when the backend does not implement them. Both built-in backends do.

getStats(): Promise<QueueStats>

Get queue statistics.

Returns: Promise resolving to statistics object

clean(maxAge: number, status: JobStatus): Promise<number>

Remove old jobs with a specific status.

Parameters:

  • maxAge - Maximum age in milliseconds
  • status - Job status to clean

Returns: Promise resolving to number of jobs removed

Types

QueueOptions

interface QueueOptions {
  backend: 'memory' | QueueBackendInterface; // e.g. new PostgresBackend({ db, queue })
  logger?: QueueLogger;           // Default: console.error. Receives every handler, claim, renew and settle failure.
  concurrency?: number;           // Default: 1
  defaultDelay?: number;          // Default: 0
  retryPolicy?: RetryPolicy;      // Default: 3 attempts, exponential backoff
  deadLetterQueue?: string;       // Deprecated, no effect: exhausted jobs stay here as FAILED
  jobTimeout?: number;            // Default: 30000ms
  cleanupInterval?: number;       // Deprecated, no effect: call clean() yourself
  autoStart?: boolean;            // Default: true
}

JobOptions

interface JobOptions {
  priority?: JobPriority;
  delay?: number;
  attempts?: number;
  timeout?: number;
  backoff?: BackoffStrategy;
  metadata?: Record<string, any>;
  runAt?: Date;                   // Run no earlier than this; takes precedence over delay
  correlationId?: string;         // Stored on the job and passed to the handler
  idempotencyKey?: string;        // Enqueue dedupe per queue (PostgresBackend)
  db?: QueueDb;                   // Enqueue on this connection/transaction (PostgresBackend)
}

JobPriority

enum JobPriority {
  LOW = 1,
  NORMAL = 5,
  HIGH = 10,
  CRITICAL = 20
}

JobStatus

enum JobStatus {
  WAITING = 'waiting',
  ACTIVE = 'active',
  COMPLETED = 'completed',
  FAILED = 'failed',
  DELAYED = 'delayed',
  CANCELLED = 'cancelled'
}

Job

interface Job<T = any> {
  id: string;
  type: string;
  data: T;
  priority: JobPriority;
  attempts: number;
  maxAttempts: number;
  delay?: number;
  createdAt: Date;
  processedAt?: Date;
  completedAt?: Date;
  failedAt?: Date;
  error?: string;
  progress?: number;
  metadata?: Record<string, any>;
  status?: JobStatus;             // Set by getJob
  runAt?: Date;
  correlationId?: string;
  idempotencyKey?: string;
  leaseToken?: string;            // PostgresBackend: the claim this worker holds
  leaseExpiresAt?: Date;
  cancelledAt?: Date;
  retryReason?: string;
}

QueueStats

interface QueueStats {
  waiting: number;
  active: number;
  completed: number;
  failed: number;
  delayed: number;
  totalProcessed: number;
  throughput: number;
}

Integration Status

Logger Integration

Status: Not applicable

This is a pure core utility package focused on queue management. Logger integration is not required as the package:

  • Uses standard EventEmitter for job lifecycle events
  • Provides comprehensive event system for external logging integration
  • Allows consumers to add logging via event handlers
  • Keeps the package lightweight and dependency-free

Applications using this package can integrate logging by listening to queue events:

import { createLogger } from '@bernierllc/logger';

const logger = createLogger({ service: 'queue' });

queue.on('job:completed', (job) => {
  logger.info('Job completed', { jobId: job.id, type: job.type });
});

queue.on('job:failed', (job) => {
  logger.error('Job failed', { jobId: job.id, error: job.error });
});

Docs-Suite Integration

Status: Ready

Documentation format: Markdown with TypeScript examples

  • Complete API reference with type definitions
  • Comprehensive usage examples
  • Integration patterns documented

NeverHub Integration

Status: Not applicable

This is a foundational core utility package that:

  • Provides queue management primitives
  • Has no runtime service dependencies
  • Operates independently without service discovery needs
  • Designed for embedding in higher-level service packages

NeverHub integration should be implemented in service-layer packages that orchestrate multiple core utilities, not in the atomic core packages themselves. This maintains clean separation of concerns per MECE architecture.

Configuration

This is a pure utility core package with no runtime environment configuration. All configuration is provided programmatically through the constructor options.

Programmatic Configuration

const queue = new QueueManager('my-queue', {
  backend: 'memory',              // or new PostgresBackend({ db, queue: 'my-queue' })
  concurrency: 5,                 // Process 5 jobs concurrently
  defaultDelay: 0,                // Default job delay in ms
  retryPolicy: {
    maxAttempts: 3,
    backoff: {
      type: 'exponential',
      delay: 1000,
      maxDelay: 30000
    }
  },
  jobTimeout: 30000,              // Job timeout in ms
  autoStart: true                 // Auto-start processing
});

Features

  • Multiple Backends: Memory (development) and Postgres (durable, multi-worker, PG13+)
  • Priority Queues: Process jobs based on priority (CRITICAL > HIGH > NORMAL > LOW)
  • Delayed Jobs: Schedule jobs to run after a specified delay
  • Automatic Retries: Configurable retry logic with exponential backoff using @bernierllc/retry-policy
  • Dead Letter: Jobs that exhaust their attempts stay as FAILED with the last error, and can be retried with a reason
  • Concurrency Control: Process multiple jobs in parallel with configurable limits
  • Job Lifecycle Events: Comprehensive event system for monitoring
  • Statistics & Monitoring: Real-time queue metrics and throughput tracking
  • Job Management: Get, cancel, retry, per-type metrics, and clean jobs by status
  • Leases & Fencing (Postgres): SKIP LOCKED claims, lease renewal, token-fenced settles
  • Type-Safe: Full TypeScript support with strict typing
  • Timeout Protection: Configurable job timeouts to prevent stuck jobs
  • Bulk Operations: Efficient bulk job addition

Dependencies

  • @bernierllc/retry-policy - Exponential backoff and retry logic

See Also

License

Copyright (c) 2025 Bernier LLC. All rights reserved.

This package is licensed under the MIT License.