๐Ÿ—๏ธ Architecture

Message Queue

Message Queue

An asynchronous communication broker system. RabbitMQ, SQS. Reduces coupling between services.

๐Ÿ“– Detailed Explanation

A Message Queue is an asynchronous communication system that temporarily stores and delivers messages between a producer (Producer) and a consumer (Consumer). Unlike synchronous API calls, the producer puts a message in the queue and returns immediately, while the consumer processes messages at its own pace.

Key advantages: 1) Loose coupling - services communicate through messages without direct dependencies on each other, 2) Asynchronous processing - long-running tasks are separated into the background, 3) Peak load smoothing - the queue acts as a buffer during traffic spikes, 4) Reliability - message persistence prevents data loss even during failures, 5) Scalability - throughput increases by horizontally scaling consumers.

Representative solutions: RabbitMQ (AMQP, flexible routing), Apache Kafka (high-throughput event streaming), AWS SQS (managed, simple), Redis Streams (lightweight, fast). The selection criteria depend on throughput, ordering guarantees, message size, and persistence requirements.

Typical use cases: sending emails/notifications, image/video processing, order processing pipelines, log collection, event delivery between microservices. Tasks that could become slow or fail when handled synchronously are separated out into a queue.

๐Ÿ’ป Code Example

// Message Queue ํŒจํ„ด ์˜ˆ์ œ (BullMQ - Redis ๊ธฐ๋ฐ˜)
import { Queue, Worker, Job } from 'bullmq';
import Redis from 'ioredis';

const connection = new Redis(process.env.REDIS_URL);

// 1. ํ ์ƒ์„ฑ
const emailQueue = new Queue('email', { connection });
const imageQueue = new Queue('image-processing', { connection });

// 2. ๋ฉ”์‹œ์ง€(Job) ์ƒ์‚ฐ - Producer
async function sendWelcomeEmail(userId: string, email: string) {
  // ์ฆ‰์‹œ ๋ฐ˜ํ™˜, ์ด๋ฉ”์ผ ๋ฐœ์†ก์€ ๋น„๋™๊ธฐ๋กœ
  await emailQueue.add('welcome', {
    userId,
    email,
    template: 'welcome'
  }, {
    attempts: 3,           // ์‹คํŒจ ์‹œ 3๋ฒˆ ์žฌ์‹œ๋„
    backoff: {
      type: 'exponential',
      delay: 1000          // 1์ดˆ โ†’ 2์ดˆ โ†’ 4์ดˆ
    },
    removeOnComplete: 100, // ์™„๋ฃŒ๋œ Job 100๊ฐœ๊นŒ์ง€๋งŒ ์œ ์ง€
    removeOnFail: 1000
  });
}

// ์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ ์š”์ฒญ
async function processImage(imageId: string, operations: string[]) {
  await imageQueue.add('resize', {
    imageId,
    operations
  }, {
    priority: 1,  // ์šฐ์„ ์ˆœ์œ„ (๋‚ฎ์„์ˆ˜๋ก ๋จผ์ €)
    delay: 0      // ์ฆ‰์‹œ ์ฒ˜๋ฆฌ
  });
}

// 3. ๋ฉ”์‹œ์ง€ ์†Œ๋น„ - Consumer (Worker)
const emailWorker = new Worker('email', async (job: Job) => {
  const { email, template, userId } = job.data;

  console.log(`Processing email job ${job.id}: ${email}`);

  // ์‹ค์ œ ์ด๋ฉ”์ผ ๋ฐœ์†ก
  await sendEmail({
    to: email,
    template,
    data: { userId }
  });

  return { sent: true, email };  // ๊ฒฐ๊ณผ ์ €์žฅ
}, {
  connection,
  concurrency: 5,  // ๋™์‹œ ์ฒ˜๋ฆฌ ์ˆ˜
  limiter: {
    max: 100,      // ๋ถ„๋‹น ์ตœ๋Œ€ 100๊ฐœ
    duration: 60000
  }
});

// ์ด๋ฒคํŠธ ํ•ธ๋“ค๋ง
emailWorker.on('completed', (job) => {
  console.log(`Job ${job.id} completed`);
});

emailWorker.on('failed', (job, err) => {
  console.error(`Job ${job?.id} failed:`, err);
  // ์•Œ๋ฆผ, ๋ชจ๋‹ˆํ„ฐ๋ง ๋“ฑ
});

// 4. AWS SQS ์˜ˆ์ œ
import { SQSClient, SendMessageCommand, ReceiveMessageCommand } from '@aws-sdk/client-sqs';

const sqs = new SQSClient({ region: 'ap-northeast-2' });
const QUEUE_URL = process.env.SQS_QUEUE_URL;

// ๋ฉ”์‹œ์ง€ ์ „์†ก
async function sendToSQS(data: object) {
  await sqs.send(new SendMessageCommand({
    QueueUrl: QUEUE_URL,
    MessageBody: JSON.stringify(data),
    MessageAttributes: {
      Type: {
        DataType: 'String',
        StringValue: 'order'
      }
    }
  }));
}

// ๋ฉ”์‹œ์ง€ ์ˆ˜์‹  (Long Polling)
async function pollMessages() {
  const response = await sqs.send(new ReceiveMessageCommand({
    QueueUrl: QUEUE_URL,
    MaxNumberOfMessages: 10,
    WaitTimeSeconds: 20,  // Long polling
    VisibilityTimeout: 30  // ์ฒ˜๋ฆฌ ์‹œ๊ฐ„
  }));

  for (const message of response.Messages || []) {
    await processMessage(JSON.parse(message.Body!));
    // ์ฒ˜๋ฆฌ ์™„๋ฃŒ ํ›„ ์‚ญ์ œ
    await sqs.send(new DeleteMessageCommand({
      QueueUrl: QUEUE_URL,
      ReceiptHandle: message.ReceiptHandle
    }));
  }
}

๐Ÿ—ฃ๏ธ Examples of Practical Conversations

In system design:

"After payment is completed, sending the email, earning points, and decreasing inventory are handled synchronously, so the response is slow." - "Handle only the payment synchronously and process the rest asynchronously with a message queue. If you publish a payment-completed event, each service processes it independently."

In a technical interview:

"When should I use RabbitMQ vs Kafka?" - "RabbitMQ is a traditional message broker that is good for complex routing and request-response patterns. Kafka specializes in event streaming and is suited for high-volume logs and real-time analytics. If throughput is important, go with Kafka."

In incident response:

"Messages keep piling up in the queue." - "Check the consumer processing speed. You should increase the number of consumers or check whether there is a bottleneck in the processing logic. It's also necessary to set up a DLQ (Dead Letter Queue) to collect failed messages separately."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

โš ๏ธ Cautions

๐Ÿ”— Related Terms

RabbitMQ Kafka Event-Driven Pub/Sub Saga Pattern

๐Ÿ“š Learn More

๐Ÿ“„ AWS - Message Queue Overview ๐Ÿ“„ BullMQ - Node.js Queue Library ๐Ÿ“„ RabbitMQ for Beginners