typescriptintermediate

Bull Queue Job Producer & Consumer

Create a job queue with Bull for background processing with retries and concurrency control.

typescript
import Queue from 'bull';

interface EmailJob {
  to: string;
  subject: string;
  body: string;
}

const emailQueue = new Queue<EmailJob>('email', {
  redis: { host: '127.0.0.1', port: 6379 },
  defaultJobOptions: {
    attempts: 3,
    backoff: { type: 'exponential', delay: 2000 },
    removeOnComplete: 100,
  },
});

// Producer
export async function enqueueEmail(data: EmailJob) {
  return emailQueue.add(data, { priority: 1 });
}

// Consumer
emailQueue.process(5, async (job) => {
  console.log(`Sending email to ${job.data.to}`);
  // await sendEmail(job.data);
  return { sent: true };
});

Use Cases

  • Email sending queue
  • Image processing pipeline

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.