Backend Engineering

Retry-Safe BullMQ Workers: Idempotency Beyond Job Deduplication

Retries make background processing resilient only when repeated execution is safe. This guide shows how to combine BullMQ controls with durable business-level idempotency.

A background job is rarely dangerous because it fails. It becomes dangerous when it succeeds partially, gets retried, and repeats a side effect that should have happened once.

That distinction matters in BullMQ. The queue can retry failed work, recover jobs after worker failures, and suppress some duplicate submissions. None of those features can guarantee that your payment provider, email service, database, or third-party API sees a side effect exactly once. BullMQ describes its delivery behavior as targeting exactly-once processing while falling back to at-least-once in the worst case. Production workers therefore need to assume that the same business operation can run more than once.

The useful design question is not “How can BullMQ be stopped from delivering a duplicate?” It is: “If this operation is delivered twice, what state proves that the second execution is safe?”

Three different problems that teams call “duplicates”

Queue systems expose several failure modes that look similar in logs but need different controls.

The first is duplicate enqueueing. An API handler receives the same webhook twice or two application instances schedule the same task. A custom BullMQ jobId or a deduplication identifier can suppress the second queue entry while the first job still exists.

The second is duplicate execution. A worker performs the external side effect, then loses its Redis lock or crashes before BullMQ records completion. The job can run again even though the external call already succeeded.

The third is duplicate intent. Two requests may look similar but represent legitimately separate business actions. Deduplicating them with a coarse key can silently discard work.

These categories explain why “a unique job ID is set” is incomplete. BullMQ notes that job ID uniqueness is scoped to a queue, and a removed completed or failed job no longer blocks the same ID from being added again. A queue-level key is useful admission control; it is not a permanent business guarantee.

Build the idempotency key from business intent

An idempotency key should identify the business operation, not the delivery attempt. Good keys tend to combine a stable entity identifier with the intended transition:

const idempotencyKey = `invoice:${invoiceId}:issue:v1`;
const bullmqJobId = `invoice-${invoiceId}-issue-v1`;

await billingQueue.add(
  'issue-invoice',
  { invoiceId, idempotencyKey },
  {
    jobId: bullmqJobId,
    attempts: 5,
    backoff: { type: 'exponential', delay: 1_000 },
  },
);

The version suffix is deliberate. If the meaning or payload contract changes, a new version prevents an old successful operation from being confused with a new intent.

Avoid keys based only on timestamps, random UUIDs generated during enqueueing, or a job’s attempt number. Those values distinguish deliveries, which is the opposite of what idempotency needs. Also avoid keys that are too broad, such as customer:42:email, when multiple distinct emails are valid.

Keep the business key in the job payload. The worker needs the same identifier when it talks to a database or an external API. BullMQ custom job IDs cannot contain :, so the queue ID uses a separate safe representation. The two identifiers should encode the same intent, but they do not need to use the same syntax.

Put the durable decision next to the durable state

For a database-only job, the strongest pattern is usually a conditional write inside a transaction. Instead of reading a row, deciding what to do in application memory, and then writing, make the state transition itself reject repeats.

const result = await db.query(
  `UPDATE invoices
   SET status = 'issued', issued_at = NOW()
   WHERE id = $1 AND status = 'pending'
   RETURNING id`,
  [invoiceId],
);

if (result.rowCount === 0) {
  return { outcome: 'already-applied-or-not-applicable' };
}

This turns a race into a property the database can enforce. A unique constraint on an operation table is another common option:

CREATE UNIQUE INDEX operations_idempotency_key
ON operations (idempotency_key);

Insert the operation record and apply the business mutation in the same transaction. If two workers race, one insert wins and the other observes the existing record. The stored result can be returned to retries so callers see a consistent outcome.

A read-before-write check without a transaction or uniqueness constraint is not enough. Two workers can both read “not processed” before either writes.

External APIs require a different boundary

The hard case is a job that changes local state and calls another service. A database transaction cannot atomically include an arbitrary HTTP request. There are several defensible strategies, depending on what the external system supports.

If the provider accepts idempotency keys, pass the same stable key on every attempt and persist the provider’s response. AWS’s guidance on idempotent APIs emphasizes caller-provided request identifiers because a timeout leaves the caller uncertain whether the original operation completed. The identifier lets the service distinguish a retry from new intent.

If the provider does not support idempotency, model the workflow explicitly. Persist an operation row with states such as pending, sending, confirmed, and needs_reconciliation. Store the external reference when one becomes available. A retry first inspects this state and, where possible, queries the provider before sending again.

For outbound events, use a transactional outbox. Commit the domain change and an outbox record in one database transaction. A separate worker publishes the record and marks it delivered. Consumers still need idempotency because publication can repeat, but the producer no longer risks committing business state without recording the event that must follow.

These approaches do not magically create distributed exactly-once behavior. They make uncertainty explicit, durable, and recoverable.

Retries need classification, limits, and jitter

Idempotency makes retries safer; it does not make every error retryable. A validation failure, revoked credential, or unsupported payload will not improve on the fifth attempt. Retrying permanent failures only increases queue latency and hides the real problem.

Classify errors into at least three groups:

  • transient: timeouts, connection resets, temporary rate limits, and some 5xx responses;
  • permanent: malformed input, non-retryable authorization or configuration failures after any supported credential-refresh path, and rejected business rules;
  • uncertain: the request may have completed, but the response was lost.

Use bounded attempts and backoff for transient failures. BullMQ supports fixed and exponential backoff. Add jitter when many workers may fail against the same dependency at once; AWS reliability guidance recommends controlling retries because synchronized clients can amplify an outage.

Uncertain outcomes deserve special handling. Retry automatically only when the downstream operation is protected by an idempotency key or can be safely reconciled. Otherwise move the operation to a review or reconciliation path instead of guessing.

Keep workers small enough to reason about

BullMQ’s idempotent-job guidance recommends atomic, simple jobs. That advice is less about code style than failure boundaries. A worker that updates three tables, uploads a file, sends an email, and calls a billing API has many partial-success states.

Split a long workflow when each step has its own retry policy or compensating action. BullMQ flows can express dependencies between jobs, but the same rule still applies: every step needs a durable definition of “already complete.”

Do not split work merely to create more queues. A single transactional database mutation is often safer as one job. Split at boundaries where atomicity ends or operational ownership changes.

Observability should describe business outcomes

Attempt counts and failed-job totals are necessary but insufficient. Instrument the decisions that prove your safeguards work:

  • idempotency-key conflicts;
  • queue submissions suppressed by deduplication;
  • jobs returning an already-applied outcome;
  • external requests recovered by provider idempotency;
  • uncertain operations awaiting reconciliation;
  • retries exhausted by error class;
  • age of the oldest unresolved operation.

Log the BullMQ job ID, idempotency key, business entity ID, attempt number, and downstream request ID together. Avoid placing secrets or sensitive payloads in logs.

Alert on a sustained increase in duplicate outcomes, not every duplicate. A duplicate may be expected after a worker restart. A sharp change often signals an upstream retry storm, a lock-duration problem, or a dependency timing out after accepting requests.

A practical review checklist

Before enabling retries on a BullMQ worker, verify the following:

  1. The idempotency key represents one business intent and remains stable across retries.
  2. BullMQ job IDs or deduplication are treated as queue admission controls, not the final guarantee.
  3. Local state transitions use transactions, conditional writes, or unique constraints.
  4. External mutations use provider idempotency or an explicit reconciliation state machine.
  5. Permanent errors fail fast; transient errors use bounded backoff and jitter.
  6. Every partial-success boundary has a recoverable state.
  7. Completed jobs are not removed without understanding how that affects queue-level duplicate suppression.
  8. Metrics distinguish successful work, safe repeats, uncertain outcomes, and terminal failures.
  9. Tests inject crashes after each side effect but before job completion is acknowledged.

That last test is the one most likely to reveal a false assumption. Force the worker to stop after the external operation succeeds, then let BullMQ retry it. If the result is safe and observable, the design is meaningfully idempotent.

The engineering standard is retry safety

Reliable queues do not eliminate duplicate delivery. They give systems a structured way to continue after failure. The application must supply the business invariants that make continuation safe.

Use BullMQ deduplication to reduce redundant work. Use durable idempotency records, transactional state transitions, downstream request keys, and reconciliation to protect real side effects. Then test the uncomfortable timing windows—not only the happy path.

If you are designing a Node.js job system and want a second set of eyes on its retry boundaries, failure states, or production-readiness plan, get in touch.

Start a conversation

Building something technically challenging? Let’s talk.

I work with teams on difficult product, architecture, and engineering problems.