Skip to main content

Creating Workers

Workers are background processes that handle asynchronous job processing. Open Mercato provides a worker discovery system that automatically registers workers defined in your modules.

Quick Start​

Create a worker by adding a .worker.ts file to your module's workers/ directory:

// src/modules/my-module/workers/my-queue.worker.ts
import type { QueuedJob, JobContext, WorkerMeta } from '@open-mercato/queue'

export const metadata: WorkerMeta = {
queue: 'my-queue',
concurrency: 2,
}

export default async function handle(
job: QueuedJob<{ message: string }>,
ctx: JobContext
): Promise<void> {
console.log(`Processing job ${ctx.jobId}:`, job.payload.message)
}

Run the worker:

# Run all workers (recommended)
yarn dev

# Or run specific queue
yarn mercato queue worker my-queue

File Structure​

Workers follow a strict naming convention for auto-discovery:

src/modules/<module>/workers/
└── <queue-name>.worker.ts

# or in packages
packages/<package>/src/modules/<module>/workers/
└── <queue-name>.worker.ts

The file name (minus .worker.ts) typically matches the queue name, though you can specify any queue name in the metadata.

Worker Anatomy​

Every worker file must export two things:

1. Metadata Export​

import type { WorkerMeta } from '@open-mercato/queue'

export const metadata: WorkerMeta = {
queue: 'my-queue', // Required: queue name to process
id: 'my-module:my-worker', // Optional: unique ID (auto-generated if omitted)
concurrency: 5, // Optional: parallel job processing (default: 1)
}

2. Default Handler Function​

import type { QueuedJob, JobContext } from '@open-mercato/queue'

export default async function handle(
job: QueuedJob<MyPayloadType>,
ctx: JobContext
): Promise<void> {
// Process the job
}

Job and Context Types​

QueuedJob​

type QueuedJob<T> = {
id: string // Unique job identifier
payload: T // Your job data
createdAt: string // ISO timestamp
metadata?: Record<string, unknown>
}

JobContext​

type JobContext = {
jobId: string // Same as job.id
attemptNumber: number // 1-based retry count
queueName: string // Queue being processed
resolve: <T>(name: string) => T // DI container access
}

Accessing Services via DI​

Use ctx.resolve() to access services from the dependency injection container:

export default async function handle(
job: QueuedJob<{ userId: string }>,
ctx: JobContext & { resolve: <T>(name: string) => T }
): Promise<void> {
// Resolve services from DI container
const emailService = ctx.resolve<EmailService>('emailService')
const userRepo = ctx.resolve<UserRepository>('userRepository')

const user = await userRepo.findById(job.payload.userId)
await emailService.sendWelcome(user.email)
}

Environment Variables​

Per-Queue Concurrency​

Override default concurrency via environment variables:

# Format: WORKERS_<QUEUE_NAME_UPPERCASE>_CONCURRENCY
WORKERS_EVENTS_CONCURRENCY=5
WORKERS_EMAIL_NOTIFICATIONS_CONCURRENCY=2
WORKERS_FULLTEXT_INDEXING_CONCURRENCY=10

Use dashes converted to underscores for queue names with hyphens.

Auto-Spawn Control​

# Enable/disable automatic worker spawning (default: true)
AUTO_SPAWN_WORKERS=true

# Set to false to run workers separately
AUTO_SPAWN_WORKERS=false

Running Workers​

Unified Entrypoint (Development Only)​

By default, yarn dev automatically spawns workers for all queues:

# Start app + all workers (development)
yarn dev

# Start app only (no workers)
AUTO_SPAWN_WORKERS=false yarn dev
Production Warning

Never use auto-spawned workers in production. The unified entrypoint is designed for development convenience only. In production:

  1. Set AUTO_SPAWN_WORKERS=false in your environment
  2. Run workers as separate processes using yarn start:workers

This allows proper scaling, monitoring, and independent restarts of worker processes.

CLI Commands​

# Run all discovered workers
yarn mercato queue worker --all
yarn start:workers

# Run specific queue
yarn mercato queue worker events
yarn mercato queue worker fulltext-indexing --concurrency=10

# Check queue status
yarn mercato queue status events

# Clear queue
yarn mercato queue clear events

Production Deployment​

For production, run workers separately for better scaling:

# Main app (disable auto-spawn)
AUTO_SPAWN_WORKERS=false yarn start

# Worker process (can run multiple)
yarn start:workers

# Or specific queues on different machines
yarn mercato queue worker events --concurrency=10
yarn mercato queue worker fulltext-indexing --concurrency=5

Complete Example​

Here's a full example of a notification worker:

// src/modules/notifications/workers/notifications.worker.ts
import type { QueuedJob, JobContext, WorkerMeta } from '@open-mercato/queue'

// Queue name constant for reuse
export const NOTIFICATIONS_QUEUE = 'notifications'

// Read concurrency from environment
const envConcurrency = process.env.WORKERS_NOTIFICATIONS_CONCURRENCY
const DEFAULT_CONCURRENCY = 3

// Metadata for auto-discovery
export const metadata: WorkerMeta = {
queue: NOTIFICATIONS_QUEUE,
concurrency: envConcurrency ? parseInt(envConcurrency, 10) : DEFAULT_CONCURRENCY,
}

// Job payload type
type NotificationPayload = {
type: 'email' | 'sms' | 'push'
userId: string
template: string
data: Record<string, unknown>
}

// Extended context with DI access
type HandlerContext = JobContext & {
resolve: <T>(name: string) => T
}

// Main handler function
export default async function handle(
job: QueuedJob<NotificationPayload>,
ctx: HandlerContext
): Promise<void> {
const { type, userId, template, data } = job.payload

console.log(`[notifications] Processing ${type} notification for user ${userId}`)

// Resolve services from DI
const notificationService = ctx.resolve<NotificationService>('notificationService')

try {
switch (type) {
case 'email':
await notificationService.sendEmail(userId, template, data)
break
case 'sms':
await notificationService.sendSms(userId, template, data)
break
case 'push':
await notificationService.sendPush(userId, template, data)
break
}

console.log(`[notifications] Successfully sent ${type} to user ${userId}`)
} catch (error) {
console.error(`[notifications] Failed to send ${type} to user ${userId}:`, error)
throw error // Re-throw to trigger retry
}
}

Enqueueing Jobs​

To add jobs to your queue, use the queue factory:

import { createQueue } from '@open-mercato/queue'
import { NOTIFICATIONS_QUEUE } from './workers/notifications.worker'

// Get queue strategy from environment
const strategy = process.env.QUEUE_STRATEGY === 'async' ? 'async' : 'local'

const queue = createQueue<NotificationPayload>(NOTIFICATIONS_QUEUE, strategy, {
connection: { url: process.env.REDIS_URL },
})

// Enqueue a job
await queue.enqueue({
type: 'email',
userId: '123',
template: 'welcome',
data: { name: 'John' },
})
Production Warning

Never use the local queue strategy in production. The local strategy is filesystem-based and:

  • Does not support distributed systems
  • Cannot handle concurrent access from multiple processes
  • Provides no high availability or persistence guarantees

Always use QUEUE_STRATEGY=async with Redis in production environments.

Jobs the Queue Abandons​

A handler can only report what it sees, and there is one failure mode it never sees: the queue giving up on a job before the handler is entered.

BullMQ counts how many times a job has stalled, and that counter is cumulative for the job's life — it does not reset when a redelivery succeeds. So for a long-lived job (one job that owns an entire import for hours or days), maxStalledCount is not a tolerance for flakiness; it is a budget for how many worker restarts the job may survive. Every deploy spends one. Past the budget BullMQ writes a deferred failure onto the job and moves it back to wait; the next worker reads that marker and fails the job before calling the processor.

The handler therefore never runs on that final delivery — it does not throw, and it never learns. (An earlier attempt of the same job usually did enter the handler, in a process that then died mid-flight; that attempt has no way to report anything either.) Any state created on enqueue — a run row, a progress record — is stranded in whatever "in progress" state it was left in, and nothing reconciles it: the queue says failed while the domain row still says running.

onJobAbandoned is the callback for exactly that case, and it is declared on the worker, beside the queue name it belongs to:

// workers/my-import.ts
import type { WorkerMeta } from '@open-mercato/queue'

export const metadata: WorkerMeta = {
queue: 'my-import',
concurrency: 5,
onJobAbandoned: async (payload, info) => {
const data = payload as { payload?: { runId?: string } } | undefined
if (typeof data?.payload?.runId !== 'string') return
await markRunFailed(data.payload.runId, `the queue abandoned this job: ${info.reason}`)
},
}

export default async function handle(job, ctx) { /* ... */ }

Declare it here and not on createModuleQueue. That is the single most important thing about this callback, and the mistake is silent: the queue you build to enqueue jobs is a different instance from the one the worker runs on. runWorker builds the worker's queue from the worker descriptors, so a callback attached to the enqueueing queue is never installed on the consumer — and the process that restarts, which is the event being reported, never constructs the enqueueing queue at all. The symptom is no error, no log, and a domain row nobody is told about.

Two consequences of travelling through worker metadata:

  • One queue gets one callback. When several workers share a queue and more than one declares it, the first wins and the CLI warns, naming the queue and the workers involved.

  • It is detected from the source at build time. The generator reads metadata to emit the registry, so the callback must be declared directly in that object literal — a spread, or a metadata object built by a helper function, will not be seen.

  • It fires only when the queue abandons a job it never handed to the handler. It is deliberately not a general "job failed" hook — a handler that ran and threw already owns its outcome, and firing for that case would double-report and erase the difference between the work failed and the work never started. The two are told apart by the reason BullMQ records (job stalled more than allowable limit, job started more than allowable limit), which is exact and identical in every worker process.

  • Keep it small and idempotent, and make it tolerate a payload it does not recognize. It runs on the worker's event emitter; the queue catches and logs anything it throws so a reporting failure cannot take the worker down. close() waits for a report already in flight, but only for ABANDONED_JOB_DRAIN_TIMEOUT_MS — a hook that hangs must not turn a graceful shutdown into a SIGKILL, and an undelivered report is picked up by the next worker's start-up sweep anyway.

  • Delivery is at-least-once. The worker reports as soon as it observes the abandonment, and also sweeps the queue's failed set — on worker start, then every five minutes (QUEUE_ABANDONED_SWEEP_INTERVAL_MS overrides the cadence) — for abandoned jobs whose report was never acknowledged. Acknowledgement is a marker written onto the stored job after the callback returns, so a callback that threw, or a process that died mid-report, leaves the job unmarked and a later sweep retries it. The failed job itself is kept for diagnosis; acknowledgement marks it, it does not delete it. Two consequences: the callback can be invoked more than once for the same job (hence the idempotency requirement above), and a report is delayed rather than lost. Residual loss remains possible where the failure record itself disappears — removeOnFail caps the failed set, and a Redis flush empties it — so state that absolutely must never be stranded should also have a staleness check of its own at the domain level.

  • It is an async-strategy concept. The local strategy runs handlers in-process, so no queue can outlive a handler and abandon its job, and the option is not forwarded.

  • It repairs reporting, not the job. A long-running job still dies when it exhausts its stall budget — it just dies visibly instead of silently.

Best Practices​

1. Make Handlers Idempotent​

Jobs may be retried on failure. Design handlers to be safely re-executed:

export default async function handle(job, ctx) {
const { paymentId } = job.payload

// Check if already processed
const payment = await paymentRepo.findById(paymentId)
if (payment.status === 'completed') {
return // Skip - already processed
}

await processPayment(paymentId)
}

2. Handle Errors Gracefully​

export default async function handle(job, ctx) {
try {
await processJob(job.payload)
} catch (error) {
if (error instanceof RetryableError) {
throw error // Will be retried
}

// Log and swallow non-retryable errors
console.error('Non-retryable error:', error)
}
}

3. Use Appropriate Concurrency​

// CPU-bound: match CPU cores
export const metadata: WorkerMeta = { queue: 'image-processing', concurrency: 4 }

// I/O-bound: higher concurrency
export const metadata: WorkerMeta = { queue: 'api-calls', concurrency: 20 }

// Rate-limited APIs: lower concurrency
export const metadata: WorkerMeta = { queue: 'email-sending', concurrency: 2 }

4. Log Progress​

export default async function handle(job, ctx) {
console.log(`[${ctx.queueName}] Starting job ${ctx.jobId} (attempt ${ctx.attemptNumber})`)

await processJob(job.payload)

console.log(`[${ctx.queueName}] Completed job ${ctx.jobId}`)
}

Built-in Workers​

Open Mercato includes these workers:

ModuleWorkerQueuePurpose
eventsevents.worker.tseventsDispatches persistent events to subscribers
searchfulltext-index.worker.tsfulltext-indexingIndexes documents for Meilisearch
searchvector-index.worker.tsvector-indexingGenerates embeddings for vector search