Message Queue
Message Queue
An asynchronous communication broker system. RabbitMQ, SQS. Reduces coupling between services.
Message Queue
An asynchronous communication broker system. RabbitMQ, SQS. Reduces coupling between services.
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.
// 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
}));
}
}
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