NextMQ

SDK reference

Every public class, method, option, error, and limit in one place. The guides teach the common paths with real code; this page is the exhaustive source of truth for the technical detail.

Imports#

import {
  FlowProducer,
  JobRemovedError,
  NextMQHttpError,
  NextMQRequestTimeoutError,
  Queue,
  RateLimitError,
  UnrecoverableJobError,
  Worker,
  isNextMQControlFlowError,
  resetNextMQConfig,
  type Job,
  type Processor,
  type RemoteJobOptions,
  type RemoteWorkerOptions,
} from '@nextmq/sdk'

import {
  WorkerRegistrationError,
  createNextMQHandler,
  ensureWorkersRegistered,
  getWorkerRegistrationStatuses,
} from '@nextmq/sdk/next'

Classes at a glance#

ClassWhat it isGuide
QueueProduce jobs and inspect/control a queue. Creating one is local; methods are HTTP calls.Queues
WorkerDeclares the processor that runs a queue's jobs, plus its execution options.Workers
JobA single job — read its state, mutate it, or signal an outcome from a processor.Jobs
FlowProducerCreate and inspect parent/child job graphs.Flows
createNextMQHandlerBuilds the signed webhook route that runs your workers.Quickstart
Note
Queue and FlowProducer take no Redis connection — the SDK reads its config from the environment and talks to NextMQ over HTTP. Every method below is an async HTTP call unless noted. See Configuration.

Queue#

const queue = new Queue<TData, TReturnValue>(name)

Produce

MethodDescription
add(name, data, opts?)Enqueue one job. opts is the job-options set below. Returns the created Job.
addBulk(jobs)Enqueue many jobs in one call ({ name, data, opts? }[]). Up to 1,000 per call.

Read

MethodDescription
getJob(jobId)Fetch one job by id, or undefined if it no longer exists.
getJobs(states, start?, end?)Fetch jobs in the given states (paged; default 0–99, max 1,000 per request).
getWaiting / getActive / getCompleted / getFailed / getDelayed / getPrioritized / getWaitingChildren (start?, end?)Paged fetch of jobs in a single state.
count() / getJobCounts(...states?)Total job count, or counts per state.
getWaitingCount / getActiveCount / … (per-state counters)Count for a single state.
getJobLogs(jobId, start?, end?)Read a job's log lines (paged, retained up to keepLogs).
getSummary()Counts and paused state in one call — handy for a dashboard row.

Control & maintenance

MethodDescription
pause()Stop the queue from starting new jobs; in-flight jobs finish. Use during an incident or migration.
resume()Resume a paused queue.
isPaused()Whether the queue is currently paused.
drain(delayed?)Remove waiting jobs (and delayed when delayed=true), keeping active ones — clear a backlog without deleting the queue.
clean(grace, limit, state)Bulk-remove jobs in a state older than grace ms (e.g. old completed/failed). limit caps how many per call.
retryJobs(opts?)Move failed (or completed) jobs back to waiting — recover after a downstream outage.
promoteJobs(opts?)Move delayed jobs to waiting now.
obliterate(opts?)Delete the queue and all its data. Destructive; pass { force: true } to skip the active-jobs guard.
Heads up
Control methods can be destructive and run under your full-scope key. Keep NEXTMQ_CONNECTION_STRING server-only.

Schedulers

MethodDescription
upsertJobScheduler(id, repeat, template?)Create or update a scheduler by id (idempotent). repeat = the scheduler options below; template sets the produced job's name/data/opts.
getJobSchedulers(start?, end?)List the queue's schedulers (paged).
getJobScheduler(id)Fetch one scheduler, or undefined.
removeJobScheduler(id)Delete a scheduler; returns whether one was removed.

Queue-wide throughput

Runtime, queue-level throttles you can change without redeploying — see Workers for how they relate to a worker's own concurrency and limiter.

MethodDescription
setGlobalConcurrency(n)Cap how many of the queue's jobs run at once, across the board.
getGlobalConcurrency()Current global concurrency, or null if unset.
removeGlobalConcurrency()Clear the global concurrency cap.
setGlobalRateLimit(max, duration)Cap how many jobs start per duration ms window.
getGlobalRateLimit()Current global rate limit { max, duration }, or null.
removeGlobalRateLimit()Clear the global rate limit.

Deduplication

MethodDescription
getDeduplicationJobId(dedupId)The job id currently holding a deduplication key, or null.
removeDeduplicationKey(dedupId)Release a deduplication key early so the next add is no longer collapsed.

Worker#

const worker = new Worker<TData, TReturnValue>(queueName, processor, options?)
MemberDescription
processor(job)Your function. Return a value to complete the job; throw to fail it (retries apply).
run()Start processing. The webhook handler calls this for you; rarely needed directly.
close()Local only — stops this declaration. It does not unregister the durable server-side worker.
autorunWhether the handler registers this worker by default (set { autorun: false } to opt out).
optionsThe resolved RemoteWorkerOptions (below).
Note
Outcome signals — moveToCompleted, moveToFailed, moveToDelayed — and the errors UnrecoverableJobError / RateLimitError are how a processor reports results. See Workers.

Job#

Properties

PropertyDescription
idJob id. Use it as the idempotency key for side effects.
nameJob name passed to add().
dataThe job payload (typed as TData).
optsThe applied job options, including clamped retention — what was actually stored.
progressLast value reported by updateProgress().
returnvalueThe processor's return value once completed.
failedReasonError message of the last failed attempt.
stacktraceCaptured stack traces for failed attempts.
attemptsMadeHow many attempts have run.
timestamp / processedOn / finishedOnCreated, first-processed, and finished epoch ms.
parent / parentKeyFor a flow child, a reference to its parent.
deliveryIdIdentifies one delivery attempt — finer-grained than id for per-attempt logging/dedup.

State

MethodDescription
getState()Current state: 'waiting' | 'active' | 'completed' | 'failed' | 'delayed' | …
refresh()Re-fetch the latest job data from the server, mutating this instance.
isCompleted / isFailed / isActive / isWaiting / isDelayed / isWaitingChildren ()Convenience booleans over the last known state.

Mutate & act

MethodDescription
updateProgress(value)Report progress (a number or an object). Call from inside a processor.
log(line)Append a log line, retained up to keepLogs. Returns the new line count.
updateData(data)Replace the job's data payload.
retry(state?)Move a failed (or completed) job back to waiting to run again.
promote()Move a delayed job to waiting now.
changeDelay(ms)Reschedule a delayed job.
changePriority({ priority?, lifo? })Change a waiting job's priority or LIFO placement.
remove({ removeChildren? })Delete the job; pass removeChildren for flow trees.

Outcome signals (inside a processor)

MethodDescription
moveToCompleted(value)Complete the job — same as returning value. Execution stops after the call.
moveToFailed(error)Fail the job — same as throwing. UnrecoverableJobError skips remaining attempts.
moveToDelayed(timestamp)Re-run the job at an absolute epoch-ms time.
moveToWaitingChildren()Not supported — model graphs with FlowProducer. Throws a clear error.

Flows & waiting

MethodDescription
getChildrenValues()In a flow parent, the children's return values keyed by '<queue>:<jobId>'.
waitUntilFinished({ timeoutMs?, pollIntervalMs? })Poll until the job completes or fails. The serverless-safe replacement for QueueEvents.

FlowProducer#

MethodDescription
add(flow)Create one parent/child graph. Children run first; the parent runs after they finish.
addBulk(flows)Create multiple independent flows in one call (up to 100).
getFlow({ id, queueName, depth?, maxChildren? })Fetch a flow tree for inspection.

@nextmq/sdk/next#

ExportDescription
createNextMQHandler({ workers })Returns { GET, POST } for the catch-all webhook route. Verifies signatures, dispatches jobs, serves /health. Node runtime only.
ensureWorkersRegistered(workers, opts?)Register workers' callback URLs up front (e.g. from instrumentation.ts). Idempotent. { includeNonAutorun: true } registers autorun:false workers too.
getWorkerRegistrationStatuses(workers)Per-worker registration status — useful in a health check or smoke test.

Job options (add)#

The third argument to add(). Unsupported options are rejected, never silently dropped.

OptionType / boundDescription
delayms ≥ 0Wait this long before the job becomes eligible. Cannot be combined with repeat.
attemptsint ≥ 0Total tries before the job is marked failed.
backoff{ type, delay }Retry spacing: type 'fixed' or 'exponential', delay in ms.
priority0 – 2,097,152Lower runs first; 0 means unprioritized.
jobIdstringCustom id. Cannot contain ':' or be an integer string. One canonical job per business object.
lifobooleanPush to the front of the queue instead of the back.
keepLogsint ≥ 0Max log lines to retain (clamped to the project cap).
sizeLimitbytes ≥ 1Reject the job if its serialized data exceeds this.
removeOnCompletebool | n | { age, count? }Retention for completed jobs. Clamped to project caps.
removeOnFailbool | n | { age, count? }Retention for failed jobs. Clamped to project caps.
deduplication{ id, … }Collapse duplicate work within a window — see below.
repeat{ pattern | every, … }Inline repeatable config; prefer Job Schedulers.

Flow child options

OptionDescription
failParentOnFailureIf this child fails, fail the parent immediately.
continueParentOnFailureLet the parent proceed even if this child fails.
ignoreDependencyOnFailureDon't block the parent on this child's result if it fails.
removeDependencyOnFailureDrop this child from the parent's dependency set on failure.

Worker options#

OptionBound / defaultDescription
concurrency1 – 100; default 1Max jobs this worker runs in parallel.
limiter{ max ≥ 1, duration ≥ 100 }Rate limit: at most max jobs per duration ms.
timeoutMs1,000 – 300,000; default 30,000How long NextMQ waits for your webhook response. Keep below your platform's function timeout.
autorundefault trueWhether the handler registers this worker by default.
lockDuration1,000 – 300,000How long a job's lock is held while processing. Advanced.
lockRenewTime500 – 300,000Lock renew interval; must be < lockDuration. Advanced.
stalledInterval1,000 – 300,000How often stalled jobs are checked. Advanced.
maxStalledCount0 – 100Times a job may stall before failing. Advanced.
drainDelay1 – 300,000Delay used while the queue drains. Advanced.

Scheduler options#

The repeat argument to upsertJobScheduler. Provide exactly one of pattern or every.

OptionDescription
patternCron expression (e.g. '0 9 * * *').
everyFixed interval in ms (alternative to pattern).
limitStop after this many runs.
tzTimezone for cron evaluation (follows DST).
startDate / endDateDon't fire before / after these times.
immediatelyProduce the first job now instead of after one interval (not with startDate).

Deduplication options#

OptionDescription
idDeduplication key. A second add with the same id is collapsed.
ttlWindow in ms during which duplicates collapse.
extendRefresh the ttl on each duplicate add.
replaceReplace the pending job's data with the newer add.
keepLastIfActiveKeep deduplicating against a job that's currently active.

Errors & control flow#

ExportUse
UnrecoverableJobErrorThrow in a processor to fail permanently without using remaining attempts.
RateLimitErrorThrow with a retry-after delay to pause/requeue on a provider rate limit, without burning an attempt.
JobRemovedErrorThrown by waitUntilFinished when the job is gone and no result snapshot remains.
NextMQHttpErrorA non-2xx response to an SDK request — inspect .status and body.
NextMQRequestTimeoutErrorAn SDK request exceeded NEXTMQ_REQUEST_TIMEOUT_MS.
WorkerRegistrationErrorensureWorkersRegistered could not register one or more workers.
isNextMQControlFlowError(err)Re-throw internal moveTo* signals from a broad try/catch so they aren't swallowed.
resetNextMQConfig()Clear cached env-derived config — mainly for tests that change process.env between cases.

Limits#

The fixed technical limits the SDK and server enforce. Plan quotas (queues, jobs, throughput included) are separate — see pricing.

Identifiers and jobs

LimitValue
Queue name1-128 characters; letters, numbers, _, -, and . only.
jobIdCannot contain ':' and cannot be an integer string.
priority0 to 2,097,152.
addBulk()At most 1,000 jobs per call.
Job list, log, and scheduler pagesAt most 1,000 items per request.
Child values pageAt most 1,000 processed child values per request.

Flows

LimitValue
Flow depthAt most 20 levels.
Children per flow nodeAt most 1,000.
FlowProducer.addBulk()At most 100 independent flows per call.
Flow child deduplicationNot supported on child jobs.

Workers and webhooks

LimitValue
concurrency1 to 100; default 1.
timeoutMs1,000 to 300,000 ms; default 30,000 ms.
limiter.durationMinimum 100 ms.
NEXTMQ_WEBHOOK_BODY_LIMIT_BYTESDefault 1,048,576; max 10,485,760.
NEXTMQ_REQUEST_TIMEOUT_MSDefault 15,000; max 300,000.

Retention defaults

SettingDefault
removeOnCompleteCompleted jobs are capped at 1,000 or 1 day.
removeOnFailFailed jobs are capped at 5,000 or 7 days.
keepLogs100 log lines.

Explicit retention values are clamped to the project caps. Immediate removal still keeps a short result snapshot for polling callers; see Reliability & delivery guarantees.