Enforce the request ID at both the queue and database boundaries
Assign a stable requestId when the HTTP API accepts work. Passing that identifier as BullMQ's jobId tells Redis to ignore duplicate enqueue requests while a matching job is still waiting, delayed, or active.
Queue-level deduplication alone is insufficient once completed jobs expire under removeOnComplete or when a worker crashes right after committing to PostgreSQL but before acknowledging completion back to Redis. A UNIQUE index on request_id in PostgreSQL acts as the permanent source of truth.
Producer deduplication with deterministic jobId and exponential backoff
// 1) Deduplicate while the job is active or waiting in Redis
await reportQueue.add(
"generate-report",
{ requestId, accountId, filters },
{
jobId: requestId,
attempts: 4,
backoff: { type: "exponential", delay: 2000 },
removeOnComplete: { age: 3600, count: 500 },
removeOnFail: { age: 86400 },
},
);Write idempotently with PostgreSQL ON CONFLICT DO NOTHING
When the worker completes generation, commit inside a transaction using ON CONFLICT (request_id) DO NOTHING and immediately select the stored row. Whether the row was created during this attempt or committed by a crashed predecessor, downstream steps receive the exact same record ID.
If a job emits side effects outside PostgreSQL—such as sending a webhook, dispatching an email, or charging a third-party provider—track side-effect delivery state in a separate column or outbox table keyed by the same requestId and pass the provider's Idempotency-Key header.
Permanent idempotency guard inside PostgreSQL
-- 2) Enforce idempotency permanently in PostgreSQL
INSERT INTO generated_reports (request_id, account_id, payload)
VALUES ($1, $2, $3)
ON CONFLICT (request_id) DO NOTHING;
SELECT id, request_id, payload, created_at
FROM generated_reports
WHERE request_id = $1;Separate transient retries from permanent failures and stalled workers
Not every failure should consume retry attempts. Validate malformed inputs or missing templates before calling queue.add(), and throw BullMQ's UnrecoverableError inside the worker when a downstream 4xx response proves retrying will never succeed.
For network timeouts and 5xx dependency blips, combine a bounded attempts count (3 to 5 attempts) with exponential backoff and jitter so recovering upstreams are not hammered simultaneously. Configure lockDuration realistically for the job's runtime so BullMQ's stalled-job checker does not prematurely hand a healthy slow job to a second worker.
- Use UnrecoverableError for invalid payloads, revoked OAuth grants, or missing tenant records.
- Keep Redis lockDuration comfortably above average processing time and call job.extendLock() for long batches.
- Retain failed jobs with requestId context for bounded inspection and safe manual replay.
Test the crash window after the database commit
To verify idempotency before production, run a targeted failure-injection check rather than trusting happy-path unit tests. Submit a request twice, pause or kill worker one right after the PostgreSQL INSERT commits and before BullMQ acknowledges completion, then let worker two pick up the stalled job.
Re-run the same requestId after Redis purges the completed job record. In both failure scenarios, the generated_reports table should contain one row and callers should read back the original report payload.
References: BullMQ Job IDs · BullMQ Retrying Failing Jobs · BullMQ Stalled Jobs