Across 40+ products shipped at StartupSphare—including high-throughput platforms like Northwind Logistics, MealNote, and Easy Clean—the single most common cause of silent data loss in early-stage Node.js backends is running asynchronous side effects inside an HTTP request lifecycle.
When an API route awaits a Stripe webhook handler, an LLM agent call, or a multi-step PDF invoice generation, a single network timeout or container restart drops the job forever. Moving those workloads into BullMQ backed by Dockerized Redis decouples your API response time from downstream latency and guarantees at-least-once execution.

Why Naive Promise.all and In-Memory Queues Fail in Production
In MealNote, we initially processed nutrition-label OCR and webhook syncs using fire-and-forget promises. Under peak load, two failure modes appeared immediately:
- OOM Kills & Deploy Restarts: Any in-memory queue (
p-queue,fastq) vanishes when Kubernetes or Docker restarts a container during a deployment. - Duplicate Webhook Execution: Payment providers like Stripe and Twilio retry webhooks if your endpoint takes longer than 3–5 seconds to return
200 OK. Without deterministicjobIddeduplication, you risk double-charging or sending duplicate notifications.
For deeper patterns on handling external webhook retries, see our guide on integrating third-party APIs like Stripe and Twilio.
Step 1: Production Docker Compose Configuration for Redis
Redis for BullMQ is not a cache—it is a persistent message broker. If Redis evicts keys when memory fills up, BullMQ loses job state and locks. You must configure noeviction and Append-Only File (AOF) persistence.
# docker-compose.yml
services:
redis:
image: redis:7.4-alpine
container_name: startupsphare_redis
restart: unless-stopped
ports:
- "6379:6379"
command: >
redis-server
--appendonly yes
--appendfsync everysec
--maxmemory 1gb
--maxmemory-policy noeviction
--requirepass ${REDIS_PASSWORD}
volumes:
- redis_data:/data
healthcheck:
test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD}", "ping"]
interval: 10s
timeout: 5s
retries: 5
volumes:
redis_data:
driver: local
Production Rule: Never use allkeys-lru or volatile-lru on a BullMQ Redis instance. Always set --maxmemory-policy noeviction so Redis returns an error rather than silently deleting active job locks.
Step 2: TypeScript BullMQ Producer with Idempotency Keys
When ingesting a Stripe webhook or queuing an async AI agent task (similar to the pipeline we built for Loomcraft and Ridgeline Health), assign a deterministic jobId. BullMQ automatically ignores duplicate add() calls if a job with that jobId is already waiting, active, or delayed.
// src/queues/webhook.queue.ts
import { Queue } from "bullmq";
import IORedis from "ioredis";
export const redisConnection = new IORedis(process.env.REDIS_URL!, {
maxRetriesPerRequest: null, // Required by BullMQ
enableReadyCheck: false,
});
export interface WebhookJobPayload {
provider: "stripe" | "twilio" | "ai-agent";
eventId: string;
payload: Record<string, unknown>;
}
export const webhookQueue = new Queue<WebhookJobPayload>("webhook-events", {
connection: redisConnection,
defaultJobOptions: {
attempts: 5,
backoff: {
type: "exponential",
delay: 2000, // 2s, 4s, 8s, 16s, 32s
},
removeOnComplete: {
age: 3600 * 24, // Keep completed jobs for 24h
count: 1000,
},
removeOnFail: false, // Retain failed jobs for DLQ inspection
},
});
export async function enqueueWebhookEvent(data: WebhookJobPayload) {
return webhookQueue.add(`${data.provider}:${data.eventId}`, data, {
jobId: `${data.provider}-${data.eventId}`, // Idempotency key
});
}
Step 3: Resilient TypeScript Worker with Graceful Shutdown
Your worker process should run as a separate container or process from your Next.js / Express API server. Always handle SIGTERM and SIGINT so active jobs finish cleanly before the container exits.
// src/workers/webhook.worker.ts
import { Worker, Job } from "bullmq";
import { redisConnection, WebhookJobPayload } from "../queues/webhook.queue";
const worker = new Worker<WebhookJobPayload>(
"webhook-events",
async (job: Job<WebhookJobPayload>) => {
const { provider, eventId, payload } = job.data;
console.log(`[Worker] Processing ${provider} event ${eventId} (attempt ${job.attemptsMade + 1})`);
if (provider === "stripe") {
// Idempotent DB update using eventId
await processStripeEvent(eventId, payload);
} else if (provider === "ai-agent") {
// Long-running LLM or document extraction task
await runAsyncAgentTask(eventId, payload);
}
return { processedAt: new Date().toISOString() };
},
{
connection: redisConnection,
concurrency: 10,
limiter: {
max: 50,
duration: 1000, // Rate-limit to 50 jobs/sec to protect downstream APIs
},
}
);
worker.on("failed", (job, err) => {
console.error(`[DLQ Alert] Job ${job?.id} failed permanently:`, err.message);
});
async function shutdown() {
console.log("[Worker] Draining active jobs before exit...");
await worker.close();
await redisConnection.quit();
process.exit(0);
}
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
Architecture Comparison: BullMQ vs. Alternatives
Choosing the right queue depends on throughput, operational overhead, and budget. Here is how we evaluate options for custom software development clients:
| Architecture | Latency | Monthly Infra Cost | Best For | Trade-Off |
|---|---|---|---|---|
| Dockerized Redis + BullMQ | < 5 ms | $15–$60 (₹1,250–₹5,000) | Node.js APIs, webhooks, AI agent tasks | Requires managing Redis AOF & memory |
| AWS SQS + Lambda | 20–80 ms | $10–$120 (₹850–₹10,000) | Serverless burst workloads | Cold starts & 15-min Lambda timeout |
| RabbitMQ | 5–15 ms | $40–$150 (₹3,300–₹12,500) | Polyglot microservices & complex routing | Higher operational complexity |
In-Memory (p-queue) | < 1 ms | $0 | Non-critical local throttling | Data loss on every deploy or crash |
Frequently Asked Questions
1. Why does BullMQ require maxmemory-policy noeviction in Redis?
BullMQ stores job payloads, delayed timers, and worker locks as Redis keys. If Redis uses an eviction policy like allkeys-lru, it will silently delete active job keys under memory pressure, causing stalled jobs and data loss.
2. How do I prevent duplicate webhook processing in BullMQ?
Pass a deterministic jobId (such as stripe-${event.id}) in the queue.add() options. BullMQ checks Redis atomically and ignores duplicate submissions while the job is waiting, active, or delayed, guaranteeing idempotent execution.
3. Can BullMQ handle long-running AI agent tasks in Node.js?
Yes. BullMQ supports configurable lockDuration and automatic lock renewal while a worker is active, making it ideal for multi-minute LLM workflows, PDF parsing, and batch embeddings without blocking your HTTP API.
4. How should I monitor failed jobs in production?
Set removeOnFail: false in defaultJobOptions so failed jobs remain in Redis for inspection, attach a worker.on("failed") listener for Slack or PagerDuty alerts, and expose a protected Bull Board dashboard for one-click retries.

