๐Ÿ”ง DevOps

Worker

Worker

A process that handles background tasks. Kubernetes worker node.

Detailed Explanation

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.

Code Example

// 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
*/

How It's Said in Practice

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."

Cautions

Learn More