bullmq

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 17 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

BullMQ for Go

The official Go port of BullMQ, the job queue for Redis and PostgreSQL.

Go producers and workers share queues with the Node.js, Python, Elixir, PHP, Rust and .NET ports. On Redis every state transition runs the same Lua scripts (src/commands at the root of this repository), and on PostgreSQL the same SQL (src/postgres), so a job added from Node.js can be processed in Go and the other way round.

The module has three packages:

  • bullmq: Queue, Worker, Job, QueueEvents, FlowProducer and job schedulers. It only depends on the Backend interface and imports no datastore driver.
  • redisbackend: the Redis backend, built on go-redis v9.
  • postgresbackend: the PostgreSQL backend, built on pgx v5.

FEATURE_PARITY.md lists what is supported and what isn't yet. The BullMQ documentation explains the concepts (queues, workers, flows, job schedulers, ...) that this guide refers to.

Contents

Requirements

  • Go 1.26 or newer.
  • Redis 6.2 or newer, or PostgreSQL 13 or newer.

Installation

go get github.com/taskforcesh/bullmq-go

Both backends ship in this module, but a program only links the driver of the backend package it imports.

Quick start

Redis

This program adds a job and processes it. Producers and workers usually run in different processes; they only need to agree on the queue name and the backend settings.

package main

import (
	"context"
	"errors"
	"log"
	"os"
	"os/signal"
	"syscall"

	bullmq "github.com/taskforcesh/bullmq-go"
	"github.com/taskforcesh/bullmq-go/redisbackend"
)

type Email struct {
	To      string `json:"to"`
	Subject string `json:"subject"`
}

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	backend := redisbackend.New(redisbackend.Options{Addr: "127.0.0.1:6379"})

	queue, err := bullmq.NewQueue("emails", &bullmq.QueueOptions{Backend: backend})
	if err != nil {
		log.Fatal(err)
	}
	defer queue.Close()

	job, err := queue.Add(ctx, "welcome", Email{To: "ada@example.com", Subject: "Welcome!"}, nil)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("added job %s", job.ID)

	worker, err := bullmq.NewWorker("emails", func(ctx context.Context, job *bullmq.Job) (any, error) {
		var email Email
		if err := job.DecodeData(&email); err != nil {
			return nil, bullmq.NewUnrecoverableError("invalid payload: %v", err)
		}
		log.Printf("sending %q to %s", email.Subject, email.To)
		return map[string]bool{"sent": true}, nil
	}, &bullmq.WorkerOptions{Backend: backend, Concurrency: 10})
	if err != nil {
		log.Fatal(err)
	}
	defer worker.Close()

	// Run blocks until ctx is cancelled or Close is called.
	if err := worker.Run(ctx); err != nil && !errors.Is(err, context.Canceled) {
		log.Fatal(err)
	}
}

Backend is required in QueueOptions, WorkerOptions, QueueEventsOptions and FlowProducerOptions; without it the constructors return a *bullmq.ConfigError. Cancelling the context of Run, as Ctrl+C does here, is an immediate shutdown; see Shutting down for the graceful one.

PostgreSQL

Only the backend changes:

package main

import (
	"context"
	"log"
	"os"

	bullmq "github.com/taskforcesh/bullmq-go"
	"github.com/taskforcesh/bullmq-go/postgresbackend"
)

func main() {
	ctx := context.Background()

	backend := postgresbackend.New(postgresbackend.Options{
		ConnString: os.Getenv("DATABASE_URL"), // e.g. postgres://localhost:5432/app
	})

	queue, err := bullmq.NewQueue("emails", &bullmq.QueueOptions{Backend: backend})
	if err != nil {
		log.Fatal(err)
	}
	defer queue.Close()

	if _, err := queue.Add(ctx, "welcome", map[string]string{"to": "ada@example.com"}, nil); err != nil {
		log.Fatal(err)
	}
}

The bullmq schema is created and migrated by the first operation. See The PostgreSQL backend for the options.

Connecting to Redis

redisbackend.Options holds everything Redis-specific:

Field Default Meaning
Addr localhost:6379 Server address
Username, Password, DB, PoolSize Passed to go-redis
Prefix bull Prefix of every key, as in the other ports. Producers and workers of a queue must use the same one
Client An existing redis.UniversalClient to use instead of the fields above; BullMQ never closes it
AutoPipeline off go-redis automatic pipelining (experimental); see Auto-pipelining

Each queue, worker and QueueEvents built from redisbackend.New with an Addr opens its own client. Pass a Client to share one connection pool, or to configure what Options doesn't expose, such as TLS:

rdb := redis.NewClient(&redis.Options{
	Addr:      "redis.example.com:6380",
	Password:  os.Getenv("REDIS_PASSWORD"),
	TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12},
})
defer rdb.Close()

backend := redisbackend.New(redisbackend.Options{Client: rdb})
queue, err := bullmq.NewQueue("emails", &bullmq.QueueOptions{Backend: backend})
if err != nil {
	log.Fatal(err)
}
defer queue.Close()

Workers and QueueEvents run their blocking reads (BZPOPMIN, XREAD) on a dedicated client that they derive from the client's options (address, credentials, TLS, dialer...) and close on Close: a single connection for a *redis.Client, one per node for a *redis.ClusterClient, named after the worker so that Queue.Workers finds it. An idle worker blocks on it for the whole DrainDelay (5 s by default), and stopping the worker interrupts the read by closing that connection, as Node's disconnectBlocking does. A *redis.Ring can't be cloned: its blocking reads share its pool, in calls of at most a second, and Queue.Workers may not find its workers.

The backend of a queue built with redisbackend.New is a *redisbackend.Backend, which exposes the client and the key names:

rb := queue.Backend().(*redisbackend.Backend)
waiting, err := rb.Client().LLen(ctx, rb.Keys().Wait()).Result()
if err != nil {
	log.Fatal(err)
}
log.Printf("%d jobs in the wait list", waiting)

Worker, QueueEvents and FlowProducer have a Backend method too. The BlockingClient of a worker's or a listener's backend is its dedicated blocking client.

Auto-pipelining

AutoPipeline (experimental) sends the backend's non-blocking commands through go-redis's automatic pipeliner, which writes the commands that concurrent goroutines issue at the same time together, as ioredis does for Node.js, instead of each command waiting for its own round trip on a pooled connection. It helps workers with a Concurrency above 1 and producers that add jobs from many goroutines. Use its full-duplex mode:

backend := redisbackend.New(redisbackend.Options{
	Addr:         "127.0.0.1:6379",
	AutoPipeline: &redis.AutoPipelineOptions{FullDuplex: true},
})

In our benchmark the full-duplex mode processed 1.2× as many jobs per second at a concurrency of 10 and 1.3× at 50 on a local Redis, 1.6× at 50 through a link with a 1.15 ms round trip, and added jobs from 32 goroutines 1.5× as fast; a concurrency of 1 doesn't change. go-redis's default (half-duplex) mode needs fewer round trips but runs one batch at a time, and was up to 26% slower than no auto-pipelining, so we don't recommend it.

Before you turn it on:

  • go-redis marks auto-pipelining as experimental: AutoPipelineOptions can change in a minor release.
  • A queued command doesn't observe its context. The backend doesn't send a command whose context is already done, but once queued the command runs, bounded by the client's read and write timeouts, even if the context is cancelled or its deadline passes first.
  • After a connection error, go-redis sends again, up to MaxRetries times, the commands whose replies it didn't read; in half-duplex mode, the whole batch, including commands whose replies it had read. A BullMQ command that already ran then runs twice, as with a plain client that loses a reply: a job fetched twice stays active until the stalled check recovers it, and an Add without a JobID adds a second job. Pass a Client with MaxRetries: -1 to turn these retries off.
  • With a Client, every backend built on it shares the client's single auto-pipeliner (the options of the first one win), and closing a backend leaves it open; closing the client stops it. A *redis.Ring runs without auto-pipelining.
  • Blocking reads, the transactions of AddBulk and flows, and commands sent through Backend.Client() are never auto-pipelined.

Adding jobs

job, err := queue.Add(ctx, "welcome", Email{To: "ada@example.com"}, &bullmq.JobOptions{
	Attempts:         bullmq.Int64(3),
	Backoff:          &bullmq.Backoff{Type: bullmq.BackoffExponential, Delay: 1000},
	RemoveOnComplete: bullmq.KeepCount(1000),
	RemoveOnFail:     bullmq.KeepAge(7 * 24 * 60 * 60),
})
if err != nil {
	log.Fatal(err)
}
log.Printf("added job %s", job.ID)

The data is encoded with encoding/json (nil is stored as {}, as Node.js stores a job without data); a processor decodes it with job.DecodeData(&v). Several options are pointers so that an explicit zero can override a queue default; bullmq.Int64 and bullmq.Bool build them.

Option Meaning
JobID Custom id. Adding a job whose id already exists does nothing and returns that id. Custom ids can't be integers nor contain :
Delay Milliseconds before the job can be processed
Priority 1 (highest) to 2,097,151; 0 means no priority
LIFO Add the job to the front of the wait list
Attempts, Backoff See Retries and backoff
RemoveOnComplete, RemoveOnFail bullmq.RemoveAll(), bullmq.KeepCount(n), bullmq.KeepAge(seconds), or a RemoveOnFinish with Count, Age and Limit. By default every finished job is kept
KeepLogs How many log rows to keep
SizeLimit Reject jobs whose encoded data is larger than this many bytes
StackTraceLimit How many failure traces to keep; every one by default
Deduplication See Deduplication
Parent and the failure options See Flows

Times and delays stored with a job keep the units every port stores: JobOptions.Delay, Backoff.Delay, DeduplicationOptions.TTL and the RepeatOptions fields are int64 milliseconds (time.Minute.Milliseconds(); dates with UnixMilli()), and RemoveOnFinish.Age is in seconds. Method parameters and worker settings are time.Durations: job.ChangeDelay, job.MoveToDelayed, job.ExtendLock, Worker.RateLimit, the grace period of Clean and the durations of WorkerOptions. So ChangeDelay(ctx, 4000) is 4 µs; write 4*time.Second.

QueueOptions.DefaultJobOptions applies to every job of a Queue, and WorkerOptions.RemoveOnComplete / RemoveOnFail are the defaults of the jobs a worker finishes. AddBulk adds several jobs in one round trip (a single MULTI/EXEC on Redis, a single transaction on PostgreSQL). On PostgreSQL a failed batch adds no job. Redis doesn't roll back the jobs already added when another one is rejected (for example because its parent doesn't exist), so check the queue before retrying a failed batch there:

jobs, err := queue.AddBulk(ctx, []bullmq.JobSpec{
	{Name: "welcome", Data: Email{To: "ada@example.com"}},
	{Name: "welcome", Data: Email{To: "grace@example.com"}, Opts: &bullmq.JobOptions{Priority: bullmq.Int64(1)}},
})
if err != nil {
	log.Fatal(err)
}
log.Printf("added %d jobs", len(jobs))
Delayed and prioritized jobs

A delayed job waits in the delayed state until it is due. Prioritized jobs are fetched by increasing Priority value, after the jobs without a priority, as in the prioritized jobs guide.

// Processed in about an hour.
_, err := queue.Add(ctx, "reminder", data, &bullmq.JobOptions{Delay: bullmq.Int64(time.Hour.Milliseconds())})
if err != nil {
	log.Fatal(err)
}

// Processed before the jobs with a larger priority value.
urgent, err := queue.Add(ctx, "report", data, &bullmq.JobOptions{Priority: bullmq.Int64(1)})
if err != nil {
	log.Fatal(err)
}

// Change your mind later.
if err := urgent.ChangePriority(ctx, 10, false); err != nil {
	log.Fatal(err)
}

Job.ChangeDelay reschedules a delayed job, Job.Promote and Queue.PromoteJobs make delayed jobs ready right away. A processor can move its own job back to the delayed set and return bullmq.ErrDelayed, which doesn't use up an attempt:

func poll(ctx context.Context, job *bullmq.Job) (any, error) {
	ready, err := checkStatus(ctx, job)
	if err != nil {
		return nil, err
	}
	if !ready {
		if err := job.MoveToDelayed(ctx, 30*time.Second); err != nil {
			return nil, err
		}
		return nil, bullmq.ErrDelayed
	}
	return "ready", nil
}
Deduplication

While a deduplication id is alive, adding another job with the same id returns the existing job's id instead of adding a job, and QueueEvents reports a deduplicated event. The modes of the deduplication guide map to DeduplicationOptions like this:

// Simple: until the first job finishes (completes, or fails for good).
_, err := queue.Add(ctx, "sync", data, &bullmq.JobOptions{
	Deduplication: &bullmq.DeduplicationOptions{ID: "sync-account-42"},
})
if err != nil {
	log.Fatal(err)
}

// Throttle: for 10 seconds after the first job was added.
_, err = queue.Add(ctx, "sync", data, &bullmq.JobOptions{
	Deduplication: &bullmq.DeduplicationOptions{ID: "sync-account-42", TTL: 10_000},
})
if err != nil {
	log.Fatal(err)
}

// Debounce: keep only the last job added within 5 seconds of the previous
// one. Replace only swaps a job that is still delayed.
_, err = queue.Add(ctx, "sync", data, &bullmq.JobOptions{
	Delay:         bullmq.Int64(5_000),
	Deduplication: &bullmq.DeduplicationOptions{ID: "sync-account-42", TTL: 5_000, Extend: true, Replace: true},
})
if err != nil {
	log.Fatal(err)
}

// Reschedule: push the delayed job back to 5 seconds from now, keeping its
// id and data. A job that is no longer delayed is left alone.
_, err = queue.Add(ctx, "sync", data, &bullmq.JobOptions{
	Delay:         bullmq.Int64(5_000),
	Deduplication: &bullmq.DeduplicationOptions{ID: "sync-account-42", Reschedule: true},
})
if err != nil {
	log.Fatal(err)
}

// Keep last if active: while the job runs, remember the last job added and
// add it once the running one finishes. At most one job runs and one waits.
_, err = queue.Add(ctx, "deploy", data, &bullmq.JobOptions{
	Deduplication: &bullmq.DeduplicationOptions{ID: "deploy-repo-7", KeepLastIfActive: true},
})
if err != nil {
	log.Fatal(err)
}

KeepLastIfActive ignores TTL: the id is held until the jobs finish. It can't be used on a flow node with a parent.

The Job returned for a duplicate carries the existing job's ID, but the data and options of the call; read it back with Queue.Job to see what is stored. Deduplication can't be combined with Parent.

Add doesn't say whether it deduplicated the job, as in Node.js: listen to the deduplicated event, or compare the returned ID with JobID when you set one. DeduplicationJobID tells which job holds a deduplication id, and the id can be released before the job finishes, so the next job with it is added:

holder, err := queue.DeduplicationJobID(ctx, "sync-account-42") // "" when none
if err != nil {
	log.Fatal(err)
}
log.Printf("job %q holds sync-account-42", holder)

// Release it, whichever job holds it.
if _, err := queue.RemoveDeduplicationKey(ctx, "sync-account-42"); err != nil {
	log.Fatal(err)
}

Job.RemoveDeduplicationKey releases the job's id only while the job holds it, for example to accept the next sync as soon as this one starts:

func syncAccount(ctx context.Context, job *bullmq.Job) (any, error) {
	if _, err := job.RemoveDeduplicationKey(ctx); err != nil {
		return nil, err
	}
	return nil, syncWithCRM(ctx, job)
}

Workers

Processors

A worker hands every job to a bullmq.Processor, a func(ctx context.Context, job *bullmq.Job) (any, error):

func sendWelcome(ctx context.Context, job *bullmq.Job) (any, error) {
	var email Email
	if err := job.DecodeData(&email); err != nil {
		// A malformed payload never succeeds: don't retry it.
		return nil, bullmq.NewUnrecoverableError("invalid payload: %v", err)
	}
	if err := mailer.Send(ctx, email); err != nil {
		return nil, err // retried while attempts remain
	}
	return map[string]string{"status": "sent"}, nil
}
  • The returned value is encoded with encoding/json and stored as the job's return value (job.ReturnValue, job.DecodeReturnValue). A value that can't be encoded fails the job.
  • A returned error fails the attempt; the job is retried while attempts remain. bullmq.NewUnrecoverableError, or calling job.Discard() before returning, fails it for good.
  • A panic is recovered and fails the attempt, with the stack as its trace.
  • bullmq.ErrDelayed, bullmq.ErrWaitingChildren, bullmq.ErrWaiting and bullmq.ErrRateLimited tell the worker that the processor moved the job itself; see delayed jobs, flows and rate limiting. job.MoveToWait puts the job back in the wait list without counting the attempt, as Node's moveToWait; return bullmq.ErrWaiting after it.
  • ctx is cancelled when the worker stops immediately, loses the job's lock or cancels the job; see Shutting down and Cancelling jobs.

A processor reports progress and writes job logs, which every port and dashboard can read:

if err := job.UpdateProgress(ctx, 50); err != nil {
	return err
}
if _, err := job.Log(ctx, "half way there"); err != nil {
	return err
}

UpdateProgress also takes any value encoded as JSON, such as a struct or a map, instead of a number; NaN and infinite numbers are rejected.

Concurrency
worker, err := bullmq.NewWorker("emails", sendWelcome, &bullmq.WorkerOptions{
	Backend:     backend,
	Name:        "mailer-1",
	Concurrency: 50,
})
if err != nil {
	log.Fatal(err)
}
defer worker.Close()

Concurrency (1 by default) is the number of jobs a worker processes at the same time, each on its own goroutine. Every processing slot finishes its job and fetches the next one in the same backend call, as the Node.js worker does, so a busy worker needs about one round trip per job whatever its concurrency. The worker only blocks on the datastore once the queue looks drained. worker.SetConcurrency(n) changes the concurrency of a running worker, as setting Node's worker.concurrency does: raising it fetches jobs for the new slots right away, and lowering it lets the jobs in flight finish, fetching no next job while more than n are in flight. Run as many workers as you like, in one process or many; to cap the number of jobs processed at once across all of them, use Queue.SetGlobalConcurrency. Queue.GlobalConcurrency returns that limit, or nil when there is none. Unlike Node.js, where setGlobalConcurrency(0) stores 0 and stops every worker, SetGlobalConcurrency(ctx, 0) removes the limit.

Name is stored on every job the worker processes and is part of the name of the worker's connection, which is how Queue.Workers finds it:

workers, err := queue.Workers(ctx)
if err != nil {
	log.Fatal(err)
}
for _, w := range workers {
	// Name is "" for a worker without one. Fields holds what the datastore
	// reports about the connection: addr, age, idle... on Redis.
	log.Printf("worker %q connected from %s", w.Name, w.Fields["addr"])
}
Worker events

Worker.Events delivers lifecycle events on a buffered channel, which is closed by Close:

go func() {
	for ev := range worker.Events() {
		switch ev.Type {
		case bullmq.EventCompleted:
			log.Printf("job %s completed with %v", ev.Job.ID, ev.Result)
		case bullmq.EventFailed:
			log.Printf("job %s failed: %v", ev.Job.ID, ev.Err)
		case bullmq.EventLockRenewalFailed:
			log.Printf("lost the locks of jobs %v", ev.JobIDs)
		case bullmq.EventError:
			log.Printf("worker error: %v", ev.Err)
		}
	}
}()
Event When Fields
EventActive A job starts Job
EventProgress Job.UpdateProgress succeeded Job, Result (a Progress)
EventCompleted A job completed Job, Result
EventFailed An attempt failed, whether the job is retried or not Job, Err
EventStalled This worker's stalled check moved a job back to wait (or failed it) Job (only its ID is set)
EventLocksRenewed Job locks were renewed JobIDs
EventLockRenewalFailed Job locks could not be renewed; those jobs' contexts are cancelled JobIDs
EventDrained A fetch found no job to process, once until a job is fetched again none
EventError A background error, such as a lost connection Err
EventClosed Run is returning none
EventPaused The Pause that paused the worker returned none
EventResumed Resume resumed a paused worker none

The channel never blocks the worker: when its buffer (256 events) is full, events are dropped and Worker.DroppedEvents counts them. To see every event, for example to keep metrics, set WorkerOptions.OnEvent. It is called synchronously on the worker's goroutines, so it must be quick and safe for concurrent use, and it must not call Close (start a goroutine for that). WorkerOptions.OnError receives the same errors as EventError, each on its own goroutine.

Pausing a worker
// Stop fetching and wait for the jobs in flight, like Node's pause().
if err := worker.Pause(ctx, false); err != nil {
	log.Fatal(err)
}
// ...
worker.Resume()

With doNotWaitActive set to true, Pause returns at once; a processor pausing its own worker must do so. Pause may also be called from OnEvent, for example to pause once the queue is drained: from EventDrained, EventCompleted or EventFailed it waits for the other jobs only, and a job fetched in the meantime is put back in the wait list rather than started. Close releases a pending Pause with bullmq.ErrWorkerClosed. As Node's paused and resumed, EventPaused is emitted once the Pause that paused the worker returns, and EventResumed by Resume. Unlike Node, a paused worker keeps checking for stalled jobs, so a paused worker still recovers the jobs of workers that died.

var worker *bullmq.Worker
worker, err := bullmq.NewWorker("emails", sendWelcome, &bullmq.WorkerOptions{
	Backend: backend,
	OnEvent: func(ev bullmq.Event) {
		if ev.Type == bullmq.EventDrained {
			_ = worker.Pause(context.Background(), false)
		}
	},
})
if err != nil {
	log.Fatal(err)
}

Worker.Pause only affects one worker. Queue.Pause pauses the queue for every worker, in any language.

Shutting down

Worker.Run blocks until the worker is stopped, and the two ways of stopping it treat in-flight jobs differently:

  • Worker.Close is graceful. The worker stops fetching, waits for the jobs in flight to finish (their contexts aren't cancelled), and releases its connections.
  • Cancelling the context of Run is immediate. That context is the parent of every job's context, so processors see the cancellation and should return. Whatever they return then isn't recorded: the jobs stay active, without using up an attempt, until their lock expires (LockDuration, 30 s by default) and the stalled check of a running worker, which runs every StalledInterval (30 s by default), moves them back to wait, as in Node.js. A job recovered this way counts as stalled, and a job that stalls more than MaxStalledCount times (1 by default) fails. Run returns once the processors have returned; Close must still be called to release the connections.

Run returns nil after Close, and the context's error when its context is done, even during a Close. Combining both gives in-flight jobs a grace period on SIGTERM:

func runUntilSignal(worker *bullmq.Worker) error {
	sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	// Processors run under runCtx, which is only cancelled if they
	// overrun the grace period.
	runCtx, cancelRun := context.WithCancel(context.Background())
	defer cancelRun()

	go func() {
		<-sigCtx.Done()
		timer := time.AfterFunc(30*time.Second, cancelRun)
		defer timer.Stop()
		_ = worker.Close()
	}()

	err := worker.Run(runCtx)
	// Close may be called again: it waits for the call above to finish.
	if cerr := worker.Close(); cerr != nil {
		return cerr
	}
	if errors.Is(err, context.Canceled) {
		// The grace period ran out: the jobs still running were left
		// active for the stalled check.
		return nil
	}
	return err
}

A worker runs once: calling Run again, or after Close, returns bullmq.ErrWorkerClosed.

Cancelling jobs

Worker.CancelJob cancels the context of a job the worker is processing, and Worker.CancelAllJobs the context of all of them. As with Node's cancelJob, the job then fails with the error its processor returns (and is retried if attempts remain). When that error is ctx.Err() itself, which says nothing more than "context canceled", the job fails with the reason instead; to keep the reason in an error of your own, wrap context.Cause(ctx). A processor that ignores the cancellation and succeeds completes the job.

if !worker.CancelJob(jobID, "superseded by a newer upload") {
	log.Printf("job %s is not being processed by this worker", jobID)
}

context.Cause tells a processor why its context was cancelled:

func upload(ctx context.Context, job *bullmq.Job) (any, error) {
	if err := transfer(ctx, job); err != nil {
		switch cause := context.Cause(ctx); {
		case errors.Is(cause, bullmq.ErrJobCancelled):
			// CancelJob: ctx is cancelled, so clean up with a context that
			// isn't, and fail the job with the reason (cause.Error()).
			cleanUp(context.WithoutCancel(ctx), job)
			return nil, cause
		case errors.Is(cause, bullmq.ErrLockLost):
			// Another worker may own the job now: stop touching it.
		}
		return nil, err
	}
	return nil, nil
}

Besides ErrJobCancelled, the cause is bullmq.ErrLockLost when the worker couldn't renew the job's lock, or the cause of the Run context. In the last two cases the job isn't failed.

Once a job's context is cancelled, the job's methods called with it (UpdateProgress, Log, UpdateData, ...) fail with the context's error, whereas Node's job methods ignore the abort signal. Make the calls of cleanup code with context.WithoutCancel(ctx):

_ = job.Log(context.WithoutCancel(ctx), fmt.Sprintf("cancelled after %d items", done))
return nil, fmt.Errorf("cancelled after %d items: %w", done, context.Cause(ctx))
Retries and backoff
_, err := queue.Add(ctx, "charge", data, &bullmq.JobOptions{
	Attempts: bullmq.Int64(5),
	// 1 s, 2 s, 4 s, 8 s between the attempts, each up to 20% shorter.
	Backoff: &bullmq.Backoff{Type: bullmq.BackoffExponential, Delay: 1000, Jitter: 0.2},
})
if err != nil {
	log.Fatal(err)
}

Attempts is the total number of tries (1 by default). BackoffFixed waits Delay milliseconds before every retry, BackoffExponential doubles it each time, and without a Backoff a failed job is retried right away. A custom backoff type is computed by WorkerOptions.BackoffStrategy, which returns the delay in milliseconds, or a negative value to fail the job for good:

worker, err := bullmq.NewWorker("emails", sendWelcome, &bullmq.WorkerOptions{
	Backend: backend,
	BackoffStrategy: func(attemptsMade int64, backoffType bullmq.BackoffType, err error, job *bullmq.Job) int64 {
		if backoffType == "linear" {
			return attemptsMade * 5_000
		}
		return -1
	},
})
if err != nil {
	log.Fatal(err)
}

A job with a custom backoff type fails instead of being retried on a worker without a BackoffStrategy, and an EventError says why. WorkerOptions.MaxStartedAttempts fails a job that was started more than that many times, for example because it keeps stalling. JobOptions.StackTraceLimit bounds the failure traces kept on the job. Job.Retry and Queue.RetryJobs move failed (or completed) jobs back to wait. Job.Retry keeps the attempt counters, so a job that used up its attempts fails for good after one more failure, unless you reset them:

err := job.Retry(ctx, bullmq.StateFailed, &bullmq.RetryOptions{ResetAttemptsMade: true})
if err != nil {
	log.Fatal(err)
}
Stalled jobs and locks

A worker holds a lock on every job it processes and renews it every LockRenewTime (half of LockDuration, which is 30 s by default). Every StalledInterval (30 s), the stalled check looks for active jobs whose lock expired, because their worker crashed or was stopped immediately, and moves them back to wait, or fails them once they stalled more than MaxStalledCount times. See the stalled jobs guide.

When renewing a lock fails, the worker emits EventLockRenewalFailed and, as a Go addition, cancels the job's context with bullmq.ErrLockLost: another worker may already own the job, so the processor should stop. Node.js keeps running the processor. The job isn't failed either way. SkipLockRenewal and SkipStalledCheck turn both mechanisms off, for workers that manage locks themselves.

Rate limiting
worker, err := bullmq.NewWorker("emails", sendWelcome, &bullmq.WorkerOptions{
	Backend: backend,
	// At most 100 jobs per minute, across every worker that sets this limiter.
	Limiter: &bullmq.RateLimiter{Max: 100, Duration: time.Minute},
})
if err != nil {
	log.Fatal(err)
}

The limit is shared by the queue, like in the other ports. Queue.SetGlobalRateLimit sets one for every worker of the queue, without configuring each of them; GlobalRateLimit reads it and RemoveGlobalRateLimit (or a max of 0) removes it. A rate-limited worker sleeps until the limit lifts, at most MaximumRateLimitDelay (30 s by default) at a time. Queue.RateLimitTTL(ctx, maxJobs) tells how long the queue stays limited, in milliseconds: the time left in the current window once maxJobs jobs were counted in it, else 0. With maxJobs 0 it uses the global rate limit's max and, without one, returns the time left whatever the count, or -2 when no window is open, as Node's getRateLimitTtl() does.

A processor can also rate limit the queue itself, for example when an external API asks it to slow down. Worker.RateLimit limits the queue for a while, and returning bullmq.ErrRateLimited puts the job back in the wait list without using up an attempt:

var worker *bullmq.Worker
worker, err := bullmq.NewWorker("emails", func(ctx context.Context, job *bullmq.Job) (any, error) {
	retryAfter, err := callAPI(ctx, job)
	if errors.Is(err, errTooManyRequests) {
		if err := worker.RateLimit(ctx, retryAfter); err != nil {
			return nil, err
		}
		return nil, bullmq.ErrRateLimited
	}
	return nil, err
}, &bullmq.WorkerOptions{
	Backend: backend,
	Limiter: &bullmq.RateLimiter{Max: 100, Duration: time.Minute},
})
if err != nil {
	log.Fatal(err)
}

As in Node.js, RateLimit only holds back workers that fetch with a limiter (Limiter, or a global rate limit).

Fetching jobs by hand

A worker created without a processor fetches nothing by itself: you fetch its jobs with GetNextJob and finish them with MoveToCompleted or MoveToFailed, as in Node's manual mode. The token you choose locks the job; pass it again to finish it. With fetchNext, finishing a job fetches the next one in the same call:

worker, err := bullmq.NewWorker("emails", nil, &bullmq.WorkerOptions{Backend: backend})
if err != nil {
	log.Fatal(err)
}
defer worker.Close()

// Moves the jobs whose lock expired back to wait, until Close.
if err := worker.StartStalledCheck(); err != nil {
	log.Fatal(err)
}

const token = "my-token"
for {
	// Waits up to DrainDelay for a job; nil when there is none.
	job, err := worker.GetNextJob(ctx, token, true)
	if err != nil {
		log.Fatal(err)
	}
	for job != nil {
		result, procErr := handle(ctx, job)
		if procErr != nil {
			job, err = job.MoveToFailed(ctx, procErr, token, true)
		} else {
			job, err = job.MoveToCompleted(ctx, result, token, true)
		}
		if err != nil {
			log.Fatal(err)
		}
	}
}
  • The worker's settings apply: LockDuration, Limiter, the removal policies, Metrics and BackoffStrategy. A failed job is retried while attempts remain, as with a processor.
  • Locks aren't renewed: finish a job within LockDuration, or call job.ExtendLock(ctx, d). A job whose lock expires is moved back to wait by the stalled check, and its token no longer finishes it.
  • GetNextJob returns nil, without waiting, while the worker or the queue is paused or the queue is rate limited. Run returns an error on a worker without a processor.
Metrics
worker, err := bullmq.NewWorker("emails", sendWelcome, &bullmq.WorkerOptions{
	Backend: backend,
	Metrics: &bullmq.MetricsOptions{MaxDataPoints: 7 * 24 * 60}, // one week of minutes
})
if err != nil {
	log.Fatal(err)
}

// One count per minute, the most recent first. As in Node.js, a minute's
// count is recorded once a job finishes in a later minute, so Data is empty
// during the first minute.
metrics, err := queue.Metrics(ctx, bullmq.StateCompleted, 0, 59)
if err != nil {
	log.Fatal(err)
}
log.Printf("%d jobs completed in total; last hour: %v", metrics.Count, metrics.Data)

Queue operations

A Queue is safe for concurrent use. Its methods mirror Node's Queue:

Methods What they do
Add, AddBulk Add jobs
Job, JobState, Jobs, JobIDs Read jobs, by id or by states
Count, JobCounts, CountsPerPriority, DelayedCount Count the waiting, delayed, prioritized and waiting-children jobs, the jobs in each state, the waiting jobs per priority, or the delayed jobs due before a time
Pause, Resume, IsPaused Pause the queue for every worker
Drain Remove the waiting and prioritized jobs, and optionally the delayed ones
Remove Remove a job by id, and optionally its children; false when a worker holds it
Clean Remove the jobs of a state older than a grace period
Obliterate Remove the queue and all of its jobs
RetryJobs, PromoteJobs Move failed or completed jobs back to wait; make delayed jobs ready
SetGlobalConcurrency, GlobalConcurrency, RemoveGlobalConcurrency, IsMaxed Cap how many jobs are active across all workers
SetGlobalRateLimit, GlobalRateLimit, RemoveGlobalRateLimit, RateLimitTTL Rate limit every worker of the queue
DeduplicationJobID, RemoveDeduplicationKey Read or release a deduplication id
Metrics, Workers Completed and failed metrics; the connected workers ([]WorkerInfo)
Meta, Version The queue metadata (limits, paused, events length) and the library that wrote it
TrimEvents Trim the event stream to about a length (QueueEvents)
UpsertJobScheduler, JobScheduler, JobSchedulers, ... Job schedulers
counts, err := queue.JobCounts(ctx, bullmq.StateWaiting, bullmq.StateActive, bullmq.StateFailed)
if err != nil {
	log.Fatal(err)
}
log.Printf("%d waiting, %d active, %d failed",
	counts[bullmq.StateWaiting], counts[bullmq.StateActive], counts[bullmq.StateFailed])

// The 10 most recent failures.
failed, err := queue.Jobs(ctx, 0, 9, false, bullmq.StateFailed)
if err != nil {
	log.Fatal(err)
}
for _, job := range failed {
	log.Printf("%s failed: %s", job.ID, job.FailedReason)
}

// The next 10 jobs to run of each pending state, as Node's getWaiting,
// getPrioritized and getDelayed list them.
next, err := queue.Jobs(ctx, 0, 9, true, bullmq.StateWaiting, bullmq.StatePrioritized, bullmq.StateDelayed)
if err != nil {
	log.Fatal(err)
}
log.Printf("%d jobs to run", len(next))

// Remove the completed jobs older than a day, at most 1000 of them.
removed, err := queue.Clean(ctx, 24*time.Hour, 1000, bullmq.StateCompleted)
if err != nil {
	log.Fatal(err)
}
log.Printf("removed %d jobs", len(removed))

// Retry the jobs that failed more than an hour ago, 1000 per round trip.
if err := queue.RetryJobs(ctx, &bullmq.RetryJobsOptions{Before: time.Now().Add(-time.Hour)}); err != nil {
	log.Fatal(err)
}

Queue.Job returns nil for a job that doesn't exist. The returned *Job can be changed and inspected: UpdateData, UpdateProgress, Log and Logs, State, IsCompleted, IsFailed, Promote, ChangeDelay, ChangePriority, Retry, and Remove (which returns bullmq.ErrJobLocked while a worker holds the job). queue.Remove(ctx, id, removeChildren) removes a job by id without reading it first, and returns false while a worker holds it.

NewQueue doesn't reach the datastore. Before its first command, a queue writes its metadata, as Node's Queue does: version and opts.maxLenEvents. The version is bullmq:<bullmq.ScriptsVersion>, the version of the Node.js package whose Lua and SQL scripts the module embeds, so dashboards enable the features of those scripts; bullmq.Version is the version of the Go module. opts.maxLenEvents is the approximate maximum length of the events stream, QueueOptions.EventsMaxLen (10,000 by default, Node's streams.events.maxLen). Set QueueOptions.SkipMetasUpdate for a role that may only read. After Obliterate or Close, the queue never writes it again, so an obliterated queue keeps no metadata.

QueueEvents

A QueueEvents reads the queue's shared event stream, so it sees what every worker and producer does, in any language:

events, err := bullmq.NewQueueEvents("emails", &bullmq.QueueEventsOptions{Backend: backend})
if err != nil {
	log.Fatal(err)
}
defer events.Close()

go func() {
	if err := events.Run(ctx); err != nil && !errors.Is(err, context.Canceled) {
		log.Printf("queue events: %v", err)
	}
}()

for ev := range events.Events() {
	switch ev.Event {
	case "completed":
		log.Printf("job %s returned %s", ev.JobID, ev.ReturnValue())
	case "failed":
		log.Printf("job %s failed: %s", ev.JobID, ev.FailedReason())
	}
}

Each QueueEvent has the event name (added, waiting, active, progress, completed, failed, delayed, stalled, removed, deduplicated, drained...), the job id and every field of the event in Data, as strings. The helpers parse the fields Node's QueueEvents parses: DecodeReturnValue(&v) the JSON return value of completed, Progress() and DecodeProgress(&v) the progress of progress, and DelayedUntil() the delay of delayed, which is when the job is due (Unix milliseconds), not a duration. The listener starts with the events published after Run starts; set LastEventID to read from another point ("0" for the oldest event kept). Events() is closed when the listener stops, by Close or by cancelling Run's context; Run then returns nil or the context's error, as Worker.Run does. Unlike a worker's events, the channel isn't lossy: the listener waits for the reader, so keep reading it. Read errors are retried and reported on Errors().

On PostgreSQL, a listener can miss events when several workers finish jobs at the same time; see Known limitations.

A QueueEventsProducer publishes custom events, as Node's does with publishEvent; listeners in every runtime receive them with the event name in Event and the fields in Data. String values are stored as they are and other values as JSON. On Redis the stream is then trimmed to about maxEvents events (1,000 when it is 0); PostgreSQL trims it to EventsMaxLen. Don't use the names of job events (completed, failed, ...) for your own.

producer, err := bullmq.NewQueueEventsProducer("emails", &bullmq.QueueEventsProducerOptions{Backend: backend})
if err != nil {
	log.Fatal(err)
}
defer producer.Close()

// Listeners see ev.Event == "example" and ev.Data["custom"] == "value".
if _, err := producer.PublishEvent(ctx, "example", map[string]any{"custom": "value"}, 0); err != nil {
	log.Fatal(err)
}

The stream keeps about QueueOptions.EventsMaxLen events (10,000 by default). Queue.TrimEvents(ctx, n) trims it to about n events, as Node's trimEvents does, and returns how many it removed. On Redis the trim is approximate (XTRIM MAXLEN ~): whole stream nodes go, so a few more than n events may be left. The PostgreSQL backend returns an error matching bullmq.ErrNotSupported, as Node's does; it trims the stream to EventsMaxLen as it adds events.

Flows

A FlowProducer adds a tree of jobs, possibly spanning several queues, in one datastore operation. A parent waits in the waiting-children state until all of its children are processed, then reads their results:

flows, err := bullmq.NewFlowProducer(&bullmq.FlowProducerOptions{Backend: backend})
if err != nil {
	log.Fatal(err)
}
defer flows.Close()

tree, err := flows.Add(ctx, bullmq.FlowJob{
	Name:      "render-report",
	QueueName: "reports",
	Data:      map[string]string{"month": "2026-10"},
	Children: []bullmq.FlowJob{
		{Name: "fetch", QueueName: "sources", Data: "sales"},
		{Name: "fetch", QueueName: "sources", Data: "costs",
			Opts: &bullmq.JobOptions{FailParentOnFailure: bullmq.Bool(true)}},
	},
}, nil)
if err != nil {
	log.Fatal(err)
}
log.Printf("report job %s waits for %d children", tree.Job.ID, len(tree.Children))

The processor of the parent reads the children's return values, by child key (bull:sources:<id> on Redis, sources:<id> on PostgreSQL):

func renderReport(ctx context.Context, job *bullmq.Job) (any, error) {
	var amounts map[string]float64
	if err := job.DecodeChildrenValues(ctx, &amounts); err != nil {
		return nil, err
	}
	total := 0.0
	for _, amount := range amounts {
		total += amount
	}
	return total, nil
}

job.ChildrenValues returns the raw JSON values instead.

  • Every queue of a flow is reached through the producer's backend, so they share its connections and its namespace (the Redis prefix or the PostgreSQL schema). FlowOpts.QueuesOptions sets default job options per queue.
  • FailParentOnFailure, ContinueParentOnFailure, IgnoreDependencyOnFailure and RemoveDependencyOnFailure decide what a failing child does to its parent, as described in the flows guide. By default the parent keeps waiting.
  • AddBulk adds several flows at once, and GetFlow reads a tree back.
  • Job.Dependencies, Job.DependenciesCount, Job.IgnoredChildrenFailures, Job.RemoveChildDependency and Job.RemoveUnprocessedChildren inspect and change the children of a parent.

A running job can also add children (with JobOptions.Parent, or a flow whose root has a Parent) and then wait for them:

moved, err := job.MoveToWaitingChildren(ctx, nil)
if err != nil {
	return nil, err
}
if moved {
	// Processed again once the children are done.
	return nil, bullmq.ErrWaitingChildren
}

Job schedulers

A job scheduler produces jobs on a cron pattern or at a fixed interval, as Node's upsertJobScheduler does:

// Every day at 09:00, Madrid time.
first, err := queue.UpsertJobScheduler(ctx, "daily-report",
	bullmq.RepeatOptions{Pattern: "0 9 * * *", Tz: "Europe/Madrid"},
	&bullmq.JobTemplate{Name: "report", Data: map[string]string{"kind": "daily"}})
if err != nil {
	log.Fatal(err)
}
if first != nil { // nil when the schedule produces no more jobs
	log.Printf("first report: job %s", first.ID)
}

// Every 10 seconds, 100 times at most.
if _, err := queue.UpsertJobScheduler(ctx, "poll",
	bullmq.RepeatOptions{Every: 10_000, Limit: 100}, nil); err != nil {
	log.Fatal(err)
}

schedulers, err := queue.JobSchedulers(ctx, 0, -1, true)
if err != nil {
	log.Fatal(err)
}
for _, s := range schedulers {
	log.Printf("%s: next run at %s", s.ID, time.UnixMilli(s.Next))
}

if _, err := queue.RemoveJobScheduler(ctx, "poll"); err != nil {
	log.Fatal(err)
}
  • Upserting again replaces the schedule and template of a scheduler. JobTemplate sets the name, data and options of the jobs; it can't set JobID, Delay, Deduplication or Repeat.
  • Only the job of the next iteration is stored, with the id repeat:<scheduler id>:<due time in ms>. The worker that fetches it adds the following one before processing it, so Go, Node.js and the other ports advance each other's schedulers. While no worker runs, a scheduler doesn't pile up jobs. RemoveJobScheduler removes that job only while it is still delayed: a job already waiting (such as the first job of an Every scheduler) or being processed runs once more.
  • Pattern takes 5 fields, or 6 with leading seconds, with names, ranges, steps, L and #. It is evaluated exactly as cron-parser evaluates it in Node.js, including across DST changes, so every port computes the same due times. W and H aren't supported.
  • Tz accepts the time zones Node.js accepts: IANA names in any case (america/new_york), ICU's legacy ids (PST) and fixed offsets (+03:00, UTC+3). Without it, patterns use the process's local time zone, as in Node.js. Time zones are read from the system's time zone database: on systems without one (scratch or distroless containers), add import _ "time/tzdata" to embed it in the binary. A worker that can't resolve a scheduler's time zone fails the iteration it fetched with the reason and an EventError, without processing it or adding the next one, so the schedule stops visibly instead of stalling.
  • Every schedulers accept an Offset; every scheduler a Limit, a StartDate and an EndDate (Unix milliseconds); Pattern schedulers Immediately, to produce their first job right away. A Go worker adds no job due after EndDate, where Node.js adds one more to Every schedulers (#5190).
  • QueueOptions.RepeatStrategy and WorkerOptions.RepeatStrategy replace cron for Pattern schedulers, as Node's settings.repeatStrategy does: it returns the next due time (Unix milliseconds) after millis, or 0 for no more runs, so Pattern can be any rule it understands. The queue that upserts a scheduler and every worker that advances it, in any language, need the same strategy; a worker without it fails the iteration.
  • Legacy repeatable jobs (Node's repeat option, BullMQ 5 and earlier) aren't supported: migrate them to job schedulers. A Go worker processes their jobs but can't schedule the next ones, and reports it with an EventError.

The PostgreSQL backend

backend := postgresbackend.New(postgresbackend.Options{
	ConnString: os.Getenv("DATABASE_URL"),
	Schema:     "jobs",
	PoolSize:   30,
})

postgresbackend stores queues with the tables and SQL that the Node.js, Python, Elixir and .NET ports use, so they all work on the same schema.

Option Default Meaning
ConnString A pgx connection string, URL or keyword/value. Required unless Pool is set
Schema bullmq Namespaces every queue, as the key prefix does on Redis
PoolSize 20 Size of the query pool (or the connection string's pool_max_conns)
Pool A *pgxpool.Pool to use instead; BullMQ never closes it. Its connections must use the schema as search_path (config.ConnConfig.RuntimeParams["search_path"] = "bullmq"). Its OnNotification/OnNotice callbacks aren't used on BullMQ's LISTEN connections
SkipVersionCheck false Skip the PostgreSQL 13 check
SkipMigrations false Don't migrate: the schema must already be up to date (see postgresbackend.Migrate)
  • Migrations. The first operation of the process reads the shared migration ledger and, unless it is up to date, creates or migrates the schema, in one transaction under the advisory lock every runtime uses. Every new backend checks that ledger: a schema that requires a newer BullMQ major version is refused with a *postgresbackend.SchemaVersionError. An up-to-date schema needs no DDL, so the application's role doesn't need to own it: it needs USAGE and CREATE on the schema (each queue gets a job id sequence on first use) and SELECT, INSERT, UPDATE and DELETE on its tables and sequences. To migrate as a deployment step instead, as Node.js does with runMigrations, call postgresbackend.Migrate(ctx, opts) with the owner's role and set SkipMigrations in the application, which then refuses a schema that isn't up to date. A schema migrated by any runtime is usable by the others.
  • Connections. Backends built with the same ConnString, Schema and PoolSize share one pgxpool pool per process. It opens connections on demand (pool_min_conns and pool_min_idle_conns are ignored for these shared pools; pass your own Pool to keep connections warm) and closes them when its last backend closes. Each worker and QueueEvents also holds one dedicated connection outside the pool, which LISTENs for new jobs or events, so idle workers wake up as soon as a job is added rather than polling. Size the server's max_connections for the pool plus one connection per worker and listener.
  • Worker discovery. The application_name of a worker's dedicated connection is <queue> or <queue>:w:<name>, as in Node.js, and is what Queue.Workers finds. PostgreSQL stores each non-ASCII byte of it as a 4-byte \xhh escape (é becomes \xc3\xa9; before PostgreSQL 16, a ?), which Queue.Workers undoes, and then truncates it to 63 bytes, so the workers of a queue with a long name may be missing, and long worker names are truncated. Non-ASCII characters make a name reach that limit sooner.
  • The backend of a queue built with postgresbackend.New is a *postgresbackend.Backend, which exposes Pool() and Schema().
  • Job data, return values and progress are stored as jsonb, so a job read back holds equal JSON values but not necessarily the same bytes in Job.Data and Job.ReturnValue: decode them rather than compare bytes.

Everything this guide describes works on both backends, with the caveats listed in FEATURE_PARITY.md and Known limitations.

Interoperability

Go shares queues with the other BullMQ runtimes on the same backend:

  • On Redis, use the same Prefix (bull by default) as the other side; on PostgreSQL, the same database and Schema.
  • Job data, return values and structured progress are JSON. A Go processor decodes data added by Node.js with job.DecodeData, and a Node.js parent reads a Go child's return value as JSON.
  • Job options are stored in the same form as Node.js stores them, so the retries, backoff, priorities, removal policies, flows and deduplication of a job behave the same whichever runtime processes it. A custom backoff type needs a BackoffStrategy on Go workers.
  • QueueEvents in any runtime sees the events of Go workers, and the other way round. Job schedulers created in one runtime are advanced by the workers of the others.
  • On PostgreSQL, Queue.Workers doesn't list .NET workers, which name their connections differently (#5184).

Testing your code

Keep processors as plain functions and unit test them with a *bullmq.Job built in the test. Methods that reach the datastore, such as UpdateProgress or Log, return bullmq.ErrNoContext on such a job, so keep those calls out of the logic you test in isolation:

func TestSendWelcomeRejectsBadPayloads(t *testing.T) {
	job := &bullmq.Job{ID: "1", Name: "welcome", Data: json.RawMessage(`"not an object"`)}
	_, err := sendWelcome(context.Background(), job)
	if !bullmq.IsUnrecoverable(err) {
		t.Fatalf("err = %v, want an unrecoverable error", err)
	}
}

For integration tests, run a real Redis or PostgreSQL (for example with docker compose, or testcontainers) and give every test its own queue, so tests can run in parallel and leave nothing behind:

func TestWelcomeEmailIsSent(t *testing.T) {
	ctx := context.Background()
	backend := redisbackend.New(redisbackend.Options{Addr: "127.0.0.1:6379"})
	name := fmt.Sprintf("emails-test-%d", time.Now().UnixNano())

	queue, err := bullmq.NewQueue(name, &bullmq.QueueOptions{Backend: backend})
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() {
		_ = queue.Obliterate(context.Background(), &bullmq.ObliterateOptions{Force: true})
		_ = queue.Close()
	})

	worker, err := bullmq.NewWorker(name, sendWelcome, &bullmq.WorkerOptions{Backend: backend})
	if err != nil {
		t.Fatal(err)
	}
	go func() { _ = worker.Run(ctx) }()
	t.Cleanup(func() { _ = worker.Close() })

	job, err := queue.Add(ctx, "welcome", Email{To: "ada@example.com"}, nil)
	if err != nil {
		t.Fatal(err)
	}

	deadline := time.Now().Add(10 * time.Second)
	for {
		state, err := queue.JobState(ctx, job.ID)
		if err != nil {
			t.Fatal(err)
		}
		if state == bullmq.StateCompleted {
			break
		}
		if time.Now().After(deadline) {
			t.Fatalf("job is %s, want completed", state)
		}
		time.Sleep(20 * time.Millisecond)
	}
}

t.Cleanup runs its functions in reverse order, so the worker is closed before the queue is obliterated. On PostgreSQL, use a dedicated database or Schema for tests; it is migrated on first use. To test stalled-job handling quickly, lower LockDuration and StalledInterval.

Known limitations

  • No telemetry. There are no OpenTelemetry hooks yet; use worker events or OnEvent for metrics and tracing.
  • Redis Cluster is lightly tested, Sentinel untested. A redis.UniversalClient for a cluster or a failover setup can be passed as Client. CI only runs on a standalone server; the cluster tests (workers, worker discovery, queue events) run when REDIS_CLUSTER_ADDRS is set. On a cluster, the prefix needs a hash tag (for example {bull}) so that the keys of a queue share a slot, as in Node.js.
  • QueueEvents on PostgreSQL can miss events under concurrency. Event ids are assigned before their transaction commits, so a listener can skip an event that commits after a later one was read. Every runtime is affected until #5183 is fixed. Don't rely on QueueEvents to see every completed or failed event on PostgreSQL; read the job state instead.
  • Time zones need a database. Job schedulers with a Tz read the system's time zone database; import time/tzdata in containers that don't have one.
  • No legacy repeatable jobs and no sandboxed processors. Use job schedulers and goroutines.

FEATURE_PARITY.md lists the Node.js features that aren't implemented yet.

Upgrading from the pre-release API

The API changed before the first release; code written against the early drafts of this port needs these changes:

Before Now
Redis: bullmq.RedisOptions{Addr: ...} in the options; Redis when unset Backend: redisbackend.New(redisbackend.Options{Addr: ...}), required in every options struct
Prefix in QueueOptions, WorkerOptions and QueueEventsOptions redisbackend.Options.Prefix
bullmq.RedisBackendFactory, bullmq.NewRedisBackend, *bullmq.RedisBackend redisbackend.New, redisbackend.NewBackend, *redisbackend.Backend
queue.Client(), queue.Keys(), bullmq.Keys queue.Backend().(*redisbackend.Backend).Client() and .Keys(), redisbackend.Keys
worker.Pause() returned at once worker.Pause(ctx, doNotWaitActive) waits for the active jobs unless doNotWaitActive is true
EventStalled reported lost locks EventLockRenewalFailed and EventLocksRenewed, with Event.JobIDs; EventStalled is only for the stalled check
Full event channel dropped events silently Worker.DroppedEvents counts them; WorkerOptions.OnEvent sees every event
Cancelling Run's context failed in-flight jobs They stay active, without using up an attempt, for the stalled check to recover
Queue.Workers returned connection names It returns []bullmq.WorkerInfo, with the worker name and the connection's fields
RemoveAll() was stored as {"count":0} Stored as true, as in the other ports
Worker.Run and QueueEvents.Run returned context.Canceled after Close They return nil after Close, and still return the context's error when their context is done
job.Retry(ctx, state) job.Retry(ctx, state, opts), where opts (or nil) can reset the attempt counters
queue.RetryJobs(ctx, state, count) returned an always-0 int64 queue.RetryJobs(ctx, &bullmq.RetryJobsOptions{State, Count, Before}) returns only an error; State defaults to failed
queue.PromoteJobs(ctx, count) returned an always-0 int64 It returns only an error
queue.Jobs(ctx, state, start, end, asc), queue.JobIDs(...) with one state queue.Jobs(ctx, start, end, asc, states...): several states, or none for all of them
queue.GlobalConcurrency(ctx) returned 0 when no limit was set It returns a *int64, nil when no limit is set
queue.Obliterate(ctx, force, count) queue.Obliterate(ctx, &bullmq.ObliterateOptions{Force, Count}), or nil
job.UpdateProgress(ctx, bullmq.Progress), built with NumberProgress or JSONProgress job.UpdateProgress(ctx, v) with a number or any JSON value; a Progress still works
job.RemoveChildDependency returned false, nil for a job without a parent It returns an error matching bullmq.ErrParentJobNotExist, as Node.js throws
redisbackend.Options without Addr connected to 127.0.0.1:6379 It connects to localhost:6379 (redisbackend.DefaultAddr), as ioredis and go-redis do; set Addr to keep 127.0.0.1
A Queue never wrote the queue metadata It writes version and opts.maxLenEvents before its first command, as Node's Queue does; QueueOptions.SkipMetasUpdate turns it off
A failed AddBulk or flow on PostgreSQL kept the jobs it had added It adds none: the batch is rolled back

Custom Backend implementations have more to change: SignalWork is gone, MoveToCompleted and MoveToFailed return a *FinishResult and can fetch the next job, FetchResult reports RateLimitDelay and NextDelayedAt, WaitForJob returns a WaitResult, BackendOptions.Prefix moved to the backends, RetryFinishedJob takes RetryOptions, a backend writes BackendOptions.QueueMeta before its first command, and there are new methods for flows, job schedulers, manual rate limiting, deduplication, counts and the queue metadata (GetQueueMeta). The documentation of the Backend interface describes the contract.

Contributing

The source of truth for this port is the golang/ directory of the main BullMQ repository. The bullmq-go repository is published automatically on every Go release and already contains the generated Lua commands and SQL files, so go get works out of the box. Contributions go to the main repository.

The Lua commands and SQL files aren't committed to the golang directory: they are generated from the shared sources, so every port stays byte-for-byte identical. So is scripts_version.go, which holds the version of the root package.json (bullmq.ScriptsVersion). Before building or testing, run from the repository root:

yarn install
yarn generate:raw:scripts
yarn copy:lua:golang
yarn copy:sql:golang

This resolves the --- @include directives of src/commands/*.lua into rawScripts/ and copies the result into golang/redisbackend/commands/, and copies the migrations and commands of src/postgres into golang/postgresbackend/sql/, where go:embed picks them up. Both copy steps also write golang/scripts_version.go.

The tests need a Redis server, and a PostgreSQL database for the PostgreSQL backend. From the repository root:

docker compose up -d
cd golang
go test ./...

Set REDIS_ADDR to use another Redis server, and POSTGRES_URL to run the tests on PostgreSQL too (the postgres service of docker-compose.yml listens on port 5432):

REDIS_ADDR=127.0.0.1:6380 \
  POSTGRES_URL='postgres://postgres:postgres@127.0.0.1:5432/bullmq_test?sslmode=disable' \
  go test ./...

Tests that need Redis are skipped when no server is reachable, and the PostgreSQL tests when POSTGRES_URL isn't set. The Redis Cluster tests run when REDIS_CLUSTER_ADDRS lists seed nodes of a cluster (for example 127.0.0.1:7000,127.0.0.1:7001). The PostgreSQL tests create their own schemas (bullmq_go_test and gotest_pg_*) and leave the default bullmq schema alone. The behaviour tests of the root package run once per datastore, as subtests named after it (for example TestWorkerProcessesJobs/redis and TestWorkerProcessesJobs/postgres); the datastores are listed in internal/testbackends. Tests specific to a backend live in redisbackend and postgresbackend.

License

MIT

Documentation

Overview

Package bullmq is the official Go implementation of BullMQ, the job queue for Redis and PostgreSQL.

Jobs are fully interoperable with the Node.js, Python, Elixir, PHP, Rust and .NET ports: every state transition runs the same shared Lua scripts (Redis) or SQL (PostgreSQL), so a queue may be produced by one language and consumed by another.

Backends

Queue, Worker, QueueEvents and FlowProducer only depend on the Backend interface, and this package imports no datastore driver. The datastore is chosen with the required Backend option, a BackendFactory:

  • redisbackend.New, in package github.com/taskforcesh/bullmq-go/redisbackend, for Redis. Its Options hold the address, credentials, the key prefix ("bull" by default) or an existing go-redis client.
  • postgresbackend.New, in package github.com/taskforcesh/bullmq-go/postgresbackend, for PostgreSQL. Its Options hold the connection string or pgxpool pool, the schema ("bullmq" by default, migrated on first use) and the pool size.

A constructor called without a Backend returns a *ConfigError.

Adding and processing jobs

backend := redisbackend.New(redisbackend.Options{Addr: "127.0.0.1:6379"})

queue, err := bullmq.NewQueue("emails", &bullmq.QueueOptions{Backend: backend})
if err != nil {
	return err
}
defer queue.Close()

if _, err := queue.Add(ctx, "welcome", payload, nil); err != nil {
	return err
}

worker, err := bullmq.NewWorker("emails", func(ctx context.Context, job *bullmq.Job) (any, error) {
	var p Payload
	if err := job.DecodeData(&p); err != nil {
		return nil, bullmq.NewUnrecoverableError("invalid payload: %v", err)
	}
	return send(ctx, p)
}, &bullmq.WorkerOptions{Backend: backend, Concurrency: 10})
if err != nil {
	return err
}
defer worker.Close()

return worker.Run(ctx)

A Processor returns the job's result, stored as JSON, or an error that fails the attempt; the job is retried while JobOptions.Attempts remain, after its Backoff. Each processing slot finishes its job and fetches the next one in the same backend call, so a busy worker needs about one round trip per job whatever its concurrency.

Stopping a worker

Worker.Close is a graceful shutdown: the worker stops fetching and waits for the jobs in flight. Cancelling the context passed to Worker.Run stops it immediately: the processors' contexts are cancelled, and the jobs they were running stay active, without using up an attempt, until the stalled check of a running worker moves them back to wait. Close must still be called to release the connections. Worker.CancelJob cancels the context of one job, which then fails with the given reason; context.Cause tells a processor why its context was cancelled (ErrJobCancelled, ErrLockLost or the cause of the Run context).

Events

Worker.Events publishes lifecycle events on a buffered channel that drops events when the reader falls behind (Worker.DroppedEvents counts them); WorkerOptions.OnEvent receives every event synchronously. QueueEvents reads the event stream shared by every worker of a queue, in any language.

Flows and job schedulers

FlowProducer adds trees of jobs whose parents wait for their children. Queue.UpsertJobScheduler creates job schedulers, which repeat a job on a cron pattern, evaluated as cron-parser does in Node.js, or at a fixed interval.

The README of the golang directory of the BullMQ repository is the user guide, and FEATURE_PARITY.md lists what is implemented relative to the Node.js reference implementation.

Index

Constants

View Source
const (
	ErrCodeJobNotExist          = -1
	ErrCodeJobLockNotExist      = -2
	ErrCodeJobNotInState        = -3
	ErrCodeJobPendingDeps       = -4
	ErrCodeParentJobNotExist    = -5
	ErrCodeJobLockMismatch      = -6
	ErrCodeJobHasFailedChildren = -9
)

Error codes returned by the shared Lua commands, and by the shared SQL commands on PostgreSQL (see ScriptError).

View Source
const (
	ErrCodeJobBelongsToJobScheduler = -8
	ErrCodeSchedulerJobIDCollision  = -10
	ErrCodeSchedulerJobSlotsBusy    = -11
)

Script error codes of job schedulers.

View Source
const DefaultEventsMaxLen int64 = 10000

DefaultEventsMaxLen is the default QueueOptions.EventsMaxLen.

View Source
const DefaultMaxEvents int64 = 1000

DefaultMaxEvents is the maxEvents of QueueEventsProducer.PublishEvent when it is 0, as in Node.js.

View Source
const ErrCodeParentJobCannotBeReplaced = -7

ErrCodeParentJobCannotBeReplaced is the script error code returned when a job that already belongs to a parent is added under another one.

View Source
const ScriptsVersion = "6.7.10"

ScriptsVersion is the version of the Node.js BullMQ package whose Lua and SQL scripts this module embeds. Queues store it in their metadata as `bullmq:<ScriptsVersion>`, as Node's Queue does, so that dashboards enable the features of that version. Version is the version of this module.

View Source
const Version = "0.1.0"

Version is the version of this module. The release process sets it (see scripts/publishGolang.sh). Queues store ScriptsVersion in their metadata instead.

Variables

View Source
var (
	// ErrJobNotFound is returned when the job an operation refers to does
	// not exist (any longer) in the datastore.
	ErrJobNotFound = errors.New("bullmq: missing job key")
	// ErrJobLockNotExist is returned when the job lock is missing.
	ErrJobLockNotExist = errors.New("bullmq: missing job lock")
	// ErrJobNotInState is returned when a job is not in the expected state set.
	ErrJobNotInState = errors.New("bullmq: job is not in the expected state")
	// ErrJobPendingDependencies is returned when a parent still has pending children.
	ErrJobPendingDependencies = errors.New("bullmq: job has pending dependencies")
	// ErrParentJobNotExist is returned when the referenced parent job is missing.
	ErrParentJobNotExist = errors.New("bullmq: parent job does not exist")
	// ErrJobLockMismatch is returned when the lock is owned by another client.
	ErrJobLockMismatch = errors.New("bullmq: lock is not owned by this client")
	// ErrParentJobCannotBeReplaced is returned when a job that already
	// belongs to a parent is added again under another one.
	ErrParentJobCannotBeReplaced = errors.New("bullmq: the parent of a job cannot be replaced")
	// ErrJobHasFailedChildren is returned when a parent cannot complete because a child failed.
	ErrJobHasFailedChildren = errors.New("bullmq: job has failed children")
	// ErrJobBelongsToJobScheduler is returned when removing the pending job
	// of a job scheduler, which only RemoveJobScheduler may remove.
	ErrJobBelongsToJobScheduler = errors.New("bullmq: job belongs to a job scheduler and cannot be removed directly")
	// ErrSchedulerJobIDCollision is returned when the job of a scheduler's
	// next iteration already exists.
	ErrSchedulerJobIDCollision = errors.New("bullmq: cannot create job scheduler iteration, job id already exists")
	// ErrSchedulerJobSlotsBusy is returned when the jobs of the next
	// iterations of an Every scheduler already exist.
	ErrSchedulerJobSlotsBusy = errors.New("bullmq: cannot create job scheduler iteration, current and next time slots already have jobs")
	// ErrJobLocked is returned by Job.Remove when the job (or a dependency) is
	// currently locked by another worker and therefore cannot be removed.
	ErrJobLocked = errors.New("bullmq: job is locked by another worker")

	// ErrWorkerClosed is returned by Worker.Run when the worker was already
	// run or is closed, and by Worker.Pause when the worker is closed while
	// Pause waits for its jobs.
	ErrWorkerClosed = errors.New("bullmq: worker is closed")
	// ErrQueueEventsClosed is returned by QueueEvents.Run when it was
	// already called or the listener is closed.
	ErrQueueEventsClosed = errors.New("bullmq: queue events is closed")
	// ErrNoContext is returned by the methods of a Job that reach the
	// datastore, such as UpdateProgress or Log, when the Job has no backend:
	// it was built by the caller (for example in a unit test) rather than
	// returned by a Queue, a Worker or a FlowProducer.
	ErrNoContext = errors.New("bullmq: job has no backend")
	// ErrDelayed is returned by a processor that has moved its job to the delayed set.
	ErrDelayed = errors.New("bullmq: job moved to delayed")
	// ErrWaitingChildren is returned by a processor that moved its job to waiting-children.
	ErrWaitingChildren = errors.New("bullmq: job moved to waiting children")
	// ErrWaiting is returned by a processor that moved its job back to wait
	// with Job.MoveToWait, as Node's WaitingError.
	ErrWaiting = errors.New("bullmq: job moved to wait")

	// ErrRateLimited is returned by a processor to put its job back in the
	// wait list without using up an attempt, because the queue is rate
	// limited (see Worker.RateLimit), as Node's Worker.RateLimitError does.
	// The worker then waits until the rate limit lifts.
	ErrRateLimited = errors.New("bullmq: rate limit exceeded")

	// ErrJobCancelled is the cause (see context.Cause) of the context of a
	// job cancelled with Worker.CancelJob or Worker.CancelAllJobs. The cause
	// reads as the cancellation reason and matches ErrJobCancelled with
	// errors.Is.
	ErrJobCancelled = errors.New("bullmq: job cancelled")
	// ErrLockLost is the cause (see context.Cause) of the context of a job
	// whose lock the worker could not renew: the job may belong to another
	// worker now.
	ErrLockLost = errors.New("bullmq: job lock lost")

	// ErrNotSupported is returned, wrapped, by an operation the backend
	// does not implement, as Node's backends throw "not implemented".
	ErrNotSupported = errors.New("bullmq: not supported by this backend")
)

Sentinel errors returned by the library.

AllStates lists every state that can be queried through Queue.JobCounts.

View Source
var ErrFlowProducerClosed = errors.New("bullmq: flow producer is closed")

ErrFlowProducerClosed is returned by the operations of a closed FlowProducer.

View Source
var ErrLegacyRepeatableJob = errors.New("bullmq: legacy repeatable job metadata is not supported")

ErrLegacyRepeatableJob is returned for repeatable jobs created with the legacy repeat API (BullMQ v5 and earlier), which this port does not support. They must be migrated to job schedulers.

Functions

func Bool

func Bool(b bool) *bool

Bool returns a pointer to b, for use with pointer-typed JobOptions fields such as LIFO.

func Int

func Int(n int) *int

Int returns a pointer to n, for use with pointer-typed options fields such as WorkerOptions.MaxStalledCount.

func Int64

func Int64(n int64) *int64

Int64 returns a pointer to n, for use with pointer-typed JobOptions fields such as Delay.

func IsUnrecoverable

func IsUnrecoverable(err error) bool

IsUnrecoverable reports whether err (or any error it wraps) is unrecoverable.

func NewUnrecoverableError

func NewUnrecoverableError(format string, args ...any) error

NewUnrecoverableError builds an error that stops a job from being retried.

Types

type Backend

type Backend interface {

	// Close releases every connection owned by the backend. Connections that
	// were supplied by the caller are left open.
	Close() error

	// SetName labels the connection used for blocking reads, for
	// observability. It is a no-op for backends without such a concept.
	SetName(ctx context.Context, name string) error

	// IsTransientError reports whether err is a connectivity or availability
	// problem that is worth retrying, as opposed to a logic error.
	IsTransientError(err error) bool

	// QueueName returns the bare queue name.
	QueueName() string

	// QualifiedName returns the cross-backend logical identifier of the queue,
	// used for example as a flow parent reference. Redis: `{prefix}:{queue}`;
	// backends without a prefix (PostgreSQL) return the bare queue name, as
	// Node does.
	QualifiedName() string

	// ResolveParent resolves the parent a job is added under into the
	// identifiers the backend persists, without touching the datastore. It
	// returns the parent reference and the backend-specific parent key
	// (Redis: `{prefix}:{queue}:{id}`), matching what fetching the job later
	// reports as [JobRecord.Parent] and [JobRecord.ParentKey].
	ResolveParent(parent *ParentOptions) (*ParentKeys, string, error)

	// ClientName builds the connection name used for worker discovery. Redis:
	// `{prefix}:{base64(queue)}{suffix}`; PostgreSQL: `{queue}{suffix}`.
	ClientName(suffix string) string

	// AddJob adds a single job, routing it to its initial state (wait,
	// delayed, prioritized, waiting-children) based on its options, and
	// returns its id.
	AddJob(ctx context.Context, job NewJob) (string, error)

	// AddJobs adds many jobs in a single efficient operation (a Redis
	// transaction, an SQL transaction, ...) and returns their ids in order.
	// When the datastore rejects a job, it returns an error; as for AddFlow,
	// PostgreSQL then adds none of them, while Redis keeps those it accepted.
	AddJobs(ctx context.Context, jobs []NewJob) ([]string, error)

	// MoveToActive atomically moves the next eligible job to active, locks
	// it with opts.Token for opts.LockDuration and returns it. When no job can
	// be fetched it returns a result with a nil Job and the reason, as
	// described on [FetchResult]. It never blocks waiting for a job.
	MoveToActive(ctx context.Context, opts MoveToActiveOptions) (*FetchResult, error)

	// MoveToCompleted moves an active job owned by opts.Token to completed
	// and records returnValue. When opts.FetchNext is set it then fetches the
	// next job exactly as MoveToActive would, locked with the same token, and
	// reports it in [FinishResult.Next].
	MoveToCompleted(ctx context.Context, jobID string, returnValue []byte, opts FinishOptions) (*FinishResult, error)

	// MoveToFailed moves an active job owned by opts.Token to failed and
	// records failure. Fetching the next job works as in MoveToCompleted.
	MoveToFailed(ctx context.Context, jobID string, failure FailureInfo, opts FinishOptions) (*FinishResult, error)

	// MoveToDelayed reschedules an active job owned by token to run after
	// delay. When opts.FetchNext is set it then tries to fetch the next job,
	// locked with the same token, and returns the outcome; otherwise it
	// returns nil. Unlike the finishing operations it may report only a
	// fetched job, without the rate-limit or delayed-job hints (Redis does
	// so), so a result with a nil Job means "fetch again", not "drained".
	MoveToDelayed(ctx context.Context, jobID, token string, delay time.Duration, opts MoveToDelayedOptions) (*FetchResult, error)

	// MoveJobFromActiveToWait puts an active job back in the wait list (or
	// the prioritized set, keeping its priority) without counting an attempt,
	// and releases its lock. Workers use it when a processor reports that the
	// queue is rate limited. An empty token skips the lock check, as Node's
	// default token "0" does. It returns the remaining rate-limit time, or 0
	// when the queue is not rate limited.
	MoveJobFromActiveToWait(ctx context.Context, jobID, token string) (time.Duration, error)

	// MoveToWaitingChildren parks an active parent job until its children
	// finish. It returns true when the job was moved and false when there were
	// no pending dependencies.
	MoveToWaitingChildren(ctx context.Context, jobID, token string, child *ParentKeys) (bool, error)

	// RetryJob puts an active job straight back into the wait list.
	RetryJob(ctx context.Context, jobID, token string, lifo bool, failure *FailureInfo) error

	// RetryFinishedJob reprocesses a completed or failed job, resetting its
	// attempt counters as opts asks.
	RetryFinishedJob(ctx context.Context, jobID string, state JobState, lifo bool, opts RetryOptions) error

	// Promote makes a delayed job available immediately.
	Promote(ctx context.Context, jobID string) error

	// MoveStalledJobsToWait recovers active jobs whose lock expired and returns
	// the ids of the jobs that were moved.
	MoveStalledJobsToWait(ctx context.Context, opts StalledOptions) ([]string, error)

	// RetryFinishedJobs moves up to count jobs of state that finished at or
	// before timestamp (Unix milliseconds) back to wait. It returns a cursor,
	// not a count: 0 once nothing is left to move, positive while more may
	// remain.
	RetryFinishedJobs(ctx context.Context, state JobState, count, timestamp int64) (int64, error)

	// PromoteJobs moves up to count delayed jobs back to wait. It returns a
	// cursor as RetryFinishedJobs does.
	PromoteJobs(ctx context.Context, count int64) (int64, error)

	// Pause pauses (true) or resumes (false) the whole queue.
	Pause(ctx context.Context, paused bool) error

	// Drain removes waiting jobs, and delayed jobs too when delayed is true.
	Drain(ctx context.Context, delayed bool) error

	// CleanJobsByState removes up to limit jobs of state that are older than
	// timestamp (Unix milliseconds) and returns their ids.
	CleanJobsByState(ctx context.Context, state JobState, timestamp, limit int64) ([]string, error)

	// Obliterate destroys the queue and its contents, removing up to count
	// jobs per call. It returns a cursor: 0 once the obliteration is
	// complete.
	Obliterate(ctx context.Context, force bool, count int64) (int64, error)

	// ExtendLock refreshes the lock of one active job. It returns
	// [ErrJobLockNotExist] when the lock is gone or owned by another token.
	ExtendLock(ctx context.Context, jobID, token string, duration time.Duration) error

	// ExtendLocks refreshes the locks of several active jobs at once and
	// returns the ids whose lock could not be extended.
	ExtendLocks(ctx context.Context, locks []JobLock, duration time.Duration) ([]string, error)

	// UpdateData replaces the JSON payload of a job.
	UpdateData(ctx context.Context, jobID string, data []byte) error

	// UpdateProgress stores a job's progress and emits the progress event.
	UpdateProgress(ctx context.Context, jobID string, progress Progress) error

	// AddLog appends a row to the job's log, keeping at most keepLogs rows when
	// keepLogs is positive, and returns the number of rows.
	AddLog(ctx context.Context, jobID, row string, keepLogs int64) (int64, error)

	// GetJobLogs returns the log rows in [start, end] and the total row count.
	GetJobLogs(ctx context.Context, jobID string, start, end int64) ([]string, int64, error)

	// ChangeDelay changes the delay of a delayed job.
	ChangeDelay(ctx context.Context, jobID string, delay time.Duration) error

	// ChangePriority changes the priority (and lifo flag) of a waiting job.
	ChangePriority(ctx context.Context, jobID string, priority int64, lifo bool) error

	// Remove deletes a job and, optionally, its children. It returns false when
	// the job (or a dependency) is locked by another worker.
	Remove(ctx context.Context, jobID string, removeChildren bool) (bool, error)

	// GetState returns the state of a job, or [StateUnknown].
	GetState(ctx context.Context, jobID string) (JobState, error)

	// GetJob returns the stored job, or nil when it does not exist.
	GetJob(ctx context.Context, jobID string) (*JobRecord, error)

	// GetJobs returns the jobs of each of states in turn, those at positions
	// start to end of that state, ordered as GetRanges orders them. A job is
	// returned once even if it shows up in two states, and jobs removed
	// meanwhile are skipped.
	GetJobs(ctx context.Context, states []JobState, start, end int64, asc bool) ([]*JobRecord, error)

	// GetCounts returns the number of jobs per requested state, in order.
	GetCounts(ctx context.Context, states []JobState) ([]int64, error)

	// GetRanges returns the ids of the jobs of each of states in turn, those
	// at positions start to end (inclusive; a negative end counts from the
	// last one) of that state, oldest or first due first when asc is set.
	// An id is returned once even if it shows up in two states.
	GetRanges(ctx context.Context, states []JobState, start, end int64, asc bool) ([]string, error)

	// IsMaxed reports whether the queue reached its global concurrency limit.
	IsMaxed(ctx context.Context) (bool, error)

	// GetRateLimitTTL returns the time left in the current rate limit window,
	// in milliseconds, once at least maxJobs jobs were counted in it, and 0
	// otherwise. A maxJobs of 0 uses the max of the global rate limit and,
	// without one, returns the time left whatever the count, or -2 when no
	// window is open (-1 for a window without expiry), as Redis PTTL does.
	GetRateLimitTTL(ctx context.Context, maxJobs int64) (int64, error)

	// SetRateLimit rate limits the whole queue for ttl, as if the limiter's
	// window were full: until it expires, fetching reports a rate limit
	// instead of a job. Like the shared commands, the limit only applies to
	// fetches made with a limiter (a worker Limiter or a global rate limit).
	// ttl must be at least 1ms.
	SetRateLimit(ctx context.Context, ttl time.Duration) error

	// GetMetrics returns the metrics collected for the completed or failed
	// state.
	GetMetrics(ctx context.Context, state JobState, start, end int64) (*Metrics, error)

	// GetClientList returns the connection list(s) of the datastore, used
	// for worker discovery, in the `CLIENT LIST` format: one string per
	// server (a cluster has several), with one connection per line as
	// space-separated key=value fields, including `name`. Queue.Workers
	// parses them. Redis returns CLIENT LIST itself; other backends report
	// their named connections as `name=<name>` lines (PostgreSQL: one per
	// application_name), or nothing.
	GetClientList(ctx context.Context) ([]string, error)

	// SetQueueMeta sets one or more queue metadata fields.
	SetQueueMeta(ctx context.Context, values map[string]any) error

	// GetQueueMetaField reads a single metadata field. The bool is false when
	// the field does not exist.
	GetQueueMetaField(ctx context.Context, field string) (string, bool, error)

	// RemoveQueueMetaFields removes metadata fields.
	RemoveQueueMetaFields(ctx context.Context, fields ...string) error

	// LastEventID returns the id of the newest event, or "0-0" when there is
	// none (the Redis stream syntax, which other backends reuse for "before
	// the first event"). Reading from it only yields events produced
	// afterwards. Event ids are opaque to callers.
	LastEventID(ctx context.Context) (string, error)

	// ReadEvents blocks up to block waiting for events newer than lastID. It
	// returns no events when the wait times out.
	ReadEvents(ctx context.Context, lastID string, block time.Duration) ([]QueueEvent, error)

	// WaitForJob blocks up to timeout until the queue signals that a job may
	// be available or that a delayed job was scheduled, then reports it in a
	// [WaitResult]. A timeout is not an error: it returns a zero WaitResult.
	// When ctx is done it returns promptly with ctx's error. It uses the
	// connection dedicated to blocking reads.
	//
	// A backend MAY return early, with or without Woken, for example when a
	// signal was meant for another worker or its blocking primitive cannot
	// wait that long. The caller must cope by fetching again (and finding
	// nothing) or waiting again; it must never rely on WaitForJob for timing.
	//
	// Workers may call it while some of their jobs are still being processed,
	// so it must not report work that cannot be claimed, for example while
	// the queue is paused or at its global concurrency limit.
	WaitForJob(ctx context.Context, timeout time.Duration) (WaitResult, error)

	// ForQueue returns a backend for another queue of the same namespace
	// that shares this backend's connections, as Node's forQueue does.
	// [FlowProducer] uses it to reach every queue of a flow over one
	// connection. name is a bare queue name or a qualified name as returned
	// by QualifiedName. The returned backend does not own the connections:
	// closing it releases only what it opened itself, and it stops working
	// once this backend is closed.
	ForQueue(name string) (Backend, error)

	// AddFlow inserts the jobs of one or more flows in a single operation (a
	// Redis transaction, an SQL transaction) and returns their ids in
	// order. Each entry names its own queue, which may differ from this
	// backend's. Entries are ordered so that a parent comes before its
	// children, and a parent is released from waiting-children only once the
	// whole tree has been inserted, if none of its children is pending.
	//
	// When the datastore rejects an entry, for example because its parent
	// does not exist ([ErrParentJobNotExist]) or because the job already
	// exists under another parent ([ErrParentJobCannotBeReplaced]), AddFlow
	// returns an error for the first rejected entry. A datastore that can
	// roll back, such as PostgreSQL, then adds none of the entries; Redis
	// keeps those it accepted.
	AddFlow(ctx context.Context, entries []FlowEntry) ([]string, error)

	// GetDependencies returns the children of a parent job grouped by
	// status, identified by their keys (`{QualifiedName}:{id}`). With nil
	// opts every group is returned in full; otherwise only the requested
	// groups are, one page each, with the cursor of the next page.
	GetDependencies(ctx context.Context, jobID string, opts *DependenciesOptions) (*Dependencies, error)

	// GetDependencyCounts returns how many children of a parent job are in
	// each status.
	GetDependencyCounts(ctx context.Context, jobID string) (DependencyCounts, error)

	// GetProcessedChildrenValues returns the return value (JSON) of every
	// completed child of a parent job, by child key.
	GetProcessedChildrenValues(ctx context.Context, jobID string) (map[string]json.RawMessage, error)

	// GetIgnoredChildrenFailures returns the failure reason of every child
	// of a parent job whose failure was ignored (IgnoreDependencyOnFailure or
	// ContinueParentOnFailure), by child key.
	GetIgnoredChildrenFailures(ctx context.Context, jobID string) (map[string]string, error)

	// RemoveChildDependency detaches a job that has not finished yet from
	// the parent stored under parentKey (see [JobRecord.ParentKey]), and
	// moves the parent to wait when it was its last pending child. It
	// returns false when there was no such dependency, [ErrJobNotFound] when
	// the job does not exist and [ErrParentJobNotExist] when the parent does
	// not.
	RemoveChildDependency(ctx context.Context, jobID, parentKey string) (bool, error)

	// RemoveUnprocessedChildren removes, recursively, the children of a
	// parent job that have not been processed yet. Active, completed and
	// failed children, and locked ones, are kept.
	RemoveUnprocessedChildren(ctx context.Context, jobID string) error

	// AddJobScheduler creates the job scheduler s.ID, or replaces its
	// schedule and template, and adds the job of its next iteration,
	// removing the pending job of the previous one. For Every schedulers
	// the backend computes the next iteration itself. It returns the id of
	// the added job and its delay in milliseconds. It fails with
	// [ErrSchedulerJobIDCollision] when a job of a Pattern scheduler with
	// that id already exists, and with [ErrSchedulerJobSlotsBusy] when no
	// free slot was found for an Every scheduler.
	AddJobScheduler(ctx context.Context, s NewJobScheduler) (string, int64, error)

	// UpdateJobSchedulerNextMillis advances the job scheduler schedulerID
	// to the iteration due at nextMillis (computed by the backend for Every
	// schedulers) and adds its job, with options jobOpts and the stored
	// template data (templateData is a fallback). Only the job of the
	// current iteration, producerID, may advance it. It returns the id of
	// the added job, or "" when none was added: the scheduler is gone,
	// producerID is not the current iteration, or the job already exists
	// (a `duplicated` event is then emitted).
	UpdateJobSchedulerNextMillis(ctx context.Context, schedulerID string, nextMillis int64, templateData []byte, jobOpts *JobOptions, producerID string) (string, error)

	// RemoveJobScheduler removes a job scheduler and the job of its next
	// iteration while that job is still delayed. It reports whether the
	// scheduler existed.
	RemoveJobScheduler(ctx context.Context, schedulerID string) (bool, error)

	// GetJobScheduler returns a job scheduler with the due time of its next
	// job, or nil when it does not exist or has no stored metadata.
	GetJobScheduler(ctx context.Context, schedulerID string) (*JobScheduler, error)

	// GetJobSchedulersRange returns the job schedulers ranked start to end
	// (inclusive; a negative end counts from the last one) by the due time
	// of their next job, latest first unless asc is set.
	GetJobSchedulersRange(ctx context.Context, start, end int64, asc bool) ([]JobSchedulerNext, error)

	// GetJobSchedulersCount returns the number of job schedulers.
	GetJobSchedulersCount(ctx context.Context) (int64, error)

	// IsJobScheduler reports whether id is a job scheduler, as opposed to a
	// legacy repeatable job, which this port does not support.
	IsJobScheduler(ctx context.Context, id string) (bool, error)

	// GetDeduplicationJobID returns the id of the job that holds the
	// deduplication id dedupID (see [DeduplicationOptions]), or "" when no
	// job holds it: it was never set, was removed, or its TTL expired.
	GetDeduplicationJobID(ctx context.Context, dedupID string) (string, error)

	// RemoveDeduplicationKey releases the deduplication id dedupID if the
	// job jobID still holds it, and reports whether it did.
	RemoveDeduplicationKey(ctx context.Context, dedupID, jobID string) (bool, error)

	// DeleteDeduplicationKey releases the deduplication id dedupID,
	// whichever job holds it, and reports whether there was one to release.
	DeleteDeduplicationKey(ctx context.Context, dedupID string) (bool, error)

	// GetCountsPerPriority returns, for each of priorities in order, how
	// many waiting jobs have that priority; 0 counts the waiting jobs
	// without a priority.
	GetCountsPerPriority(ctx context.Context, priorities []int64) ([]int64, error)

	// GetDelayedCount returns how many delayed jobs are due strictly before
	// before (Unix milliseconds).
	GetDelayedCount(ctx context.Context, before int64) (int64, error)

	// GetQueueMeta returns every field of the queue metadata hash, or an
	// empty map when there is none.
	GetQueueMeta(ctx context.Context) (map[string]string, error)

	// TrimEvents trims the event stream to about maxLength events and
	// returns how many it removed. A backend that can't returns an error
	// wrapping ErrNotSupported.
	TrimEvents(ctx context.Context, maxLength int64) (int64, error)

	// PublishEvent appends an event called event with fields (besides the
	// `event` field) to the event stream, trimmed to about maxEvents where
	// the backend trims on add, and returns its id.
	PublishEvent(ctx context.Context, event string, fields map[string]string, maxEvents int64) (string, error)
}

Backend is the datastore-agnostic contract describing every high-level operation that Queue, Worker, QueueEvents and Job need in order to function. It is the Go counterpart of the `IQueueBackend` interface of the Node.js implementation (src/interfaces/queue-backend.ts) and keeps the same operation names and semantics.

The interface expresses the queue semantics ("move job to active", "extend lock", "promote job", ...) independently of the underlying store. The Redis implementation lives in the redisbackend subpackage; other datastores are plugged in through a BackendFactory without any change to Queue, Worker, QueueEvents or Job. This package never imports a datastore driver.

Rules for implementations:

  • Methods use only exported domain types. Datastore specifics (Lua scripts, key names, SQL, msgpack encoding, reply parsing) stay private to the implementation.
  • A backend owns its connection(s). Callers never thread a connection or a transaction through an operation.
  • Operations that fail because of queue semantics return the sentinel errors of this package (for example ErrJobNotFound or ErrJobLockNotExist), directly or wrapped in a ScriptError whose Code is one of the ErrCode constants (-1 to -11), whatever the datastore reports natively. The shared PostgreSQL commands raise SQLSTATE BM001 with the same code in the detail.
  • All methods must be safe for concurrent use.
  • Times are Unix milliseconds and durations have millisecond precision, as in every other BullMQ port.

Fetching jobs follows Node's protocol. Backend.MoveToActive moves the next job to active and locks it with a token chosen by the worker. When no job can be fetched, the FetchResult says why, so the worker knows how long it may sleep. A worker finishing a job can ask for the next one in the same operation (FinishOptions.FetchNext), which saves a round trip per job; the next job is then locked with the same token. Between fetches an idle worker blocks in Backend.WaitForJob.

type BackendFactory

type BackendFactory func(name string, opts BackendOptions) (Backend, error)

BackendFactory builds a Backend for the queue called name. It is injected through the required Backend field of QueueOptions, WorkerOptions and QueueEventsOptions, for example with redisbackend.New. The queue name has already been validated when the factory is called.

type BackendOptions

type BackendOptions struct {
	// WithBlockingConnection requests a connection dedicated to WaitForJob and
	// ReadEvents, so a blocked read never starves other operations.
	WithBlockingConnection bool
	// ClientNameSuffix is appended to the base client name of the dedicated
	// blocking connection, for example ":w:<worker>" or ":qe".
	ClientNameSuffix string
	// BlockTimeout is the longest blocking read the owner will request. It
	// lets the backend size socket read timeouts.
	BlockTimeout time.Duration
	// QueueMeta holds queue metadata fields the backend writes, as
	// SetQueueMeta does, once, before the first command it sends. A write
	// that fails is not retried, unless it failed because its context was
	// done or with a transient error. Obliterate and Close stop any later
	// write, so the metadata never comes back after an Obliterate. Queue
	// sets it unless QueueOptions.SkipMetasUpdate is set.
	QueueMeta map[string]any
}

BackendOptions describes the role of the backend being built by a BackendFactory. Datastore settings such as addresses, credentials or a Redis key prefix belong to the options of the backend package itself.

type Backoff

type Backoff struct {
	// Type is the strategy name. Custom strategy names are forwarded to the
	// worker's WorkerOptions.BackoffStrategy callback.
	Type BackoffType `json:"type"`
	// Delay is the base delay, in milliseconds (an int64, not a
	// time.Duration).
	Delay int64 `json:"delay,omitempty"`
	// Jitter is the fraction (0 to 1) of the delay that is randomized: the
	// effective delay is drawn uniformly from [delay*(1-Jitter), delay),
	// excluding delay itself, and rounded down to whole milliseconds. 0 (the
	// default) disables jitter. Applies to the fixed and exponential
	// strategies.
	Jitter float64 `json:"jitter,omitempty"`
}

Backoff configures the retry delay of a job.

type BackoffType

type BackoffType string

BackoffType selects the delay curve used between retries.

const (
	BackoffFixed       BackoffType = "fixed"
	BackoffExponential BackoffType = "exponential"
)

Supported backoff strategies.

type ConfigError

type ConfigError struct {
	Message string
}

ConfigError signals invalid user supplied configuration.

func (*ConfigError) Error

func (e *ConfigError) Error() string

type DeduplicationOptions

type DeduplicationOptions struct {
	// ID is the deduplication id.
	ID string `json:"id"`
	// TTL is how long the id is held, in milliseconds (an int64, not a
	// time.Duration). When it is 0, the id is held until the job completes
	// or fails for good.
	TTL int64 `json:"ttl,omitempty"`
	// Extend refreshes the TTL when a duplicate is discarded.
	Extend bool `json:"extend,omitempty"`
	// Replace discards the existing job in favour of the new one, while the
	// existing job is still delayed.
	Replace bool `json:"replace,omitempty"`
	// Reschedule moves the existing job, while it is still delayed, to the
	// new job's delay counted from the new job's timestamp (no delay makes
	// it due now). The existing job keeps its id and data, and a `delayed`
	// event is emitted. It is independent of Extend, and ignored when
	// Replace is set.
	Reschedule bool `json:"reschedule,omitempty"`
	// KeepLastIfActive keeps the data of the last job added while the
	// existing job is active: when that job completes or fails, a new job
	// is added with it, so at most one job runs and one waits per id. TTL
	// is then ignored: the id is held until the jobs finish. It can't be
	// used on a flow node with a parent.
	KeepLastIfActive bool `json:"keepLastIfActive,omitempty"`
}

DeduplicationOptions prevents duplicate jobs from being added while a job holds the deduplication id, as Node's deduplication option does.

Adding a job whose id another job holds adds nothing: Queue.Add returns a Job with the ID of the job that holds it (and the data and options of the call), and QueueEvents reports a `deduplicated` event. As in Node, Add does not say whether it deduplicated the job; use the event, or compare the returned ID with JobOptions.JobID when you set one. Queue.DeduplicationJobID reports the job that holds an id, and Queue.RemoveDeduplicationKey and Job.RemoveDeduplicationKey release it early.

type Dependencies

type Dependencies struct {
	// Processed maps the key of every completed child to its return value
	// (JSON).
	Processed map[string]json.RawMessage
	// Unprocessed lists the keys of the children that have not finished.
	Unprocessed []string
	// Ignored maps the key of every child whose failure was ignored
	// (IgnoreDependencyOnFailure or ContinueParentOnFailure) to its failure
	// reason.
	Ignored map[string]string
	// Failed lists the keys of the children that failed with
	// FailParentOnFailure.
	Failed []string

	NextProcessedCursor   uint64
	NextUnprocessedCursor uint64
	NextIgnoredCursor     uint64
	NextFailedCursor      uint64
}

Dependencies are the children of a parent job grouped by status. Children are identified by their key, `{QualifiedName}:{id}` (for example `bull:emails:42` on Redis and `emails:42` on PostgreSQL), which works across queues.

A group that was not requested is nil. A next cursor is 0 once the last page of its group was returned.

type DependenciesOptions

type DependenciesOptions struct {
	// Processed pages through the completed children.
	Processed *DependencyPage
	// Unprocessed pages through the children that have not finished yet.
	Unprocessed *DependencyPage
	// Ignored pages through the children whose failure was ignored.
	Ignored *DependencyPage
	// Failed pages through the children that failed their parent.
	Failed *DependencyPage
}

DependenciesOptions selects the children returned by Job.Dependencies: only the groups whose page is set are returned, one page each.

type DependencyCounts

type DependencyCounts struct {
	Processed   int64
	Unprocessed int64
	Ignored     int64
	Failed      int64
}

DependencyCounts is the number of children of a parent job in each status (see Dependencies).

type DependencyPage

type DependencyPage struct {
	// Cursor is where the page starts: 0 for the first page, then the next
	// cursor reported with the previous page.
	Cursor uint64
	// Count is how many children to return. Defaults to 20. On Redis it is
	// a hint for the processed, unprocessed and ignored groups, as the COUNT
	// of HSCAN and SSCAN: the children of a small group are all returned.
	Count int64
}

DependencyPage requests a page of a group of children.

type Event

type Event struct {
	// Type is the kind of event.
	Type EventType
	// Job is the job the event refers to; nil for EventDrained, EventError,
	// EventClosed, EventPaused, EventResumed and the lock events. For EventStalled only ID and
	// QueueName are set, since the stalled check reports job ids; load the
	// job with Queue.Job (or Job.State) if needed.
	Job *Job
	// JobIDs lists the jobs of EventLockRenewalFailed and EventLocksRenewed.
	JobIDs []string
	// Result is the processor return value for EventCompleted, or the new
	// Progress value for EventProgress.
	Result any
	// Err carries the failure for EventFailed and EventError.
	Err error
}

Event is emitted by a Worker through Worker.Events.

type EventType

type EventType string

EventType identifies a worker lifecycle event.

const (
	EventActive    EventType = "active"
	EventCompleted EventType = "completed"
	EventFailed    EventType = "failed"
	EventProgress  EventType = "progress"
	// EventStalled reports a job that the stalled check of this worker
	// moved back to wait (or failed) because its lock had expired. Only the
	// ID and QueueName of its Event.Job are set.
	EventStalled EventType = "stalled"
	// EventLockRenewalFailed lists, in Event.JobIDs, the jobs of this worker
	// whose lock could not be renewed. Their contexts are cancelled with
	// ErrLockLost, since another worker may own them now; Node.js only
	// reports them.
	EventLockRenewalFailed EventType = "lockRenewalFailed"
	// EventLocksRenewed lists, in Event.JobIDs, the jobs whose locks were
	// renewed.
	EventLocksRenewed EventType = "locksRenewed"
	EventDrained      EventType = "drained"
	EventError        EventType = "error"
	EventClosed       EventType = "closed"
	// EventPaused is emitted by the Pause that paused the worker once it
	// returns, as Node emits paused once pause has waited for the jobs in
	// flight (whose EventCompleted or EventFailed may follow it); not when
	// the worker was resumed or closed meanwhile.
	EventPaused EventType = "paused"
	// EventResumed is emitted by Resume when the worker was paused.
	EventResumed EventType = "resumed"
)

Worker event types.

type FailureInfo

type FailureInfo struct {
	// Reason is the failure message.
	Reason string
	// Stacktrace holds the (already trimmed) failure traces to persist.
	Stacktrace []string
}

FailureInfo describes why an attempt failed.

type FetchResult

type FetchResult struct {
	// Job is the job that was moved to active, or nil when none was fetched.
	Job *JobRecord
	// RateLimitDelay is how long the queue stays rate limited when Job is nil
	// because of the rate limit.
	RateLimitDelay time.Duration
	// NextDelayedAt is when the next delayed job is due (Unix milliseconds)
	// when Job is nil; 0 means none, or unknown.
	NextDelayedAt int64
}

FetchResult is the outcome of fetching a job, with Backend.MoveToActive or as the next job of a finishing operation. It mirrors the `[jobData, id, rateLimitDelay, delayUntil]` tuple of the other ports.

When Job is nil, the other fields say why no job was fetched:

  • RateLimitDelay > 0: the queue is rate limited for that long, and no job may be fetched before it lifts.
  • NextDelayedAt > 0: nothing is ready, but a delayed job is due then.
  • both zero: the queue is empty, paused or at its global concurrency limit.

type FinishOptions

type FinishOptions struct {
	// Token is the lock token held on the job. The next job, when fetched,
	// is locked with the same token.
	Token string
	// JobOpts are the options of the job being finished.
	JobOpts *JobOptions
	// KeepJobs is the effective removal policy for the target state.
	KeepJobs *RemoveOnFinish
	// LockDuration is the worker lock duration.
	LockDuration time.Duration
	// WorkerName is the name of the worker.
	WorkerName string
	// Limiter is the worker rate limiter.
	Limiter *RateLimiter
	// Metrics enables metrics collection.
	Metrics *MetricsOptions
	// FetchNext fetches the next job in the same operation, as MoveToActive
	// would with Token, LockDuration, WorkerName and Limiter.
	FetchNext bool
}

FinishOptions carries the settings needed to move a job to a finished state and, optionally, to fetch the next one.

type FinishResult

type FinishResult struct {
	// FinishedOn is the recorded finishedOn timestamp (Unix milliseconds).
	FinishedOn int64
	// Next is the outcome of fetching the next job. It is nil when
	// [FinishOptions.FetchNext] was not set, so callers can tell "not
	// requested" from "nothing to fetch" (a non-nil result with a nil Job).
	Next *FetchResult
}

FinishResult is the outcome of Backend.MoveToCompleted and Backend.MoveToFailed.

type FlowEntry

type FlowEntry struct {
	// QueueName is the queue the job is added to.
	QueueName string
	// JobID is the id the job is stored under: its custom id, or one the
	// FlowProducer generated, since children must know their parent's id
	// before it is stored. Job.Opts.JobID only holds a custom id, which is
	// what the other ports store in the job options.
	JobID string
	// Job is the validated job.
	Job NewJob
	// WaitingChildren adds the job in the waiting-children state: it is a
	// parent, and its children follow it in the entries.
	WaitingChildren bool
}

FlowEntry is a job of a flow handed to Backend.AddFlow.

type FlowGetOptions

type FlowGetOptions struct {
	// ID is the id of the root job.
	ID string
	// QueueName is the queue of the root job.
	QueueName string
	// Depth is how many levels of the tree are returned, the root included.
	// Defaults to 10.
	Depth int
	// MaxChildren is how many children of each status (processed,
	// unprocessed, failed, ignored) are returned per job. Defaults to 20. On
	// Redis it is a hint, like the COUNT of HSCAN: the children of a small
	// group are all returned.
	MaxChildren int64
}

FlowGetOptions selects the flow returned by FlowProducer.GetFlow.

type FlowJob

type FlowJob struct {
	// Name is the job name handed to the processor.
	Name string
	// QueueName is the queue the job is added to.
	QueueName string
	// Data is the payload; it is marshalled to JSON. nil is stored as {}, as
	// Node stores a job added without data.
	Data any
	// Opts are the job options. Opts.Parent is only honoured on the root of
	// a flow, to add the whole flow under an existing job; the other nodes
	// are children of their parent node. Deduplication is only allowed on a
	// root without children nor parent.
	Opts *JobOptions
	// Children are the jobs this job waits for.
	Children []FlowJob
}

FlowJob is a node of a flow: a job and the children it waits for. A node with children is added in the waiting-children state and processed once all of them are, with their results available through Job.ChildrenValues. Children may belong to other queues.

type FlowOpts

type FlowOpts struct {
	// QueuesOptions holds options for the nodes of a queue, by queue name.
	QueuesOptions map[string]FlowQueueOptions
}

FlowOpts tunes FlowProducer.Add.

type FlowProducer

type FlowProducer struct {
	// contains filtered or unexported fields
}

FlowProducer adds flows: trees of jobs, possibly spanning several queues, in which a parent is processed only once its children are, as Node's FlowProducer does.

A FlowProducer is safe for concurrent use.

func NewFlowProducer

func NewFlowProducer(opts *FlowProducerOptions) (*FlowProducer, error)

NewFlowProducer creates a flow producer.

func (*FlowProducer) Add

func (fp *FlowProducer) Add(ctx context.Context, flow FlowJob, opts *FlowOpts) (*JobNode, error)

Add adds a flow and returns its jobs. Children are processed before their parents; a parent sees their results with Job.ChildrenValues.

The whole tree is sent in one datastore operation (a Redis transaction, a database transaction on PostgreSQL). When the datastore rejects one of its jobs, for example because the parent of the root does not exist (ErrParentJobNotExist: then no job is added) or because a child with a custom id already belongs to another parent (ErrParentJobCannotBeReplaced), Add returns an error. PostgreSQL then rolls the whole tree back; on Redis, as in Node, the jobs the datastore accepted are kept.

func (*FlowProducer) AddBulk

func (fp *FlowProducer) AddBulk(ctx context.Context, flows []FlowJob) ([]*JobNode, error)

AddBulk adds several flows in one datastore operation and returns their jobs, in order. Errors are reported as in FlowProducer.Add: when the datastore rejects a job, AddBulk returns an error; PostgreSQL then adds no job of any of the flows, while Redis keeps the jobs it accepted.

func (*FlowProducer) Backend

func (fp *FlowProducer) Backend() Backend

Backend returns the datastore backend of the producer, which reaches every queue of its flows. Type-assert it to the concrete backend, for example *redisbackend.Backend, to reach datastore-specific features.

func (*FlowProducer) Close

func (fp *FlowProducer) Close() error

Close releases the connections of the flow producer. The jobs it returned can no longer reach the datastore afterwards.

func (*FlowProducer) GetFlow

func (fp *FlowProducer) GetFlow(ctx context.Context, opts FlowGetOptions) (*JobNode, error)

GetFlow returns the tree of jobs rooted at a job: the job and, level by level, the children it has in any status. It returns nil when the job does not exist. Children that no longer exist are left out.

type FlowProducerOptions

type FlowProducerOptions struct {
	// Backend builds the datastore backend, for example
	// redisbackend.New(redisbackend.Options{Addr: "127.0.0.1:6379"}). It is
	// required. Every queue of a flow is reached through the backend it
	// builds, so the queues of a flow share its connections and its namespace
	// (the Redis key prefix or the PostgreSQL schema).
	Backend BackendFactory
}

FlowProducerOptions configures a FlowProducer.

type FlowQueueOptions

type FlowQueueOptions struct {
	// DefaultJobOptions are merged into the options of the queue's nodes, as
	// QueueOptions.DefaultJobOptions are into the jobs of a Queue.
	DefaultJobOptions *JobOptions
}

FlowQueueOptions are applied to every node of a flow that belongs to one queue.

type Job

type Job struct {
	// ID is the job id.
	ID string
	// Name is the job name.
	Name string
	// Data is the JSON encoded payload. On PostgreSQL, which stores it as
	// jsonb, a job read back from the datastore holds an equal JSON value
	// but not necessarily the same bytes (whitespace and key order may
	// differ), so decode it rather than compare bytes.
	Data json.RawMessage
	// Opts are the options the job was created with.
	Opts *JobOptions
	// Progress is the last reported progress value.
	Progress Progress
	// AttemptsMade is how many times the job has finished an attempt.
	AttemptsMade int64
	// AttemptsStarted is how many times the job has been moved to active.
	AttemptsStarted int64
	// Timestamp is the creation time in Unix milliseconds.
	Timestamp int64
	// ProcessedOn is when the job was last moved to active, in Unix milliseconds.
	ProcessedOn int64
	// FinishedOn is when the job completed or failed, in Unix milliseconds.
	FinishedOn int64
	// FailedReason is the error message of the last failure.
	FailedReason string
	// DeferredFailure is set by the stalled-check script when the job
	// exceeded MaxStalledCount; when non-empty the job must be failed
	// unrecoverably instead of being handed to the processor.
	DeferredFailure string
	// Stacktrace holds the recorded failure traces.
	Stacktrace []string
	// ReturnValue is the JSON encoded value returned by the processor. On
	// PostgreSQL it is re-encoded as Data is: equal as JSON, possibly with
	// different bytes.
	ReturnValue json.RawMessage
	// ParentKey is the key of the parent job, if any.
	ParentKey string
	// Parent identifies the parent job, if any.
	Parent *ParentKeys
	// ProcessedBy is the name of the worker that last processed the job.
	ProcessedBy string
	// StalledCounter is how many times the job has been detected as stalled.
	StalledCounter int64
	// Delay is the configured delay, in milliseconds (ChangeDelay takes a
	// time.Duration).
	Delay int64
	// Priority is the configured priority.
	Priority int64
	// RepeatJobKey links the job to a job scheduler.
	RepeatJobKey string
	// DeduplicationID is the deduplication id the job was added with (see
	// JobOptions.Deduplication), or "".
	DeduplicationID string
	// QueueName is the name of the owning queue.
	QueueName string
	// contains filtered or unexported fields
}

Job is a unit of work stored in a queue.

Values returned by Queue and Worker methods carry a live Backend, so mutating methods such as UpdateProgress or Log can be called on them.

func (*Job) ChangeDelay

func (j *Job) ChangeDelay(ctx context.Context, delay time.Duration) error

ChangeDelay makes a job that is in the delayed set due after delay, counted from now. delay is a time.Duration, used with millisecond precision, unlike JobOptions.Delay and Job.Delay, which are milliseconds: pass 4*time.Second, not 4000.

func (*Job) ChangePriority

func (j *Job) ChangePriority(ctx context.Context, priority int64, lifo bool) error

ChangePriority updates the priority of a waiting or prioritized job.

func (*Job) ChildrenValues

func (j *Job) ChildrenValues(ctx context.Context) (map[string]json.RawMessage, error)

ChildrenValues returns the return value (JSON) of every completed child of the job, by child key (see Dependencies), as Node's getChildrenValues.

func (*Job) DecodeChildrenValues

func (j *Job) DecodeChildrenValues(ctx context.Context, out any) error

DecodeChildrenValues decodes the return values of the completed children of the job into out, a pointer to a map from child key to the type of the values, as DecodeData decodes the job's data:

var costs map[string]float64
if err := job.DecodeChildrenValues(ctx, &costs); err != nil {
	return nil, err
}

func (*Job) DecodeData

func (j *Job) DecodeData(out any) error

DecodeData unmarshals the job payload into out.

func (*Job) DecodeReturnValue

func (j *Job) DecodeReturnValue(out any) error

DecodeReturnValue unmarshals the processor result into out.

func (*Job) Dependencies

func (j *Job) Dependencies(ctx context.Context, opts *DependenciesOptions) (*Dependencies, error)

Dependencies returns the children of the job grouped by status. With nil opts every group is returned in full; otherwise only the requested groups, one page each.

func (*Job) DependenciesCount

func (j *Job) DependenciesCount(ctx context.Context) (DependencyCounts, error)

DependenciesCount returns how many children of the job are in each status.

func (*Job) Discard

func (j *Job) Discard()

Discard marks the job so that it is not retried when the processor fails.

func (*Job) Discarded

func (j *Job) Discarded() bool

Discarded reports whether Discard was called.

func (*Job) ExtendLock

func (j *Job) ExtendLock(ctx context.Context, duration time.Duration) error

ExtendLock refreshes the lock held on an active job, so it expires duration (a time.Duration, used with millisecond precision) from now.

func (*Job) FailedChildrenValues deprecated

func (j *Job) FailedChildrenValues(ctx context.Context) (map[string]string, error)

FailedChildrenValues returns the same as Job.IgnoredChildrenFailures.

Deprecated: use Job.IgnoredChildrenFailures; Node deprecated getFailedChildrenValues too.

func (*Job) IgnoredChildrenFailures

func (j *Job) IgnoredChildrenFailures(ctx context.Context) (map[string]string, error)

IgnoredChildrenFailures returns the failure reason of every child whose failure was ignored, with IgnoreDependencyOnFailure or ContinueParentOnFailure, by child key.

func (*Job) IsCompleted

func (j *Job) IsCompleted(ctx context.Context) (bool, error)

IsCompleted reports whether the job finished successfully.

func (*Job) IsFailed

func (j *Job) IsFailed(ctx context.Context) (bool, error)

IsFailed reports whether the job finished with an error.

func (*Job) Log

func (j *Job) Log(ctx context.Context, message string) (int64, error)

Log appends a row to the job log and returns the total number of rows kept.

func (*Job) Logs

func (j *Job) Logs(ctx context.Context, start, end int64) ([]string, int64, error)

Logs returns the log rows of the job together with the total count.

func (*Job) MoveToCompleted

func (j *Job) MoveToCompleted(ctx context.Context, result any, token string, fetchNext bool) (*Job, error)

MoveToCompleted completes a job fetched with Worker.GetNextJob and locked with token, recording result (encoded as JSON) as its return value, as Node's job.moveToCompleted does. The worker's settings apply: the removal policy, the metrics and, for the next job, the lock duration and limiter.

With fetchNext, the next job is fetched in the same datastore call and locked with the same token, as GetNextJob(ctx, token, false) would; it is returned, or nil when there is none (or the worker is paused or closed). It fails when the job's lock is gone or held by another token, for example because the job stalled.

Processors don't call it: the worker completes their jobs.

func (*Job) MoveToDelayed

func (j *Job) MoveToDelayed(ctx context.Context, delay time.Duration) error

MoveToDelayed reschedules an active job to run after delay, a time.Duration counted from now and used with millisecond precision (Node's moveToDelayed takes the due timestamp instead). Processors should return ErrDelayed afterwards so the worker does not also move the job to a finished state.

The current attempt is not counted, matching the Node.js implementation.

func (*Job) MoveToFailed

func (j *Job) MoveToFailed(ctx context.Context, cause error, token string, fetchNext bool) (*Job, error)

MoveToFailed records a failed attempt of a job fetched with Worker.GetNextJob and locked with token, with cause as its failure, as Node's job.moveToFailed does. As when a processor fails, the job is retried, after its backoff, while attempts remain, unless cause is unrecoverable (see NewUnrecoverableError) or the job was discarded; otherwise it fails for good.

With fetchNext, the next job is fetched in the same datastore call, as in MoveToCompleted, and returned. A job retried right away is not, so fetch it with GetNextJob. It fails when the job's lock is gone or held by another token.

func (*Job) MoveToWait

func (j *Job) MoveToWait(ctx context.Context) error

MoveToWait puts the active job back in the wait list (or the prioritized set, keeping its priority) without counting an attempt, and releases its lock, as Node's job.moveToWait does. A processor must then return ErrWaiting, so the worker does not also finish the job. It fails when the job's lock is gone or held by another token.

func (*Job) MoveToWaitingChildren

func (j *Job) MoveToWaitingChildren(ctx context.Context, child *ParentKeys) (bool, error)

MoveToWaitingChildren parks an active parent job until its children finish. It returns true when the job was moved and false when there were no pending dependencies. Processors should return ErrWaitingChildren when true.

child identifies the job whose completion is being awaited. Its QueueKey must be the fully qualified queue name (see Backend.QualifiedName) of the queue the child belongs to, which may differ from the parent's own queue. Pass nil if there is no specific child to check for.

func (*Job) Promote

func (j *Job) Promote(ctx context.Context) error

Promote moves a delayed job to the wait list immediately.

func (*Job) Remove

func (j *Job) Remove(ctx context.Context, removeChildren bool) error

Remove deletes the job and all of its data. Active jobs cannot be removed.

func (*Job) RemoveChildDependency

func (j *Job) RemoveChildDependency(ctx context.Context) (bool, error)

RemoveChildDependency detaches the job, which must not have finished yet, from its parent, so the parent no longer waits for it; a parent left without pending children is moved to wait. It returns false when the job was not a pending child of its parent. As in Node.js, it returns an error matching ErrParentJobNotExist when the job has no parent, or its parent no longer exists. On success the job's Parent and ParentKey are cleared.

func (*Job) RemoveDeduplicationKey

func (j *Job) RemoveDeduplicationKey(ctx context.Context) (bool, error)

RemoveDeduplicationKey releases the job's deduplication id if the job still holds it, so the next job added with it is not deduplicated, as Node's job.removeDeduplicationKey does. It reports whether it did: false when the job has no deduplication id, or when the id expired or is held by another job.

func (*Job) RemoveUnprocessedChildren

func (j *Job) RemoveUnprocessedChildren(ctx context.Context) error

RemoveUnprocessedChildren removes, recursively, the children of the job that have not been processed yet: active, completed and failed children, and locked ones, are kept. It can be slow with many children.

func (*Job) Retry

func (j *Job) Retry(ctx context.Context, state JobState, opts *RetryOptions) error

Retry moves a completed or failed job back to the wait list (or to the prioritized set when it has a priority). opts may be nil.

state must be either StateCompleted or StateFailed. Unless opts resets them, the attempt counters are kept: a job that used up its attempts fails for good after its next failure.

func (*Job) State

func (j *Job) State(ctx context.Context) (JobState, error)

State returns the current state of the job.

func (*Job) Token

func (j *Job) Token() string

Token returns the lock token held by the worker currently processing the job.

func (*Job) UpdateData

func (j *Job) UpdateData(ctx context.Context, data any) error

UpdateData replaces the job payload.

func (*Job) UpdateProgress

func (j *Job) UpdateProgress(ctx context.Context, progress any) error

UpdateProgress stores a new progress value and emits a `progress` event on the owning Worker, mirroring how a per-job update is observed through Worker.Events.

progress is a number, or any value encoded as JSON, as Node's updateProgress takes a number or an object; a Progress is stored as is. NaN and infinite numbers, which have no JSON encoding, are rejected.

type JobCounts

type JobCounts map[JobState]int64

JobCounts holds the number of jobs per state.

type JobLock

type JobLock struct {
	JobID string
	Token string
}

JobLock identifies the lock held on an active job.

type JobNode

type JobNode struct {
	Job      *Job
	Children []*JobNode
}

JobNode is a job of a flow with its children.

type JobOptions

type JobOptions struct {
	// JobID overrides the automatically generated job id.
	JobID string `json:"jobId,omitempty"`
	// Delay is how long before the job becomes available, in milliseconds
	// (an int64, not a time.Duration: use time.Minute.Milliseconds(), for
	// example), as every port stores it. A pointer so a per-job value of 0
	// can be told apart from "not set", letting it override a non-zero
	// queue default back to 0.
	Delay *int64 `json:"delay,omitempty"`
	// Priority; lower values are processed first. 0 means unprioritized and
	// the maximum is 2^21-1 (2097151). A
	// pointer so a per-job value of 0 can be told apart from "not set",
	// letting it override a non-zero queue default back to 0.
	Priority *int64 `json:"priority,omitempty"`
	// LIFO pushes the job to the front of the wait list. A pointer so an
	// explicit `false` can override a queue default of `true`.
	LIFO *bool `json:"lifo,omitempty"`
	// Attempts is the total number of times the job may be tried. A pointer
	// so a per-job value of 0 can override a non-zero queue default.
	Attempts *int64 `json:"attempts,omitempty"`
	// Backoff configures the delay between retries.
	Backoff *Backoff `json:"backoff,omitempty"`
	// RemoveOnComplete controls automatic removal of completed jobs.
	RemoveOnComplete *RemoveOnFinish `json:"removeOnComplete,omitempty"`
	// RemoveOnFail controls automatic removal of failed jobs.
	RemoveOnFail *RemoveOnFinish `json:"removeOnFail,omitempty"`
	// KeepLogs limits how many log rows are retained per job. A pointer so a
	// per-job value of 0 can override a non-zero queue default.
	KeepLogs *int64 `json:"kl,omitempty"`
	// SizeLimit rejects jobs whose serialized data exceeds this many bytes. A
	// pointer so a per-job value of 0 can override a non-zero queue default.
	SizeLimit *int64 `json:"sizeLimit,omitempty"`
	// StackTraceLimit caps how many failure traces are kept on the job: the
	// most recent ones. 0 keeps none; unset keeps them all, as in Node.js.
	StackTraceLimit *int64 `json:"stackTraceLimit,omitempty"`
	// Timestamp is the creation time in Unix milliseconds. Defaults to now.
	Timestamp int64 `json:"timestamp,omitempty"`

	// Parent links this job to a parent job.
	Parent *ParentOptions `json:"parent,omitempty"`
	// Deduplication prevents duplicates while the key is alive.
	Deduplication *DeduplicationOptions `json:"de,omitempty"`

	// FailParentOnFailure fails the parent when this job fails. A pointer so
	// an explicit `false` can override a queue default of `true`.
	FailParentOnFailure *bool `json:"fpof,omitempty"`
	// ContinueParentOnFailure unblocks the parent when this job fails. A
	// pointer so an explicit `false` can override a queue default of `true`.
	ContinueParentOnFailure *bool `json:"cpof,omitempty"`
	// IgnoreDependencyOnFailure removes this job from the parent's
	// dependencies when it fails, without failing the parent. A pointer so
	// an explicit `false` can override a queue default of `true`.
	IgnoreDependencyOnFailure *bool `json:"idof,omitempty"`
	// RemoveDependencyOnFailure removes the dependency when this job fails. A
	// pointer so an explicit `false` can override a queue default of `true`.
	RemoveDependencyOnFailure *bool `json:"rdof,omitempty"`

	// Repeat, PrevMillis and RepeatJobKey are set by job schedulers on the
	// jobs they produce: the schedule with the iteration count, the due time
	// of the iteration (Unix milliseconds) and the scheduler id. Repeat
	// cannot be set when adding a job; use Queue.UpsertJobScheduler.
	Repeat       *RepeatOptions `json:"repeat,omitempty"`
	PrevMillis   int64          `json:"prevMillis,omitempty"`
	RepeatJobKey string         `json:"repeatJobKey,omitempty"`
}

JobOptions configures a single job.

The JSON tags mirror the field names persisted by the shared Lua and SQL commands, so options round-trip across all BullMQ language ports.

func (*JobOptions) UnmarshalJSON

func (opts *JobOptions) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes stored job options. A removal policy stored in a form no BullMQ port writes is dropped, so the worker default applies.

type JobRecord

type JobRecord struct {
	ID              string
	Name            string
	Data            json.RawMessage
	Opts            *JobOptions
	Progress        Progress
	ReturnValue     json.RawMessage
	Stacktrace      []string
	ParentKey       string
	Parent          *ParentKeys
	ProcessedBy     string
	RepeatJobKey    string
	DeduplicationID string
	FailedReason    string
	DeferredFailure string
	Timestamp       int64
	AttemptsMade    int64
	AttemptsStarted int64
	ProcessedOn     int64
	FinishedOn      int64
	StalledCounter  int64
	Priority        int64
	Delay           int64
}

JobRecord is the stored representation of a job returned by a Backend.

type JobScheduler

type JobScheduler struct {
	// ID is the scheduler id (Node's `key`).
	ID string
	// Name is the name of the jobs it produces.
	Name string
	// IterationCount is how many jobs it has produced.
	IterationCount int64
	Limit          int64
	StartDate      int64
	EndDate        int64
	Tz             string
	Pattern        string
	Every          int64
	Offset         int64
	// Next is when its next job is due.
	Next int64
	// Template holds the data and options of the jobs it produces, or nil
	// when it stores neither.
	Template *JobSchedulerTemplate
}

JobScheduler describes a stored job scheduler, as returned by Queue.JobScheduler and Queue.JobSchedulers. It mirrors Node's JobSchedulerJson; times are Unix milliseconds and zero values mean unset.

type JobSchedulerNext

type JobSchedulerNext struct {
	ID   string
	Next int64
}

JobSchedulerNext is a scheduler id with the due time of its next job, as listed by Backend.GetJobSchedulersRange.

type JobSchedulerTemplate

type JobSchedulerTemplate struct {
	// Data is the JSON payload, or nil when none is stored.
	Data json.RawMessage
	// Opts are the job options, or nil when none are stored.
	Opts *JobOptions
}

JobSchedulerTemplate is the stored template of a job scheduler.

type JobSpec

type JobSpec struct {
	// Name is the job name handed to the processor.
	Name string
	// Data is the payload; it is marshalled to JSON. nil is stored as {}, as
	// Node stores a job added without data.
	Data any
	// Opts overrides the queue default job options.
	Opts *JobOptions
}

JobSpec describes a job to add through Add or AddBulk.

type JobState

type JobState string

JobState is the lifecycle state of a job.

const (
	StateWaiting         JobState = "waiting"
	StateActive          JobState = "active"
	StateDelayed         JobState = "delayed"
	StatePrioritized     JobState = "prioritized"
	StateCompleted       JobState = "completed"
	StateFailed          JobState = "failed"
	StateWaitingChildren JobState = "waiting-children"
	StateUnknown         JobState = "unknown"
)

Job states, matching the values returned by the shared `getState` command.

const StatePaused JobState = "paused"

StatePaused designates the paused list of older BullMQ versions, as Node's "paused" job type does. Jobs of a paused queue stay waiting, and Queue.Resume moves any job left in that list back to wait. It is accepted by Clean, JobCounts and JobIDs but is never the state of a job. On PostgreSQL, which has no paused list, JobCounts and JobIDs report it empty, while Clean treats it as StateWaiting, as the shared SQL does.

type JobTemplate

type JobTemplate struct {
	// Name is the name of every job. It defaults to the scheduler id.
	Name string
	// Data is the payload of every job; it is marshalled to JSON. Nil
	// means an empty object.
	Data any
	// Opts are the options of every job, merged over the queue's default
	// job options. JobID, Delay, Deduplication and Repeat cannot be set.
	Opts *JobOptions
}

JobTemplate describes the jobs a job scheduler produces.

type Metrics

type Metrics struct {
	// Count is the total number of jobs recorded.
	Count int64
	// PrevCount is the job count at the last time a data point was recorded.
	// It is internal metrics state used to compute the next data point's
	// delta, not a retention boundary.
	PrevCount int64
	// PrevTS is the timestamp (Unix milliseconds) of the transition that last
	// recorded a data point, i.e. the previous collection timestamp. It is
	// internal metrics state, not the timestamp of the oldest retained data
	// point, so do not use it as the retention boundary.
	PrevTS int64
	// Data holds one entry per minute, most recent first: the number of
	// jobs recorded in that minute. Entries are added when a job is
	// recorded in a later minute than the previous entry, so Data stays
	// empty during the first minute of collection, as in Node.js.
	Data []int64
	// NumPoints is the total number of retained data points, regardless of
	// the requested [start, end] window. Use it for pagination (the reference
	// getMetrics API returns it as `count`).
	NumPoints int64
}

Metrics is the result of Queue.Metrics.

type MetricsOptions

type MetricsOptions struct {
	// MaxDataPoints is the number of one-minute data points to retain.
	MaxDataPoints int64
}

MetricsOptions enables the collection of completed/failed counters.

type MoveToActiveOptions

type MoveToActiveOptions struct {
	// Token is the lock token to acquire.
	Token string
	// LockDuration is how long the lock is held.
	LockDuration time.Duration
	// WorkerName is stored on the job as the processing worker.
	WorkerName string
	// Limiter throttles how many jobs may be fetched per window.
	Limiter *RateLimiter
}

MoveToActiveOptions are the worker settings needed to fetch a job.

type MoveToDelayedOptions

type MoveToDelayedOptions struct {
	// SkipAttempt keeps the attempts counter untouched.
	SkipAttempt bool
	// Failure is recorded on the job when the delay is a retry backoff.
	Failure *FailureInfo
	// FetchNext fetches the next job in the same operation, as MoveToActive
	// would with the job's token and the settings below.
	FetchNext bool
	// LockDuration is how long the next job's lock is held.
	LockDuration time.Duration
	// WorkerName is stored on the next job as the processing worker.
	WorkerName string
	// Limiter throttles fetching the next job.
	Limiter *RateLimiter
}

MoveToDelayedOptions tunes Backend.MoveToDelayed.

type NewJob

type NewJob struct {
	// Name is the job name handed to the processor.
	Name string
	// Data is the JSON encoded payload.
	Data []byte
	// Opts are the effective job options.
	Opts *JobOptions
}

NewJob is a validated job ready to be stored by a Backend. Opts is a private copy with defaults merged and Timestamp set.

type NewJobScheduler

type NewJobScheduler struct {
	// ID identifies the scheduler.
	ID string
	// NextMillis is when the next iteration is due (Unix milliseconds). It
	// is ignored for Every schedulers, whose next iteration the backend
	// computes from Every, Offset and StartDate as the shared commands do.
	NextMillis int64
	// Name is the name of the jobs the scheduler produces.
	Name string
	// The schedule; zero values are not stored. Offset is only set for
	// Every schedulers.
	Pattern   string
	Every     int64
	Tz        string
	Limit     int64
	Offset    int64
	StartDate int64
	EndDate   int64
	// TemplateData is the JSON payload of every job.
	TemplateData []byte
	// TemplateOpts are the options of every job.
	TemplateOpts *JobOptions
	// JobOpts are the options of the job of the next iteration.
	JobOpts *JobOptions
	// ProducerID is the job that produced this iteration, if any.
	ProducerID string
}

NewJobScheduler is a job scheduler to store with Backend.AddJobScheduler, with the options of the job of its next iteration. It mirrors the arguments of Node's addJobScheduler.

type ObliterateOptions

type ObliterateOptions struct {
	// Force obliterates the queue even while some of its jobs are active.
	Force bool
	// Count is how many jobs are removed per datastore call, so that a
	// large queue doesn't block the datastore; it is not a cap on the
	// total. 0 means 1000.
	Count int64
}

ObliterateOptions tunes Queue.Obliterate, as Node's obliterate options do.

type ParentKeys

type ParentKeys struct {
	// ID is the parent job id.
	ID string `json:"id"`
	// QueueKey is the qualified name of the parent's queue (see
	// [Backend.QualifiedName]): `{prefix}:{queueName}` on Redis, the bare
	// queue name on PostgreSQL.
	QueueKey string `json:"queueKey"`
}

ParentKeys identifies the parent of a job as persisted by the backend.

type ParentOptions

type ParentOptions struct {
	// ID is the parent job id.
	ID string `json:"id"`
	// Queue is the parent queue. Either a bare queue name or a fully
	// qualified `{prefix}:{queueName}` key.
	Queue string `json:"queue"`
}

ParentOptions links a job to a parent job, possibly in another queue.

type Processor

type Processor func(ctx context.Context, job *Job) (any, error)

Processor handles a single job. The returned value is JSON encoded and stored as the job's return value.

Returning an error fails the job; if attempts remain the job is retried using the configured backoff. Return an error created with NewUnrecoverableError to fail without retrying.

ctx is cancelled when the context passed to Worker.Run is, when the worker loses the job's lock (ErrLockLost), and by Worker.CancelJob (ErrJobCancelled); context.Cause tells which. An error returned after the worker itself cancelled ctx (Run or the lock) is not recorded: the job is left active, without using up an attempt, for the stalled check to recover. After CancelJob the job fails with the error the processor returns, as in Node.js, and with the cancellation reason when that error is ctx.Err() itself.

Once ctx is cancelled, the job's methods called with it (UpdateProgress, Log, ...) fail with ctx's error. Cleanup that must still reach the datastore uses context.WithoutCancel(ctx).

type Progress

type Progress struct {
	// contains filtered or unexported fields
}

Progress is a job progress value: either a number or an arbitrary JSON value.

func JSONProgress

func JSONProgress(v any) (Progress, error)

JSONProgress builds a structured progress value. Job.UpdateProgress also takes the value itself.

func NumberProgress

func NumberProgress(v float64) (Progress, error)

NumberProgress builds a numeric progress value. It returns an error for NaN and infinite values, which have no JSON representation.

func (Progress) Decode

func (p Progress) Decode(out any) error

Decode unmarshals a structured progress value into out.

func (Progress) MarshalJSON

func (p Progress) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Progress) Number

func (p Progress) Number() (float64, bool)

Number returns the progress as a float. It reports false when the progress is not a plain number.

func (Progress) Raw

func (p Progress) Raw() string

Raw returns the JSON encoding of the progress value.

func (*Progress) UnmarshalJSON

func (p *Progress) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Queue

type Queue struct {
	// contains filtered or unexported fields
}

Queue adds jobs to a BullMQ queue and inspects its contents.

A Queue only depends on the Backend abstraction, so it works with any datastore for which a backend exists.

A Queue is safe for concurrent use.

func NewQueue

func NewQueue(name string, opts *QueueOptions) (*Queue, error)

NewQueue creates a queue named name. It does not reach the datastore: the queue writes its metadata (see QueueOptions.SkipMetasUpdate) before its first command.

func (*Queue) Add

func (q *Queue) Add(ctx context.Context, name string, data any, opts *JobOptions) (*Job, error)

Add inserts a single job into the queue. data is marshalled to JSON, and nil is stored as {}, as Node stores a job added without data. When the job is deduplicated (see DeduplicationOptions), nothing is added and the returned Job has the ID of the job that holds the deduplication id.

func (*Queue) AddBulk

func (q *Queue) AddBulk(ctx context.Context, specs []JobSpec) ([]*Job, error)

AddBulk inserts every job in one backend operation. On PostgreSQL that is a database transaction: a failed batch adds no job. On Redis it is a single transaction, but Redis does not roll back the scripts that ran when another returns an application-level error, such as a missing parent, so a failed batch may leave the other jobs added.

func (*Queue) Backend

func (q *Queue) Backend() Backend

Backend returns the datastore backend used by the queue. Type-assert it to the concrete backend, for example *redisbackend.Backend, to reach datastore-specific features such as the underlying client.

func (*Queue) Clean

func (q *Queue) Clean(ctx context.Context, grace time.Duration, limit int64, state JobState) ([]string, error)

Clean removes finished (or waiting/delayed) jobs older than grace.

state must be one of StateWaiting, StateActive, StatePaused, StatePrioritized, StateDelayed, StateCompleted or StateFailed ("wait" is accepted for StateWaiting, as in Node). A limit of 0 means unlimited. Removal runs in batches of at most 10,000 jobs, repeating until limit jobs were removed or a batch comes back short, so a large state never blocks the datastore in a single call. It returns the removed job ids.

func (*Queue) Close

func (q *Queue) Close() error

Close releases the connections the queue owns.

func (*Queue) Count

func (q *Queue) Count(ctx context.Context) (int64, error)

Count returns the number of waiting, delayed, prioritized, and waiting-children jobs.

func (*Queue) CountsPerPriority

func (q *Queue) CountsPerPriority(ctx context.Context, priorities ...int64) (map[int64]int64, error)

CountsPerPriority returns how many waiting jobs have each of priorities, as Node's getCountsPerPriority does: 0 counts the waiting jobs without a priority. Repeated priorities are counted once, and an empty list returns an empty map.

func (*Queue) DeduplicationJobID

func (q *Queue) DeduplicationJobID(ctx context.Context, dedupID string) (string, error)

DeduplicationJobID returns the id of the job that holds the deduplication id dedupID (see DeduplicationOptions), or "" when no job holds it: it was never used, was removed, or its TTL expired. While a job holds it, adding a job with the same deduplication id returns that job's id.

func (*Queue) DelayedCount

func (q *Queue) DelayedCount(ctx context.Context, before time.Time) (int64, error)

DelayedCount returns how many delayed jobs are due strictly before before, as Node's getDelayedCount(timestamp) does, for example to count the overdue ones with time.Now(). The zero time counts every delayed job.

func (*Queue) Drain

func (q *Queue) Drain(ctx context.Context, delayed bool) error

Drain removes all waiting and prioritized jobs. Active, completed and failed jobs are left untouched. When delayed is true, delayed jobs are removed too.

func (*Queue) GlobalConcurrency

func (q *Queue) GlobalConcurrency(ctx context.Context) (*int64, error)

GlobalConcurrency returns the global concurrency limit, or nil when none is set, as Node's getGlobalConcurrency returns null. It may be 0 when another port stored it (see SetGlobalConcurrency): no job is then fetched, and IsMaxed reports true.

func (*Queue) GlobalRateLimit

func (q *Queue) GlobalRateLimit(ctx context.Context) (*RateLimiter, error)

GlobalRateLimit returns the global rate limit, or nil when none is set.

func (*Queue) IsMaxed

func (q *Queue) IsMaxed(ctx context.Context) (bool, error)

IsMaxed reports whether the queue reached its global concurrency limit.

func (*Queue) IsPaused

func (q *Queue) IsPaused(ctx context.Context) (bool, error)

IsPaused reports whether the queue is paused.

func (*Queue) Job

func (q *Queue) Job(ctx context.Context, jobID string) (*Job, error)

Job fetches a job by id. It returns nil when the job does not exist.

func (*Queue) JobCounts

func (q *Queue) JobCounts(ctx context.Context, states ...JobState) (JobCounts, error)

JobCounts returns the number of jobs in each of the requested states. When no state is given every state in AllStates is returned.

func (*Queue) JobIDs

func (q *Queue) JobIDs(ctx context.Context, start, end int64, asc bool, states ...JobState) ([]string, error)

JobIDs returns the ids of the jobs in the given states, as Node's getRanges does: for each state, in order, the jobs at positions start to end (inclusive; a negative end counts from the last one) of that state, so the range applies to every state on its own. A job listed twice is returned once. With no state, every state in AllStates is listed.

asc selects the order within each state. Node's shortcuts use asc=true for waiting, active, delayed, prioritized and waiting-children jobs (oldest or first due first: getWaiting, getActive, getDelayed, getPrioritized, getWaitingChildren) and asc=false for completed and failed jobs (most recent first: getCompleted, getFailed), and getJobs defaults to false.

func (*Queue) JobScheduler

func (q *Queue) JobScheduler(ctx context.Context, id string) (*JobScheduler, error)

JobScheduler returns the job scheduler id, or nil when it does not exist.

func (*Queue) JobSchedulers

func (q *Queue) JobSchedulers(ctx context.Context, start, end int64, asc bool) ([]*JobScheduler, error)

JobSchedulers returns the job schedulers ranked start to end (inclusive; -1 is the last one) by the due time of their next job, latest first unless asc is set.

func (*Queue) JobSchedulersCount

func (q *Queue) JobSchedulersCount(ctx context.Context) (int64, error)

JobSchedulersCount returns the number of job schedulers.

func (*Queue) JobState

func (q *Queue) JobState(ctx context.Context, jobID string) (JobState, error)

JobState returns the state of a job.

func (*Queue) Jobs

func (q *Queue) Jobs(ctx context.Context, start, end int64, asc bool, states ...JobState) ([]*Job, error)

Jobs returns the jobs in the given states, selected and ordered as by JobIDs, as Node's getJobs does. For example, the 10 most recent failures:

jobs, err := queue.Jobs(ctx, 0, 9, false, bullmq.StateFailed)

func (*Queue) Meta

func (q *Queue) Meta(ctx context.Context) (*QueueMeta, error)

Meta returns the queue's metadata, as Node's getMeta does.

func (*Queue) Metrics

func (q *Queue) Metrics(ctx context.Context, state JobState, start, end int64) (*Metrics, error)

Metrics returns the collected metrics for the completed or failed state.

func (*Queue) Name

func (q *Queue) Name() string

Name returns the queue name.

func (*Queue) Obliterate

func (q *Queue) Obliterate(ctx context.Context, opts *ObliterateOptions) error

Obliterate deletes the queue and every job in it, with its metadata, whatever their state. opts may be nil.

The queue is paused first, matching the behaviour of the other ports. Unless opts.Force is set, the call fails if there are still active jobs.

func (*Queue) Pause

func (q *Queue) Pause(ctx context.Context) error

Pause stops workers from picking up new jobs. Jobs already active keep running.

func (*Queue) PromoteJobs

func (q *Queue) PromoteJobs(ctx context.Context, count int64) error

PromoteJobs moves every delayed job to the wait list right away, in batches of count jobs (one datastore call each; 0 means 1000), as Node's promoteJobs does.

func (*Queue) RateLimitTTL

func (q *Queue) RateLimitTTL(ctx context.Context, maxJobs int64) (int64, error)

RateLimitTTL returns how long, in milliseconds, the queue stays rate limited, as Node's getRateLimitTtl does.

maxJobs is the number of jobs per window that makes the queue rate limited: RateLimitTTL returns the time left in the current window once at least maxJobs jobs were counted in it, and 0 otherwise. A maxJobs of 0, like Node's omitted argument, uses the Max of the global rate limit (see SetGlobalRateLimit). Without a global rate limit either, it returns the time left in the current window whatever its count, or the codes of Redis PTTL: -2 when no window is open, and -1 when the window never expires.

func (*Queue) Remove

func (q *Queue) Remove(ctx context.Context, jobID string, removeChildren bool) (bool, error)

Remove deletes the job jobID and all of its data, as Node's queue.remove does, without reading it first. With removeChildren, its children are removed too, recursively. It returns false, removing nothing, when the job or one of the children to remove is locked by a worker (Job.Remove reports that as ErrJobLocked); a job that does not exist counts as removed. The current job of a job scheduler can't be removed this way (ErrJobBelongsToJobScheduler); remove the scheduler instead.

func (*Queue) RemoveDeduplicationKey

func (q *Queue) RemoveDeduplicationKey(ctx context.Context, dedupID string) (bool, error)

RemoveDeduplicationKey releases the deduplication id dedupID, whichever job holds it, so the next job added with it is not deduplicated. It reports whether there was one to release. Job.RemoveDeduplicationKey releases it only if a given job still holds it.

func (*Queue) RemoveGlobalConcurrency

func (q *Queue) RemoveGlobalConcurrency(ctx context.Context) error

RemoveGlobalConcurrency removes the global concurrency limit.

func (*Queue) RemoveGlobalRateLimit

func (q *Queue) RemoveGlobalRateLimit(ctx context.Context) error

RemoveGlobalRateLimit removes the global rate limit: workers are then only limited by their own Limiter.

func (*Queue) RemoveJobScheduler

func (q *Queue) RemoveJobScheduler(ctx context.Context, id string) (bool, error)

RemoveJobScheduler removes the job scheduler id and the job of its next iteration while that job is still delayed, as in Node.js: an iteration job already waiting (such as the first job of an Every scheduler, or a due job that was promoted) or being processed is kept, and runs once more. It reports whether the scheduler existed.

func (*Queue) Resume

func (q *Queue) Resume(ctx context.Context) error

Resume lets workers pick up jobs again.

func (*Queue) RetryJobs

func (q *Queue) RetryJobs(ctx context.Context, opts *RetryJobsOptions) error

RetryJobs moves every failed (or completed) job back to the wait list, in batches, as Node's retryJobs does. opts may be nil. Their attempt counters are kept on Redis but reset on PostgreSQL, as the shared commands do.

func (*Queue) SetGlobalConcurrency

func (q *Queue) SetGlobalConcurrency(ctx context.Context, max int64) error

SetGlobalConcurrency limits how many jobs may be active across all workers. A value of 0 (or less) removes the limit, as RemoveGlobalConcurrency does. Unlike Go, Node's setGlobalConcurrency(0) stores 0, which stops every worker: the queue is then always maxed.

func (*Queue) SetGlobalRateLimit

func (q *Queue) SetGlobalRateLimit(ctx context.Context, max int64, duration time.Duration) error

SetGlobalRateLimit throttles every worker of this queue to at most max jobs per duration. For a worker that also has a Limiter, this max and the Limiter's Duration apply, as in Node.js. A max of 0 removes the limit, as RemoveGlobalRateLimit does.

func (*Queue) TrimEvents

func (q *Queue) TrimEvents(ctx context.Context, maxLength int64) (int64, error)

TrimEvents trims the queue's event stream to about maxLength events, as Node's trimEvents does, and returns how many it removed. Redis trims approximately (XTRIM MAXLEN ~), so a few more events may be left. The PostgreSQL backend can't (an error wrapping ErrNotSupported, as Node's throws): it trims the stream to QueueOptions.EventsMaxLen as it adds events.

func (*Queue) UpsertJobScheduler

func (q *Queue) UpsertJobScheduler(ctx context.Context, id string, repeat RepeatOptions, template *JobTemplate) (*Job, error)

UpsertJobScheduler creates the job scheduler id, or replaces its schedule and template, and adds the job of its next iteration, which it returns. The scheduler then keeps producing jobs: each time a worker fetches one, it adds the job of the following iteration. The jobs have the id `repeat:<id>:<due time in Unix milliseconds>`.

It returns nil, without error, when the schedule produces no job: its limit is reached, or no time matching Pattern is left before EndDate (or QueueOptions.RepeatStrategy returned 0).

func (*Queue) Version

func (q *Queue) Version(ctx context.Context) (string, error)

Version returns the BullMQ version of the scripts of the library that last wrote the queue's metadata, as `bullmq:<version>` (Go writes `bullmq:<ScriptsVersion>`), or "" when none did, as Node's getVersion does.

func (*Queue) Workers

func (q *Queue) Workers(ctx context.Context) ([]WorkerInfo, error)

Workers lists the workers connected to this queue, as Node's getWorkers does. Workers are found by the name of their dedicated connection, in CLIENT LIST on Redis and in pg_stat_activity on PostgreSQL. PostgreSQL stores each non-ASCII byte of a connection name as a 4-byte `\xhh` escape (a `?` before version 16, which loses the worker name's non-ASCII characters) and truncates the result to 63 bytes, so there the workers of a queue with a long name may be missing, and long worker names are truncated. Those escapes are decoded, so a worker name that itself contains `\x` followed by two hex digits of 80-ff (such as `w\xc3\xb6`) is listed decoded (`wö`): PostgreSQL stores both names the same way.

type QueueEvent

type QueueEvent struct {
	// ID is the opaque, backend-specific id of the event: a stream entry id
	// such as `1700000000000-0` on Redis, a number such as `42` on
	// PostgreSQL. Ids increase with every event; pass one as
	// QueueEventsOptions.LastEventID to resume reading after that event.
	ID string
	// Event is the event name, for example `added`, `active`, `completed`,
	// `failed`, `progress`, `delayed`, `waiting`, `stalled`, `removed`,
	// `paused`, `resumed` or `drained`.
	Event string
	// JobID is the job the event refers to, when applicable.
	JobID string
	// Data holds every field of the event, including `event` and `jobId`.
	Data map[string]string
}

QueueEvent is a single event of the queue's event stream.

func (QueueEvent) DecodeProgress

func (e QueueEvent) DecodeProgress(out any) error

DecodeProgress decodes the progress value of a `progress` event into out.

func (QueueEvent) DecodeReturnValue

func (e QueueEvent) DecodeReturnValue(out any) error

DecodeReturnValue decodes the JSON return value of a `completed` event into out, as Job.DecodeReturnValue does. It does nothing when the event has none.

func (QueueEvent) DelayedUntil

func (e QueueEvent) DelayedUntil() (t time.Time, ok bool)

DelayedUntil returns when the job of a `delayed` event becomes due: its delay field, which holds Unix milliseconds rather than a duration, as in Node.js. ok is false when the event has no such field.

func (QueueEvent) FailedReason

func (e QueueEvent) FailedReason() string

FailedReason returns the error message of a `failed` event.

func (QueueEvent) Progress

func (e QueueEvent) Progress() (Progress, error)

Progress returns the progress value of a `progress` event: a number or any JSON value, read with Progress.Number or Progress.Decode.

func (QueueEvent) ReturnValue

func (e QueueEvent) ReturnValue() string

ReturnValue returns the serialized processor result of a `completed` event.

type QueueEvents

type QueueEvents struct {
	// contains filtered or unexported fields
}

QueueEvents streams the global events emitted by a queue, allowing a process that does not run the worker to observe job progress.

func NewQueueEvents

func NewQueueEvents(queueName string, opts *QueueEventsOptions) (*QueueEvents, error)

NewQueueEvents creates an event listener for the given queue.

func (*QueueEvents) Backend

func (qe *QueueEvents) Backend() Backend

Backend returns the datastore backend of the listener. Type-assert it to the concrete backend, for example *redisbackend.Backend, to reach datastore-specific features such as its dedicated blocking client.

func (*QueueEvents) Close

func (qe *QueueEvents) Close() error

Close stops the listener and releases the connection when it owns it.

func (*QueueEvents) Errors

func (qe *QueueEvents) Errors() <-chan error

Errors returns the channel carrying non-fatal read errors. It is closed when the listener stops, after the last error has been sent.

func (*QueueEvents) Events

func (qe *QueueEvents) Events() <-chan QueueEvent

Events returns the channel on which stream entries are delivered. It is closed when the listener stops.

func (*QueueEvents) Run

func (qe *QueueEvents) Run(ctx context.Context) error

Run reads the event stream and delivers its events on the Events channel until it stops, then closes the Events and Errors channels.

  • After Close it returns nil.
  • When ctx is done it returns ctx's error.
  • Read errors are sent on the Errors channel and retried a second later, but an error reading the id of the newest event at startup (for the default LastEventID `$`) is returned.
  • It returns ErrQueueEventsClosed straight away when Run was already called or the listener is closed.

Call Close after Run returns because ctx was done, to release the listener's connection.

type QueueEventsOptions

type QueueEventsOptions struct {
	// Backend builds the datastore backend. It is required.
	Backend BackendFactory
	// LastEventID is the id of the event to start reading after: a
	// [QueueEvent.ID], `0-0` (or `0`) to read every stored event, or `$`,
	// the default, to read only the events produced once the listener
	// starts.
	LastEventID string
	// BlockingTimeout is the longest a single read of the event stream waits
	// for new events before reading again (XREAD BLOCK on Redis, a LISTEN
	// wait on PostgreSQL). Defaults to 5s.
	BlockingTimeout time.Duration
	// BufferSize is the size of the delivery channel. Defaults to 128.
	BufferSize int
}

QueueEventsOptions configures a QueueEvents listener.

type QueueEventsProducer

type QueueEventsProducer struct {
	// contains filtered or unexported fields
}

QueueEventsProducer publishes custom events on a queue's event stream, as Node's QueueEventsProducer does. The QueueEvents of every runtime receive them like the events of jobs: QueueEvent.Event is the event's name and QueueEvent.Data holds its fields.

A QueueEventsProducer is safe for concurrent use.

func NewQueueEventsProducer

func NewQueueEventsProducer(name string, opts *QueueEventsProducerOptions) (*QueueEventsProducer, error)

NewQueueEventsProducer creates a producer of custom events for the queue called name.

func (*QueueEventsProducer) Backend

func (p *QueueEventsProducer) Backend() Backend

Backend returns the datastore backend of the producer.

func (*QueueEventsProducer) Close

func (p *QueueEventsProducer) Close() error

Close releases the connections the producer owns.

func (*QueueEventsProducer) PublishEvent

func (p *QueueEventsProducer) PublishEvent(ctx context.Context, eventName string, fields map[string]any, maxEvents int64) (string, error)

PublishEvent appends an event called eventName to the event stream, with fields, and returns its id, as Node's publishEvent({eventName, ...fields}, maxEvents) does. String values are stored as they are, and other values as their JSON encoding; a field can't be called "event", which holds the name. On Redis the stream is trimmed to about maxEvents events (0 means DefaultMaxEvents); PostgreSQL trims it to the queue's EventsMaxLen instead. Don't use the names of the events of jobs (completed, failed, ...), which listeners would take for them.

type QueueEventsProducerOptions

type QueueEventsProducerOptions struct {
	// Backend builds the datastore backend. It is required.
	Backend BackendFactory
}

QueueEventsProducerOptions configures a QueueEventsProducer.

type QueueMeta

type QueueMeta struct {
	// Concurrency is the global concurrency limit (SetGlobalConcurrency). A
	// stored 0, which another runtime may write, holds every job.
	Concurrency *int64
	// Max is the number of jobs allowed per Duration by the global rate
	// limit (SetGlobalRateLimit).
	Max *int64
	// Duration is the window of the global rate limit.
	Duration *time.Duration
	// MaxLenEvents is the approximate maximum length of the events stream.
	MaxLenEvents *int64
	// Paused reports whether the queue is paused.
	Paused bool
	// Version is the BullMQ version of the scripts of the library that last
	// wrote the queue's metadata, as `bullmq:<version>` (Go writes
	// `bullmq:<ScriptsVersion>`), or "" when none did.
	Version string
}

QueueMeta is the queue's metadata, as Node's Queue.getMeta returns it. A numeric field is nil when it is not set.

type QueueOptions

type QueueOptions struct {
	// Backend builds the datastore backend, for example
	// redisbackend.New(redisbackend.Options{Addr: "127.0.0.1:6379"}). It is
	// required.
	Backend BackendFactory
	// DefaultJobOptions are merged into every job added to this queue.
	DefaultJobOptions *JobOptions
	// EventsMaxLen is the approximate maximum length of the queue's events
	// stream, stored as the `opts.maxLenEvents` metadata, as Node's
	// streams.events.maxLen. Defaults to 10000.
	EventsMaxLen int64
	// SkipMetasUpdate stops the queue from writing its metadata (version
	// and opts.maxLenEvents), for example for a role that may only read.
	SkipMetasUpdate bool
	// RepeatStrategy, when set, computes the due times of the Pattern job
	// schedulers this queue upserts, instead of cron (see [RepeatStrategy]).
	// Set the same one on the workers.
	RepeatStrategy RepeatStrategy
}

QueueOptions configures a Queue.

type RateLimiter

type RateLimiter struct {
	// Max is the maximum number of jobs per Duration.
	Max int64
	// Duration is the rate limit window. It is stored with millisecond
	// precision, so sub-millisecond values are rounded down.
	Duration time.Duration
}

RateLimiter throttles how many jobs a worker may process per time window.

type RemoveOnFinish

type RemoveOnFinish struct {
	// Count keeps at most Count finished jobs. A value of 0 removes the job
	// straight away.
	Count *int64 `json:"count,omitempty"`
	// Age keeps finished jobs younger than Age, in seconds (not
	// milliseconds), as in every port.
	Age *int64 `json:"age,omitempty"`
	// Limit caps how many jobs a single cleanup pass may remove.
	Limit *int64 `json:"limit,omitempty"`
	// contains filtered or unexported fields
}

RemoveOnFinish controls the automatic removal of completed or failed jobs.

Use RemoveAll, KeepCount or KeepAge to construct a value, or set Count, Age and Limit directly; the zero value keeps every finished job. It is stored in the three forms the other BullMQ ports write: a boolean (RemoveAll is stored as true), a count (KeepCount), or a {count, age, limit} object.

func KeepAge

func KeepAge(seconds int64) *RemoveOnFinish

KeepAge keeps finished jobs younger than seconds, in seconds (not milliseconds): KeepAge(24 * 60 * 60) keeps a day.

func KeepCount

func KeepCount(n int64) *RemoveOnFinish

KeepCount keeps at most n finished jobs. It is stored as the number n, as the other ports store `removeOnComplete: n`.

func RemoveAll

func RemoveAll() *RemoveOnFinish

RemoveAll removes jobs as soon as they finish. It is stored as true, as the other ports store `removeOnComplete: true`.

func (*RemoveOnFinish) IsRemoveAll

func (r *RemoveOnFinish) IsRemoveAll() bool

IsRemoveAll reports whether r is the boolean form true (RemoveAll): each job is removed as soon as it finishes, without trimming the other finished jobs. Backends that tell "remove this job" from "keep no finished job" apart (the shared PostgreSQL commands do) must check it rather than Count.

func (RemoveOnFinish) MarshalJSON

func (r RemoveOnFinish) MarshalJSON() ([]byte, error)

MarshalJSON writes r in the form it was built or read in: true or false, a count, or an object. A count whose Age or Limit was set afterwards is written as an object, so they are kept.

func (*RemoveOnFinish) UnmarshalJSON

func (r *RemoveOnFinish) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts the boolean, numeric and object forms written by the other BullMQ ports. Fractional counts are rounded away from zero, so they keep their meaning (a positive count stays positive, a negative one keeps every job), fractional ages are rounded up and negative ages are ignored. Any other value is ignored, as if the option were not set.

type RepeatOptions

type RepeatOptions struct {
	// Pattern is a cron expression with 5 fields, or 6 with leading seconds,
	// evaluated like cron-parser does in Node.js, in time zone Tz.
	Pattern string `json:"pattern,omitempty"`
	// Every repeats the job every this many milliseconds.
	Every int64 `json:"every,omitempty"`
	// Limit is the maximum number of jobs the scheduler produces. 0 means no
	// limit.
	Limit int64 `json:"limit,omitempty"`
	// Immediately makes a Pattern scheduler produce its first job right away
	// instead of at the first time matching the pattern. Every schedulers
	// always produce their first job right away (or at StartDate).
	Immediately bool `json:"immediately,omitempty"`
	// Offset shifts the runs of an Every scheduler, in milliseconds.
	Offset int64 `json:"offset,omitempty"`
	// StartDate is when the schedule starts, in Unix milliseconds. 0 means
	// now.
	StartDate int64 `json:"startDate,omitempty"`
	// EndDate is when the schedule ends, in Unix milliseconds. 0 means
	// never.
	EndDate int64 `json:"endDate,omitempty"`
	// Tz is the time zone Pattern is evaluated in, as Node.js resolves it:
	// an IANA name in any case, an ICU legacy id such as "PST", or a fixed
	// offset such as "+03:00" or "UTC+3". Empty means the local time zone
	// of the process, as in Node.js. Time zones are read from the system's
	// time zone database; programs running where there is none can embed
	// one with `import _ "time/tzdata"`.
	Tz string `json:"tz,omitempty"`
	// Count is the iteration of the job it is stored in. It is maintained
	// by the scheduler and ignored by Queue.UpsertJobScheduler.
	Count int64 `json:"count,omitempty"`
}

RepeatOptions describe the schedule of a job scheduler, as Node's RepeatOptions do. Exactly one of Pattern and Every must be set. Every, Offset, StartDate and EndDate are int64 milliseconds (dates are Unix milliseconds: use time.Time.UnixMilli), not time.Duration or time.Time.

The JSON form is the one every BullMQ port stores in the options of the jobs a scheduler produces (`opts.repeat`), with times in Unix milliseconds.

func (*RepeatOptions) UnmarshalJSON

func (r *RepeatOptions) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes repeat options written by any BullMQ port, accepting numbers written as floats or strings, and dates written as ISO 8601 strings.

type RepeatStrategy

type RepeatStrategy func(millis int64, opts RepeatOptions, jobName string) (int64, error)

RepeatStrategy computes when the next job of a Pattern scheduler is due, instead of evaluating Pattern as a cron expression, as Node's settings.repeatStrategy does. It is set on QueueOptions and WorkerOptions, and every queue and worker that schedules the iterations of a scheduler needs the same one, whatever its language.

millis is the time to compute the next run after (Unix milliseconds), opts the scheduler's repeat options, whose Count is the number of jobs produced so far, and jobName the name of its jobs. It returns when the next job is due (Unix milliseconds; a time in the past means now), or 0 when there is no next run, as Node's strategy returns undefined. Pattern can then be any string the strategy understands, such as an RRULE.

type RetryJobsOptions

type RetryJobsOptions struct {
	// State is the state of the jobs to retry: StateFailed (the default) or
	// StateCompleted.
	State JobState
	// Count is how many jobs are moved per batch, one datastore call each,
	// not a cap on the total; 0 means 1000.
	Count int64
	// Before only retries the jobs that finished at or before it; the zero
	// time means now.
	Before time.Time
}

RetryJobsOptions tunes Queue.RetryJobs, as the options of Node's retryJobs do.

type RetryOptions

type RetryOptions struct {
	// ResetAttemptsMade sets the job's attempts-made counter back to 0, so
	// it gets every attempt of JobOptions.Attempts again.
	ResetAttemptsMade bool
	// ResetAttemptsStarted sets the job's attempts-started counter back to
	// 0, which WorkerOptions.MaxStartedAttempts checks.
	ResetAttemptsStarted bool
}

RetryOptions tunes Job.Retry, as Node's RetryOptions does.

type ScriptError

type ScriptError struct {
	Code   int64
	Script string
}

ScriptError wraps a negative status code returned by a backend command: a Lua command on Redis, or a shared SQL command on PostgreSQL, which raises SQLSTATE BM001 with the same code. Script names the command. Code is one of the ErrCode constants, and errors.Is matches the corresponding sentinel error (for example ErrJobNotFound for ErrCodeJobNotExist).

func (*ScriptError) Error

func (e *ScriptError) Error() string

func (*ScriptError) Unwrap

func (e *ScriptError) Unwrap() error

type StalledOptions

type StalledOptions struct {
	// MaxStalledCount is how many times a job may stall before failing.
	MaxStalledCount int
	// Interval is the stalled check interval.
	Interval time.Duration
}

StalledOptions configures Backend.MoveStalledJobsToWait.

type UnrecoverableError

type UnrecoverableError struct {
	Message string
}

UnrecoverableError makes a job fail immediately without consuming further attempts.

func (*UnrecoverableError) Error

func (e *UnrecoverableError) Error() string

type WaitResult

type WaitResult struct {
	// Woken is true when the wait ended because the queue signalled work,
	// and false when it timed out. Signals may be spurious.
	Woken bool
	// NextDelayedAt is when the next delayed job is due (Unix milliseconds),
	// when the signal says so; 0 means a job may be ready now, or unknown.
	NextDelayedAt int64
}

WaitResult is the outcome of Backend.WaitForJob.

type Worker

type Worker struct {
	// contains filtered or unexported fields
}

Worker fetches jobs from a queue and hands them to a Processor.

Every processing slot finishes its job and fetches the next one in the same backend call (fetch-next), as the Node.js worker does, so a busy worker needs about one round trip per job whatever its concurrency. The fetch loop only fetches to fill free slots, and blocks on the backend only once the queue looks drained.

func NewWorker

func NewWorker(queueName string, proc Processor, opts *WorkerOptions) (*Worker, error)

NewWorker creates a worker for the given queue. Call Run to start processing.

A worker created with a nil proc processes nothing by itself: its jobs are fetched with GetNextJob and finished with Job.MoveToCompleted or Job.MoveToFailed, as in Node's manual mode (see GetNextJob).

func (*Worker) ActiveCount

func (w *Worker) ActiveCount() int

ActiveCount returns how many jobs are currently being processed.

func (*Worker) Backend

func (w *Worker) Backend() Backend

Backend returns the datastore backend of the worker. Type-assert it to the concrete backend, for example *redisbackend.Backend, to reach datastore-specific features such as its dedicated blocking client.

func (*Worker) CancelAllJobs

func (w *Worker) CancelAllJobs(reason string)

CancelAllJobs cancels every job this worker is processing, as CancelJob does.

func (*Worker) CancelJob

func (w *Worker) CancelJob(jobID, reason string) bool

CancelJob cancels the context of a job this worker is processing, with a cause (see context.Cause) that matches ErrJobCancelled and reads as reason. When the processor then returns an error, the job fails with it (and is retried if attempts remain), as Node.js's cancelJob records what the processor throws; a bare ctx.Err() fails it with reason. To keep the reason in an error of your own, wrap context.Cause(ctx). A processor that returns no error completes the job. It reports whether the job was being processed.

func (*Worker) Close

func (w *Worker) Close() error

Close stops the worker and waits for in-flight jobs to finish. It is safe to call more than once and from several goroutines; every call returns the same result.

func (*Worker) Concurrency

func (w *Worker) Concurrency() int

Concurrency returns how many jobs the worker processes in parallel: WorkerOptions.Concurrency, or the value of the last SetConcurrency.

func (*Worker) DroppedEvents

func (w *Worker) DroppedEvents() uint64

DroppedEvents returns how many events could not be delivered on the Events channel because its buffer was full.

func (*Worker) Events

func (w *Worker) Events() <-chan Event

Events returns the channel on which lifecycle events are published. It is closed by Close.

The channel is buffered; events are dropped when the consumer falls behind, so a worker never blocks on event delivery. DroppedEvents counts them. Use WorkerOptions.OnEvent to observe every event.

func (*Worker) GetNextJob

func (w *Worker) GetNextJob(ctx context.Context, token string, block bool) (*Job, error)

GetNextJob fetches the next job of a worker without a processor and locks it with token, as Node's worker.getNextJob does. It returns nil when no job can be fetched: the queue is empty, paused, rate limited or at its global concurrency limit, or the worker is paused. When block is set and the queue is empty, it waits for a job for up to DrainDelay, fetching again whenever the queue signals one or a delayed job is due, or until ctx is done or the worker is closed.

The job is locked for LockDuration and its lock is not renewed: finish it with Job.MoveToCompleted or Job.MoveToFailed, with the same token, before the lock expires, or extend the lock with Job.ExtendLock. A job whose lock expires is moved back to wait by the stalled check of any worker (see StartStalledCheck), and its token no longer finishes it.

As in Node.js, it emits EventActive for the job and, for the job of a job scheduler, first adds the job of the scheduler's next iteration. Jobs fetched by hand don't count for Pause and ActiveCount. GetNextJob may be called concurrently; calls that block wait in turn. It returns ErrWorkerClosed once the worker is closed.

func (*Worker) ID

func (w *Worker) ID() string

ID returns the unique id of this worker instance.

func (*Worker) IsPaused

func (w *Worker) IsPaused() bool

IsPaused reports whether the worker is paused.

func (*Worker) Name

func (w *Worker) Name() string

Name returns the worker name, falling back to its generated id.

func (*Worker) Pause

func (w *Worker) Pause(ctx context.Context, doNotWaitActive bool) error

Pause stops this worker from starting new jobs, as Node's pause does. Unless doNotWaitActive is set, it then waits until the jobs being processed have finished, or until ctx is done (returning ctx's error), the worker is resumed, or it is closed (returning ErrWorkerClosed). The Pause that paused the worker then emits EventPaused, unless the worker was resumed or closed meanwhile. A paused worker keeps checking for stalled jobs, unlike Node's.

It may be called from WorkerOptions.OnEvent: from EventDrained, or from the EventCompleted or EventFailed of a job, it waits for the other jobs only. A processor pausing its own worker, or a callback for an event emitted while its job runs (EventActive, EventProgress), must set doNotWaitActive, since Pause would otherwise wait for that job.

func (*Worker) RateLimit

func (w *Worker) RateLimit(ctx context.Context, d time.Duration) error

RateLimit rate limits the whole queue for d, as Node's rateLimit does: until it expires, workers that fetch with a limiter (WorkerOptions.Limiter or a global rate limit) get no job. A processor typically calls it and then returns ErrRateLimited, which puts its job back in the wait list.

func (*Worker) Resume

func (w *Worker) Resume()

Resume restarts fetching jobs after Pause, and emits EventResumed when the worker was paused.

func (*Worker) Run

func (w *Worker) Run(ctx context.Context) error

Run starts the worker and blocks until it stops.

  • After Close it stops fetching, waits for the jobs being processed to finish, and returns nil.
  • When ctx is done it stops fetching and cancels the context of the jobs being processed, which are left active for the stalled check to recover (see Processor). Once their processors have returned, it returns ctx's error, even if Close was also called.
  • It returns ErrWorkerClosed straight away when Run was already called or the worker is closed, and a ConfigError for a worker without a processor.

Call Close after Run returns because ctx was done, to release the worker's connections.

func (*Worker) SetConcurrency

func (w *Worker) SetConcurrency(n int) error

SetConcurrency changes how many jobs the worker processes in parallel while it runs, as setting Node's worker.concurrency does. Raising it fetches jobs for the new slots right away. Lowering it lets the jobs in flight finish: a slot finishing a job fetches no next job while more slots than n are in use. n must be at least 1.

func (*Worker) StartStalledCheck

func (w *Worker) StartStalledCheck() error

StartStalledCheck starts the stalled check of a worker without a processor, as Node's startStalledCheckTimer does: right away and then every StalledInterval until the worker is closed, it moves the active jobs whose lock expired back to wait, or fails those that stalled more than MaxStalledCount times, and reports them with EventStalled. Calling it again does nothing, nor does it when SkipStalledCheck is set. A worker with a processor checks for stalled jobs while it runs, so it returns a ConfigError there.

type WorkerInfo

type WorkerInfo struct {
	// Name is the worker's name (WorkerOptions.Name), or "" for a worker
	// without one.
	Name string
	// Fields holds what the datastore reports about the worker's
	// connection: every field of its CLIENT LIST entry on Redis (id, addr,
	// age, idle, ...), only name on PostgreSQL. Fields["name"] is the raw
	// connection name, which encodes the queue: `{prefix}:{base64(queue)}`
	// followed by `:w:{name}` for a named worker on Redis, `{queue}` and
	// `:w:{name}` on PostgreSQL, where it is reported as the worker set it,
	// with PostgreSQL's `\xhh` escaping of non-ASCII bytes undone.
	Fields map[string]string
}

WorkerInfo describes a worker connected to a queue, as listed by Queue.Workers.

type WorkerOptions

type WorkerOptions struct {
	// Backend builds the datastore backend. It is required.
	Backend BackendFactory
	// Name identifies the worker; stored on each processed job as `pb`.
	Name string
	// Concurrency is the number of jobs processed in parallel. Defaults to 1.
	// Worker.SetConcurrency changes it while the worker runs.
	Concurrency int
	// LockDuration is how long a job lock is held. Defaults to 30s. A positive
	// value must be at least 1ms, since the lock TTL is stored in milliseconds,
	// and at least 2ms unless SkipLockRenewal is set (the renewal interval
	// must be at least 1ms and less than LockDuration).
	LockDuration time.Duration
	// LockRenewTime is how often the lock is renewed. Defaults to LockDuration/2.
	// When renewal is enabled it must be at least 1ms (the lock TTL is stored
	// in milliseconds) and less than LockDuration, so the lock is renewed
	// before it expires.
	LockRenewTime time.Duration
	// StalledInterval is how often stalled jobs are checked. Defaults to 30s.
	// A positive value must be at least 1ms unless SkipStalledCheck is set,
	// since it is stored as a millisecond lock TTL.
	StalledInterval time.Duration
	// MaxStartedAttempts fails a job unrecoverably ("job started more than
	// allowable limit") when it is started more than this many times, for
	// example because it keeps stalling. 0, the default, means no limit.
	// Negative values are rejected.
	MaxStartedAttempts int
	// MaxStalledCount is how many times a job may stall before failing. Defaults to 1.
	// Use a pointer so an explicit 0 (fail on first stall) is distinguishable
	// from unset. Negative values are rejected.
	MaxStalledCount *int
	// SkipStalledCheck disables the stalled job checker.
	SkipStalledCheck bool
	// SkipLockRenewal disables automatic lock renewal.
	SkipLockRenewal bool
	// DrainDelay is how long a blocking fetch waits for new jobs. Defaults to 5s.
	DrainDelay time.Duration
	// Limiter throttles job processing.
	Limiter *RateLimiter
	// MaximumRateLimitDelay caps how long the worker sleeps in one go while
	// the queue is rate limited, so delayed jobs keep being promoted during a
	// long limit. Defaults to 30s.
	MaximumRateLimitDelay time.Duration
	// Metrics enables completed/failed metrics collection.
	Metrics *MetricsOptions
	// RemoveOnComplete is the default removal policy for completed jobs.
	RemoveOnComplete *RemoveOnFinish
	// RemoveOnFail is the default removal policy for failed jobs.
	RemoveOnFail *RemoveOnFinish
	// BackoffStrategy computes a custom retry delay in milliseconds. Returning
	// a negative value discards the job.
	BackoffStrategy func(attemptsMade int64, backoffType BackoffType, err error, job *Job) int64
	// RepeatStrategy, when set, computes the due time of the next iteration
	// of a Pattern job scheduler when the worker fetches one of its jobs,
	// instead of cron (see [RepeatStrategy]). It must match the one of the
	// queue that upserted the scheduler.
	RepeatStrategy RepeatStrategy
	// OnEvent, when set, is called synchronously with every event the worker
	// emits, including those dropped from a full Events channel. It runs on
	// the worker's goroutines (a slow callback slows processing down), may
	// be called concurrently, and must not call Worker.Close, which waits
	// for those goroutines; start a goroutine for that instead. It may call
	// Worker.Pause, for example on EventDrained (see Pause for the events it
	// must not wait from).
	OnEvent func(Event)
	// OnError is called for background errors that cannot be returned to a caller.
	// It runs on its own goroutine, so it may safely call Worker.Close, but
	// calls can be concurrent and are not ordered; the callback must be safe
	// for concurrent use.
	OnError func(err error)
}

WorkerOptions configures a Worker.

Directories

Path Synopsis
internal
cronparity
Package cronparity evaluates cron expressions exactly like cron-parser 5.10.6, the library and version the Node.js BullMQ uses for job scheduler patterns, so a Go worker computes the same next runs, and therefore the same job ids, as a Node.js worker would.
Package cronparity evaluates cron expressions exactly like cron-parser 5.10.6, the library and version the Node.js BullMQ uses for job scheduler patterns, so a Go worker computes the same next runs, and therefore the same job ids, as a Node.js worker would.
queuemeta
Package queuemeta writes the metadata of a queue (bullmq.BackendOptions.
Package queuemeta writes the metadata of a queue (bullmq.BackendOptions.
testbackends
Package testbackends lists the datastores that the shared behaviour tests of package bullmq run against, together with the datastore-level fixtures some of those tests need.
Package testbackends lists the datastores that the shared behaviour tests of package bullmq run against, together with the datastore-level fixtures some of those tests need.
Package postgresbackend is the PostgreSQL implementation of bullmq.Backend.
Package postgresbackend is the PostgreSQL implementation of bullmq.Backend.
Package redisbackend is the Redis implementation of bullmq.Backend.
Package redisbackend is the Redis implementation of bullmq.Backend.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL