К основному содержанию
скилл CX Codex

background-job-orchestrator — скилл для Claude Code: обзор

Скилл background-job-orchestrator помогает настроить фоновые очереди на BullMQ или Celery. Переносит тяжёлые операции из обработчиков API, добавляет повторные попытки и защищает сервис от перегрузок.

MIT 198 установок ★ 274 обновлён 2026-10-30

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add curiositech/some_claude_skills --skill background-job-orchestrator -a claude-code
Открыть на GitHub

Что делает background-job-orchestrator

Скилл учит агента проектировать архитектуру асинхронных задач без блокировки входящих HTTP-запросов. Он предлагает решения под выбранный стек: BullMQ для TypeScript и Redis, Celery для проектов на Python или управляемые сервисы AWS SQS и Google Cloud Tasks. Агент получает доступ к редактированию файлов через Read, Write и Edit, а также может вызывать пакетные менеджеры через Bash(npm:*,pip:*).

Внутри заложены готовые шаблоны для типовых проблем очередей. Инструкции помогают настроить очереди недоставленных сообщений (Dead Letter Queue), ключи идемпотентности против повторных списаний и рейт-лимиты для внешних API. При высоких нагрузках скилл подскажет, как настроить горизонтальное масштабирование воркеров и мониторинг глубины очередей.

Для очередей потребуется запущенный Redis. Без брокера сообщений запустить воркеры BullMQ или Celery невозможно. При этом скилл запрещает использовать фоновые очереди для WebSockets, синхронных ответов API и задач с субсекундной задержкой.

Какие задачи решает

  • перенести отправку писем и построение отчётов из API в асинхронный воркер
  • настроить повторные попытки с экспоненциальной задержкой и Dead Letter Queue
  • исключить повторные операции с помощью ключей идемпотентности
  • ограничить частоту вызовов внешних API на уровне очередей

Примеры запросов агенту

  • Перенеси генерацию отчётов в фоновый воркер на BullMQ с Redis.
  • Настрой очередь Celery для рассылки писем с повторами и dead letter queue.
  • Добавь рейт-лимиты и проверку идемпотентности в фоновые задачи BullMQ.

Как установить background-job-orchestrator

1Через Skills CLI (Vercel)

npx skills add curiositech/some_claude_skills --skill background-job-orchestrator -a claude-code

2Вручную: положить файлы

~/.claude/skills/background-job-orchestrator/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/background-job-orchestrator/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о background-job-orchestrator

Как установить background-job-orchestrator в Claude Code?

Запустите команду npx skills add curiositech/some_claude_skills --skill background-job-orchestrator -a claude-code. Файл скилла будет сохранён в ~/.claude/skills/background-job-orchestrator/SKILL.md.

Что делает background-job-orchestrator?

Скилл направляет агента при разработке надёжных фоновых воркеров. Он внедряет очереди задач, планирование по расписанию, защиту от дублирования и изоляцию сбойных заданий.

Для каких задач этот скилл не подходит?

Его не стоит использовать для двусторонней связи через WebSockets, синхронных HTTP-ответов и операций с задержкой менее секунды. Для простых задержек до пяти секунд авторы рекомендуют обычный setTimeout.

Исходный текст

SKILL.md · MIT
---
name: background-job-orchestrator
description: Expert in background job processing with Bull/BullMQ (Redis), Celery, and cloud queues. Implements retries, scheduling, priority queues, and worker management. Use for async task processing,
  email campaigns, report generation, batch operations. Activate on "background job", "async task", "queue", "worker", "BullMQ", "Celery". NOT for real-time WebSocket communication, synchronous API calls,
  or simple setTimeout operations.
allowed-tools: Read,Write,Edit,Bash(npm:*,pip:*)
metadata:
  category: DevOps & Site Reliability
  tags:
  - background
  - job
  - orchestrator
  - background-job
  - async-task
  pairs-with:
  - skill: data-pipeline-engineer
    reason: Background jobs are the execution layer for ETL/ELT data pipeline stages
  - skill: site-reliability-engineer
    reason: Job queue health monitoring and failure alerting are core SRE concerns
  - skill: error-handling-patterns
    reason: Retry logic, dead letter queues, and failure recovery are critical for background job reliability
---

# Background Job Orchestrator

Expert in designing and implementing production-grade background job systems that handle long-running tasks without blocking API responses.

## When to Use

✅ **Use for**:
- Long-running tasks (email sends, report generation, image processing)
- Batch operations (bulk imports, exports, data migrations)
- Scheduled tasks (daily digests, cleanup jobs, recurring reports)
- Tasks requiring retry logic (external API calls, flaky operations)
- Priority-based processing (premium users first, critical alerts)
- Rate-limited operations (API quotas, third-party service limits)

❌ **NOT for**:
- Real-time bidirectional communication (use WebSockets)
- Sub-second latency requirements (use in-memory caching)
- Simple delays (setTimeout is fine for <5 seconds)
- Synchronous API responses (keep logic in request handler)

## Quick Decision Tree

```
Does this task:
├── Take >5 seconds? → Background job
├── Need to retry on failure? → Background job
├── Run on a schedule? → Background job (cron pattern)
├── Block user interaction? → Background job
├── Process in batches? → Background job
└── Return immediately? → Keep synchronous
```

---

## Technology Selection

### Node.js: BullMQ (Recommended 2024+)

**When to use**:
- TypeScript project
- Redis already in stack
- Need advanced features (rate limiting, priorities, repeatable jobs)

**Why BullMQ over Bull**:
- Bull (v3) → BullMQ (v4+): Complete rewrite in TypeScript
- Better Redis connection handling
- Improved concurrency and performance
- Active maintenance (Bull is in maintenance mode)

### Python: Celery

**When to use**:
- Python/Django project
- Need distributed task execution
- Complex workflows (chains, groups, chords)

**Alternatives**:
- **RQ** (Redis Queue): Simpler, fewer features
- **Dramatiq**: Modern, less ecosystem
- **Huey**: Lightweight, good for small projects

### Cloud-Native: AWS SQS, Google Cloud Tasks

**When to use**:
- Serverless architecture
- Don't want to manage Redis/RabbitMQ
- Need guaranteed delivery and dead-letter queues

---

## Common Anti-Patterns

### Anti-Pattern 1: No Dead Letter Queue

**Novice thinking**: "Retry 3 times, then fail silently"

**Problem**: Failed jobs disappear with no visibility or recovery path.

**Correct approach**:
```typescript
// BullMQ with dead letter queue
const queue = new Queue('email-queue', {
  connection: redis,
  defaultJobOptions: {
    attempts: 3,
    backoff: {
      type: 'exponential',
      delay: 2000
    },
    removeOnComplete: 100, // Keep last 100 successful
    removeOnFail: false     // Keep all failed for inspection
  }
});

// Monitor failed jobs
const failedJobs = await queue.getFailed();
```

**Timeline**:
- Pre-2020: Retry and forget
- 2020+: Dead letter queues standard
- 2024+: Observability for job failures required

---

### Anti-Pattern 2: Synchronous Job Processing

**Symptom**: API endpoint waits for job completion

**Problem**:
```typescript
// ❌ WRONG - Blocks API response
app.post('/send-email', async (req, res) => {
  await sendEmail(req.body.to, req.body.subject);
  res.json({ success: true });
});
```

**Why wrong**: Timeout, poor UX, wastes server resources

**Correct approach**:
```typescript
// ✅ RIGHT - Queue and return immediately
app.post('/send-email', async (req, res) => {
  const job = await emailQueue.add('send', {
    to: req.body.to,
    subject: req.body.subject
  });

  res.json({
    success: true,
    jobId: job.id,
    status: 'queued'
  });
});

// Separate worker processes the job
worker.process('send', async (job) => {
  await sendEmail(job.data.to, job.data.subject);
});
```

---

### Anti-Pattern 3: No Idempotency

**Problem**: Job runs twice → duplicate charges, double emails

**Why it happens**:
- Redis connection drops mid-processing
- Worker crashes before job completion
- Job timeout triggers retry while still running

**Correct approach**:
```typescript
// ✅ Idempotent job with deduplication key
await queue.add('charge-payment', {
  userId: 123,
  amount: 50.00
}, {
  jobId: `payment-${orderId}`, // Prevents duplicates
  attempts: 3
});

// In worker: Check if already processed
worker.process('charge-payment', async (job) => {
  const { userId, amount } = job.data;

  // Check idempotency
  const existing = await db.payments.findOne({
    jobId: job.id
  });
  if (existing) {
    return existing; // Already processed
  }

  // Process payment
  const result = await stripe.charges.create({...});

  // Store idempotency record
  await db.payments.create({
    jobId: job.id,
    result
  });

  return result;
});
```

---

### Anti-Pattern 4: No Rate Limiting

**Problem**: Overwhelm third-party APIs or exhaust quotas

**Symptom**: "Rate limit exceeded" errors from Sendgrid, Stripe, etc.

**Correct approach**:
```typescript
// BullMQ rate limiting
const queue = new Queue('api-calls', {
  limiter: {
    max: 100,        // Max 100 jobs
    duration: 60000  // Per 60 seconds
  }
});

// Or: Priority-based rate limits
await queue.add('send-email', data, {
  priority: user.isPremium ? 1 : 10,
  rateLimiter: {
    max: user.isPremium ? 1000 : 100,
    duration: 3600000 // Per hour
  }
});
```

---

### Anti-Pattern 5: Forgetting Worker Scaling

**Problem**: Single worker can't keep up with queue depth

**Symptom**: Queue backs up, jobs delayed hours/days

**Correct approach**:
```typescript
// Horizontal scaling with multiple workers
const worker = new Worker('email-queue', async (job) => {
  await processEmail(job.data);
}, {
  connection: redis,
  concurrency: 5  // Process 5 jobs concurrently per worker
});

// Run multiple worker processes (PM2, Kubernetes, etc.)
// Each worker processes concurrency * num_workers jobs
```

**Monitoring**:
```typescript
// Set up alerts for queue depth
setInterval(async () => {
  const waiting = await queue.getWaitingCount();
  if (waiting > 1000) {
    alert('Queue depth exceeds 1000, scale workers!');
  }
}, 60000);
```

---

## Implementation Patterns

### Pattern 1: Email Campaigns

```typescript
// Queue setup
const emailQueue = new Queue('email-campaign', { connection: redis });

// Enqueue batch
async function sendCampaign(userIds: number[], template: string) {
  const jobs = userIds.map(userId => ({
    name: 'send',
    data: { userId, template },
    opts: {
      attempts: 3,
      backoff: { type: 'exponential', delay: 5000 }
    }
  }));

  await emailQueue.addBulk(jobs);
}

// Worker with retry logic
const worker = new Worker('email-campaign', async (job) => {
  const { userId, template } = job.data;

  const user = await db.users.findById(userId);
  const email = renderTemplate(template, user);

  try {
    await sendgrid.send({
      to: user.email,
      subject: email.subject,
      html: email.body
    });
  } catch (error) {
    if (error.code === 'ECONNREFUSED') {
      throw error; // Retry
    }
    // Invalid email, don't retry
    console.error(`Invalid email for user ${userId}`);
  }
}, {
  connection: redis,
  concurrency: 10
});
```

### Pattern 2: Scheduled Reports

```typescript
// Daily report at 9 AM
await queue.add('daily-report', {
  type: 'sales',
  recipients: ['[email protected]']
}, {
  repeat: {
    pattern: '0 9 * * *', // Cron syntax
    tz: 'America/New_York'
  }
});

// Worker generates and emails report
worker.process('daily-report', async (job) => {
  const { type, recipients } = job.data;

  const data = await generateReport(type);
  const pdf = await createPDF(data);

  await emailQueue.add('send', {
    to: recipients,
    subject: `Daily ${type} Report`,
    attachments: [{ filename: 'report.pdf', content: pdf }]
  });
});
```

### Pattern 3: Video Transcoding Pipeline

```typescript
// Multi-stage job with progress tracking
await videoQueue.add('transcode', {
  videoId: 123,
  formats: ['720p', '1080p', '4k']
}, {
  attempts: 2,
  timeout: 3600000 // 1 hour timeout
});

worker.process('transcode', async (job) => {
  const { videoId, formats } = job.data;

  for (let i = 0; i < formats.length; i++) {
    const format = formats[i];

    // Update progress
    await job.updateProgress((i / formats.length) * 100);

    // Transcode
    await ffmpeg.transcode(videoId, format);
  }

  await job.updateProgress(100);
});

// Client polls for progress
app.get('/videos/:id/status', async (req, res) => {
  const job = await queue.getJob(req.params.jobId);
  res.json({
    state: await job.getState(),
    progress: job.progress
  });
});
```

---

## Monitoring & Observability

### Essential Metrics

```typescript
// Queue health dashboard
async function getQueueMetrics() {
  const [waiting, active, completed, failed, delayed] = await Promise.all([
    queue.getWaitingCount(),
    queue.getActiveCount(),
    queue.getCompletedCount(),
    queue.getFailedCount(),
    queue.getDelayedCount()
  ]);

  return {
    waiting,    // Jobs waiting to be processed
    active,     // Jobs currently processing
    completed,  // Successfully completed
    failed,     // Failed after retries
    delayed,    // Scheduled for future
    health: waiting < 1000 && failed < 100 ? 'healthy' : 'degraded'
  };
}
```

### BullMQ Board (UI)

```typescript
// Development: Monitor jobs visually
import { createBullBoard } from '@bull-board/api';
import { BullMQAdapter } from '@bull-board/api/bullMQAdapter';
import { ExpressAdapter } from '@bull-board/express';

const serverAdapter = new ExpressAdapter();

createBullBoard({
  queues: [
    new BullMQAdapter(emailQueue),
    new BullMQAdapter(videoQueue)
  ],
  serverAdapter
});

app.use('/admin/queues', serverAdapter.getRouter());
// Visit http://localhost:3000/admin/queues
```

---

## Production Checklist

```
□ Dead letter queue configured
□ Retry strategy with exponential backoff
□ Job timeout limits set
□ Rate limiting for third-party APIs
□ Idempotency keys for critical operations
□ Worker concurrency tuned (CPU cores * 2)
□ Horizontal scaling configured (multiple workers)
□ Queue depth monitoring with alerts
□ Failed job inspection workflow
□ Job data doesn't contain PII in logs
□ Redis persistence enabled (AOF or RDB)
□ Graceful shutdown handling (SIGTERM)
```

---

## When to Use vs Avoid

| Scenario | Use Background Jobs? |
|----------|---------------------|
| Send welcome email on signup | ✅ Yes - can take 2-5 seconds |
| Charge credit card | ⚠️ Maybe - depends on payment provider latency |
| Generate PDF report (30 seconds) | ✅ Yes - definitely background |
| Fetch user profile from DB | ❌ No - milliseconds, keep synchronous |
| Process video upload (5 minutes) | ✅ Yes - always background |
| Validate form input | ❌ No - synchronous validation |
| Daily cron job | ✅ Yes - use repeatable jobs |
| Real-time chat message | ❌ No - use WebSockets |

---

## Technology Comparison

| Feature | BullMQ | Celery | AWS SQS |
|---------|--------|--------|---------|
| Language | Node.js | Python | Any (HTTP API) |
| Backend | Redis | Redis/RabbitMQ/SQS | Managed |
| Priorities | ✅ | ✅ | ✅ |
| Rate Limiting | ✅ | ❌ | ✅ (via attributes) |
| Repeat/Cron | ✅ | ✅ (celery-beat) | ❌ (use EventBridge) |
| UI Dashboard | Bull Board | Flower | CloudWatch |
| Workflows | ❌ | ✅ (chains, groups) | ❌ |
| Learning Curve | Medium | Medium | Low |
| Cost | Redis hosting | Redis hosting | $0.40/million requests |

---

## References

- `/references/bullmq-patterns.md` - Advanced BullMQ patterns and examples
- `/references/celery-workflows.md` - Celery chains, groups, and chords
- `/references/job-observability.md` - Monitoring, alerting, and debugging

## Scripts

- `scripts/setup_bullmq.sh` - Initialize BullMQ with Redis
- `scripts/queue_health_check.ts` - Queue metrics dashboard
- `scripts/retry_failed_jobs.ts` - Bulk retry failed jobs

---

**This skill guides**: Background job implementation | Queue architecture | Retry strategies | Worker scaling | Job observability

© curiositech · MIT · curiositech/some_claude_skills

Похожие скиллы

Все скиллы по теме «Бэкенд и API» →
background-jobs-designer patricio0312rev Скилл background-jobs-designer для Claude Code проектирует очереди фоновых задач, повторы и мониторинг. Описывает работу с BullMQ, Celery и асинхронными воркерами. CX Codex +1 286установок background-job-processing aj-geddes Скилл background-job-processing для Claude Code и Codex настраивает фоновую обработку задач: очереди, воркеры, расписание и повторные попытки при сбоях. Письма, отчёты и большие выгрузки уходят из основного потока. CX Codex +1 490установок python-background-jobs Seth Hobson Скилл python-background-jobs для Claude Code выносит долгие Python-задачи из цикла запрос–ответ и обрабатывает их воркерами. Решает задачи очередей, экспортов, уведомлений и событийной архитектуры. CX Codex +1 11 137установок render-background-workers Render Скилл render-background-workers помогает настроить фоновые воркеры на Render: подключить очередь, поймать SIGTERM и не потерять задачи при деплое. CX Codex +1 432установок Background Jobs taste f Промпт Background Jobs taste для ChatGPT и Claude.ai задаёт инженерные правила надёжности для фоновых задач и очередей. Помогает проектировать воркеры с защитой от дублей, взаимных блокировок и зависаний. GP ChatGPT ★ 178 201звёзд репо queue-job-processor patricio0312rev Скилл queue-job-processor настраивает фоновые очереди задач на базе BullMQ и Redis, включая воркеры, повторные попытки и отслеживание прогресса. CX Codex +1 300установок

Из того же набора180

Весь набор →
supabase-admin Скилл supabase-admin для Claude Code администрирует Supabase: проектирует схемы, настраивает политики RLS и миграции, отлаживает запросы. Помогает менять структуру базы и выяснять причины пустой выборки. CX Codex +1 200установок playwright-e2e-tester Скилл playwright-e2e-tester помогает писать E2E-тесты на Playwright, настраивать Page Object Model и готовить пайплайны GitHub Actions. Пригодится при автоматизации веб-тестов и отлове регрессий интерфейса. CX Codex +1 200установок sober-addict-protector Скилл sober-addict-protector помогает вести ежедневные проверки трезвости, замечать триггеры и готовить план защиты от срыва. CX Codex +1 199установок product-appeal-analyzer Скилл product-appeal-analyzer оценивает, захочет ли целевая аудитория выбрать продукт: разбирает позиционирование, доверие и эмоциональный отклик. Используйте его для ревью лендинга или сообщений о продукте. CX Codex +1 199установок skill-logger Скилл skill-logger для Claude Code, Codex, Cursor и других платформ: фиксирует каждый запуск скилла, считает метрики качества и собирает сигналы для улучшений. CX Codex +1 197установок site-reliability-engineer Скилл site-reliability-engineer проверяет здоровье сборки Docusaurus: ищет ошибки в MDX, проверяет ссылки и помогает подготовить безопасный деплой. CX Codex +1 196установок skill-documentarian Скилл skill-documentarian синхронизирует навыки с документацией сайта, следит за метаданными, тегами и бейджами. Нужен при добавлении или проверке скиллов. CX Codex +1 196установок vr-avatar-engineer Скилл vr-avatar-engineer для Claude Code проектирует VR-аватары. Охватывает отслеживание мимики, сетевую синхронизацию и рендеринг кожи для Vision Pro, Quest и PC VR. CX Codex +1 195установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой