Designing Retryable Background Jobs Without Duplicate Side Effects
How to build idempotent distributed tasks using BullMQ, Kafka, and PostgreSQL without double-charging or duplicate notifications.
Core Takeaway
In distributed architectures, transient network failures and process crashes are inevitable. When background workers fail mid-execution and queues redeliver the job, naive retry logic can cause catastrophic duplicate side effects—such as duplicate customer emails or repeated payment charges. This note outlines architectural patterns for building strictly idempotent background jobs.
Problem Statement & Context
Most message brokers (Kafka, RabbitMQ, BullMQ/Redis) offer 'at-least-once' delivery guarantees under network partitions. This means a job will never be lost, but it may be delivered to a worker more than once. If your worker code is not designed to be idempotent, retrying a job that partially completed can trigger duplicate database inserts, duplicate downstream API calls, or corrupted state.
System Flow & Data Path
[ Job Enqueued ] ---> Idempotency Key: "notify:u12:order99:email"
|
v
[ Worker Picks Job ]
|
v
[ PostgreSQL Check ] ---> INSERT INTO processed_jobs (key, 'PROCESSING')
| ON CONFLICT DO NOTHING;
|
+---> Conflict? ---> [ SKIP & ACK: Job already processed ]
|
+---> Success! ---> [ Call External Provider (Resend / Twilio) ]
|
+-------------+-------------+
| |
(Success 200) (Network Timeout 504)
v v
[ UPDATE: 'COMPLETED' ] [ Throw RetryableError ]
| |
[ BullMQ Job Done ] [ BullMQ Exponential Backoff ]Architectural Concepts & Implementation
1. Deterministic Idempotency Keys at Job Creation
Every background job must be assigned an immutable, deterministic idempotency key derived from the originating business event (e.g., checkout_evt_98234_email or pr_eval_#142_sha7c91). Never rely on arbitrary auto-incrementing queue IDs.
import { Queue } from 'bullmq';
const notificationQueue = new Queue('notifications', { connection: redisOptions });
export async function enqueueNotification(
userId: string,
eventId: string,
channel: 'email' | 'push'
) {
// Deterministic job ID guarantees BullMQ will ignore duplicate enqueue attempts
// within the active/waiting job window
const jobId = 'notify:' + userId + ':' + eventId + ':' + channel;
await notificationQueue.add(
'send_alert',
{ userId, eventId, channel, timestamp: Date.now() },
{
jobId, // Native deduplication in BullMQ
attempts: 5,
backoff: {
type: 'exponential',
delay: 2000, // 2s, 4s, 8s, 16s...
},
removeOnComplete: { age: 3600 * 24 }, // retain for 24h audit
}
);
}2. Atomic State Reservation with PostgreSQL UNIQUE Indexes
Before executing any non-reversible external side-effect (e.g., calling an SMS gateway or sending an email), the worker must record its intent in a persistent relational store with a UNIQUE constraint. If another worker attempts to process the same key concurrently, the database rejects the duplicate transaction.
CREATE TABLE processed_job_records (
idempotency_key VARCHAR(128) PRIMARY KEY,
job_type VARCHAR(64) NOT NULL,
status VARCHAR(32) NOT NULL, -- 'PROCESSING', 'COMPLETED', 'FAILED'
result_payload JSONB,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- In worker code:
-- INSERT INTO processed_job_records (idempotency_key, job_type, status)
-- VALUES ($1, $2, 'PROCESSING')
-- ON CONFLICT (idempotency_key) DO NOTHING;
-- If rows_affected == 0, another worker already owns this job!3. Handling Partial Failures and Downstream Retries
If the external provider returns a 500 error or times out, the worker must throw a specific retryable exception. BullMQ's exponential backoff handles scheduling the retry. However, if the external service does not support idempotency keys natively, you must query their status API before retrying to verify whether the previous attempt actually took effect.
Common Pitfalls & Trade-offs
- !Pitfall: Releasing idempotency locks on error. If you delete the idempotency key on failure, a race condition can cause two concurrent retry workers to run simultaneously. Keep the record and update status to 'RETRY_PENDING' instead.
- !Pitfall: In-memory only locks. Redis SET NX locks can be lost if the Redis node crashes or experiences a replica failover. For high-value operations, persist the lock key in PostgreSQL.
- !Trade-off: Deduplication key retention. Storing idempotency keys forever increases table size. Implement a partitioning or rolling cleanup policy (e.g., retaining keys for 7 to 30 days based on business retry windows).
Production Verification Checklist
- Derive idempotency keys deterministically from source business entity IDs.
- Configure exponential backoff with jitter on all queue retry policies.
- Store idempotency reservations in a relational store with UNIQUE constraints before calling external APIs.
- Send permanent failures (4xx client errors) to a Dead Letter Queue (DLQ) immediately rather than retrying indefinitely.
- Ensure all downstream provider calls pass client request idempotency headers where supported.