Worker
Worker
A process that handles background tasks. Kubernetes worker node.
Worker
A process that handles background tasks. Kubernetes worker node.
A Worker is a process that handles tasks in the background. Separated from the web request-response cycle, it asynchronously processes tasks that take a long time or do not require an immediate response, such as sending emails, image processing, and data aggregation.
In a message queue-based architecture, when a Producer puts a task into the queue, a Worker consumes and processes it. RabbitMQ, Redis Queue, Amazon SQS, and Kafka are representative message brokers. Celery (Python), BullMQ (Node.js), and Sidekiq (Ruby) are Worker frameworks.
In Kubernetes, a Worker is deployed as a Deployment and automatically scaled according to queue length by the Horizontal Pod Autoscaler. A node that carries out the commands of the control plane is also called a Worker Node, which means a server that runs Pods.
In practice, retry logic on task failure (exponential backoff), a Dead Letter Queue (isolating tasks that failed processing), and ensuring idempotency (idempotency: the result is the same even if executed more than once) are important. Monitoring tracks queue length, processing time, and failure rate.
// BullMQ๋ฅผ ์ฌ์ฉํ Node.js Worker ์์
// queue.js - ํ ์ค์
import { Queue } from 'bullmq';
const connection = {
host: process.env.REDIS_HOST || 'localhost',
port: 6379,
};
// ์ด๋ฉ์ผ ๋ฐ์ก ํ
export const emailQueue = new Queue('email', { connection });
// ์ด๋ฏธ์ง ์ฒ๋ฆฌ ํ
export const imageQueue = new Queue('image-processing', {
connection,
defaultJobOptions: {
attempts: 3, // ์ต๋ 3๋ฒ ์ฌ์๋
backoff: {
type: 'exponential', // ์ง์ ๋ฐฑ์คํ
delay: 1000, // 1์ด๋ถํฐ ์์
},
removeOnComplete: 100, // ์๋ฃ๋ ์์
100๊ฐ๋ง ์ ์ง
removeOnFail: 500, // ์คํจํ ์์
500๊ฐ๋ง ์ ์ง
},
});
// producer.js - ์์
์ถ๊ฐ
export async function sendWelcomeEmail(userId, email) {
const job = await emailQueue.add('welcome', {
userId,
email,
template: 'welcome',
}, {
priority: 1, // ๋์ ์ฐ์ ์์
delay: 0, // ์ฆ์ ์คํ
jobId: `welcome-${userId}`, // ์ค๋ณต ๋ฐฉ์ง์ฉ ID
});
console.log(`Job ${job.id} added to queue`);
return job;
}
export async function processImage(imageId, operations) {
return imageQueue.add('resize', {
imageId,
operations, // [{ type: 'resize', width: 800 }, { type: 'compress' }]
});
}
// worker.js - Worker ์ ์
import { Worker } from 'bullmq';
import { sendEmail } from './services/email';
import { resizeImage, compressImage } from './services/image';
// ์ด๋ฉ์ผ Worker
const emailWorker = new Worker('email', async (job) => {
console.log(`Processing email job ${job.id}`);
const { userId, email, template } = job.data;
// ๋ฉฑ๋ฑ์ฑ: ์ด๋ฏธ ๋ฐ์ก๋ ์ด๋ฉ์ผ์ธ์ง ํ์ธ
if (await isEmailAlreadySent(userId, template)) {
console.log(`Email already sent to ${email}`);
return { status: 'skipped', reason: 'already_sent' };
}
await sendEmail({
to: email,
template,
data: { userId },
});
await markEmailAsSent(userId, template);
return { status: 'sent', email };
}, {
connection,
concurrency: 5, // ๋์ ์ฒ๋ฆฌ ์
});
// ์ด๋ฒคํธ ํธ๋ค๋ง
emailWorker.on('completed', (job, result) => {
console.log(`Job ${job.id} completed:`, result);
});
emailWorker.on('failed', (job, err) => {
console.error(`Job ${job.id} failed:`, err.message);
// ์๋ฆผ ๋ฐ์ก, ๋ฉํธ๋ฆญ ๊ธฐ๋ก ๋ฑ
});
// ์ด๋ฏธ์ง ์ฒ๋ฆฌ Worker
const imageWorker = new Worker('image-processing', async (job) => {
const { imageId, operations } = job.data;
let image = await loadImage(imageId);
for (const op of operations) {
// ์งํ๋ฅ ์
๋ฐ์ดํธ
await job.updateProgress(operations.indexOf(op) / operations.length * 100);
if (op.type === 'resize') {
image = await resizeImage(image, op.width, op.height);
} else if (op.type === 'compress') {
image = await compressImage(image, op.quality);
}
}
const outputPath = await saveImage(image);
return { outputPath };
}, {
connection,
concurrency: 2, // ๋ฆฌ์์ค ๋ง์ด ์ฐ๋ฏ๋ก ์ ํ
});
// Kubernetes Deployment (worker.yaml)
/*
apiVersion: apps/v1
kind: Deployment
metadata:
name: email-worker
spec:
replicas: 3
selector:
matchLabels:
app: email-worker
template:
spec:
containers:
- name: worker
image: myapp/worker:v1.0.0
command: ["node", "worker.js"]
env:
- name: REDIS_HOST
valueFrom:
configMapKeyRef:
name: redis-config
key: host
resources:
requests:
cpu: 100m
memory: 256Mi
*/
Senior: "The order completion email is affecting the API response time. We should separate it into a Worker and process it asynchronously."
Junior: "If we put it in the queue but the Worker dies, won't the email not be sent?"
Senior: "Set up Redis persistence and add retry logic for task failures. Tasks that keep failing get collected separately in the Dead Letter Queue so we can check them."
Interviewer: "How do you ensure idempotency in a message queue-based system?"
Candidate: "I assign a unique ID to each task and record the IDs of completed tasks in Redis or a DB. When a Worker receives a task, it first checks with this ID whether it has already been processed, and skips it if it is a duplicate. Even if a task is resent or retried due to network problems, the same result is guaranteed."
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free
Reviewer: "This is a Worker that calls an external API, but there is no timeout or retry configuration."
Developer: "I'll set the axios timeout to 30 seconds, and add attempts: 3 and exponential backoff in BullMQ. After 3 failures, the task will go to the DLQ."