Communitygithub.com

背景任務編排器

專精於使用 Bull/BullMQ (Redis)、Celery 和雲端佇列來設計背景工作處理系統。實作重試、排程、優先級佇列和工作管理。用於非同步任務處理、電子郵件行銷活動、報告生成、批次操作。

背景任務編排器 是什麼?

此技能「背景任務編排器」專為需要處理耗時任務而不阻塞 API 回應的情境而設計,無論是開發 Node.js 還是 Python 應用程式。它主要支援三種技術:BullMQ (Node.js, TypeScript)、Celery (Python) 以及雲端原生解決方案如 AWS SQS 和 Google Cloud Tasks。技能的核心價值在於教授生產級背景工作的設計與實作模式,涵蓋從技術選擇決策樹(何時使用背景任務 vs. 保持同步)到常見反模式(如缺少死信佇列、缺少冪等性、缺少速率限制)的全面指南。它提供了具體的程式碼範例,說明如何在 BullMQ 和 Celery 中設定佇列、工作器、重試策略、排程(使用 cron 表達式)以及優先級佇列。此外,它還包括實用的實作模式(如電子郵件行銷活動、排程報告、影片轉碼管道)、監控與可觀測性建議(如佇列深度指標、Bull Board UI)、一份生產就緒檢查清單,以及一份技術比較表格。此技能特別警告不要用於即時 WebSocket 通訊、同步 API 呼叫或簡單的 setTimeout 延遲。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/curiositech/windags-skills/tree/HEAD/skills/background-job-orchestrator

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

背景任務編排器 是做什麼的?

專精於設計與實作生產級的背景任務系統,能夠處理長時間運行的任務,而不阻塞 API 回應。

使用時機

✅ 適用於:

  • 長時間任務(發送電子郵件、生成報告、圖片處理)
  • 批次操作(大量匯入、匯出、資料遷移)
  • 排程任務(每日摘要、清理任務、定期報告)
  • 需要重試邏輯的任務(外部 API 呼叫、不穩定操作)
  • 基於優先級的處理(高級用戶優先、關鍵警報)
  • 受速率限制的操作(API 配額、第三方服務限制)

❌ 不適用於:

  • 即時雙向通訊(請使用 WebSocket)
  • 次毫秒延遲需求(請使用記憶體快取)
  • 簡單延遲(低於 5 秒可使用 setTimeout)
  • 同步 API 回應(請將邏輯保留在請求處理程式中)

快速決策樹

這個任務是否:
├── 需要超過 5 秒? → 背景任務
├── 失敗時需要重試? → 背景任務
├── 依照排程執行? → 背景任務(cron 模式)
├── 會阻擋用戶互動? → 背景任務
├── 需要批次處理? → 背景任務
└── 需要立即回應? → 保持同步

技術選擇

Node.js:BullMQ(2024 年推薦)

使用時機:

  • TypeScript 專案
  • 已使用 Redis
  • 需要進階功能(速率限制、優先級、可重複任務)

為何選擇 BullMQ 而非 Bull:

  • Bull (v3) → BullMQ (v4+):使用 TypeScript 完全重寫
  • 更好的 Redis 連線處理
  • 改進的並發性和效能
  • 積極維護(Bull 處於維護模式)

Python:Celery

使用時機:

  • Python/Django 專案
  • 需要分散式任務執行
  • 複雜工作流程(chains、groups、chords)

替代方案:

  • RQ (Redis Queue):更簡單,功能較少
  • Dramatiq:現代化,生態系統較小
  • Huey:輕量級,適合小型專案

雲端原生:AWS SQS、Google Cloud Tasks

使用時機:

  • 無伺服器架構
  • 不想管理 Redis/RabbitMQ
  • 需要保證交付和死信佇列

常見反模式

反模式 1:沒有死信佇列

新手思維:「重試 3 次,然後靜默失敗」

問題:失敗的任務消失,無任何可見性或恢復途徑。

正確做法:

// BullMQ 搭配死信佇列
const queue = new Queue('email-queue', {
  connection: redis,
  defaultJobOptions: {
    attempts: 3,
    backoff: {
      type: 'exponential',
      delay: 2000
    },
    removeOnComplete: 100, // 保留最近 100 個成功的
    removeOnFail: false     // 保留所有失敗的以供檢查
  }
});

// 監控失敗任務
const failedJobs = await queue.getFailed();

時間線:

  • 2020 年前:重試並遺忘
  • 2020 年後:死信佇列成為標準
  • 2024 年後:任務失敗的可觀測性成為必要

反模式 2:同步任務處理

症狀:API 端點等待任務完成

問題:

// ❌ 錯誤 - 阻塞 API 回應
app.post('/send-email', async (req, res) => {
  await sendEmail(req.body.to, req.body.subject);
  res.json({ success: true });
});

為何錯誤:逾時、用戶體驗差、浪費伺服器資源

正確做法:

// ✅ 正確 - 立即加入佇列並回應
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'
  });
});

// 獨立工作器處理任務
worker.process('send', async (job) => {
  await sendEmail(job.data.to, job.data.subject);
});

反模式 3:沒有冪等性

問題:任務執行兩次 → 重複扣款、重複發送電子郵件

發生原因:

  • Redis 連線在處理中斷線
  • 工作器在任務完成前崩潰
  • 任務超時觸發重試,但原任務仍在運行

正確做法:

// ✅ 具備去重鍵的冪等任務
await queue.add('charge-payment', {
  userId: 123,
  amount: 50.00
}, {
  jobId: `payment-${orderId}`, // 防止重複
  attempts: 3
});

// 在工作器中:檢查是否已處理
worker.process('charge-payment', async (job) => {
  const { userId, amount } = job.data;

  // 檢查冪等性
  const existing = await db.payments.findOne({
    jobId: job.id
  });
  if (existing) {
    return existing; // 已處理
  }

  // 處理付款
  const result = await stripe.charges.create({...});

  // 儲存冪等性紀錄
  await db.payments.create({
    jobId: job.id,
    result
  });

  return result;
});

反模式 4:沒有速率限制

問題:讓第三方 API 不堪負荷或耗盡配額

症狀:來自 Sendgrid、Stripe 等的「速率限制超標」錯誤

正確做法:

// BullMQ 速率限制
const queue = new Queue('api-calls', {
  limiter: {
    max: 100,        // 最多 100 個任務
    duration: 60000  // 每 60 秒
  }
});

// 或:基於優先級的速率限制
await queue.add('send-email', data, {
  priority: user.isPremium ? 1 : 10,
  rateLimiter: {
    max: user.isPremium ? 1000 : 100,
    duration: 3600000 // 每小時
  }
});

反模式 5:忘記工作器擴展

問題:單一工作器無法跟上佇列深度

症狀:佇列積壓,任務延遲數小時/天

正確做法:

// 水平擴展,使用多個工作器
const worker = new Worker('email-queue', async (job) => {
  await processEmail(job.data);
}, {
  connection: redis,
  concurrency: 5  // 每個工作器同時處理 5 個任務
});

// 運行多個工作器程序(PM2、Kubernetes 等)
// 每個工作器處理 concurrency * num_workers 個任務

監控:

// 設定佇列深度警報
setInterval(async () => {
  const waiting = await queue.getWaitingCount();
  if (waiting > 1000) {
    alert('佇列深度超過 1000,請擴展工作器!');
  }
}, 60000);

實作模式

模式 1:電子郵件行銷活動

// 佇列設定
const emailQueue = new Queue('email-campaign', { connection: redis });

// 加入批次
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);
}

// 具備重試邏輯的工作器
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; // 重試
    }
    // 無效的電子郵件,不重試
    console.error(`用戶 ${userId} 的電子郵件無效`);
  }
}, {
  connection: redis,
  concurrency: 10
});

模式 2:排程報告

// 每天早上 9 點的報告
await queue.add('daily-report', {
  type: 'sales',
  recipients: ['[email protected]']
}, {
  repeat: {
    pattern: '0 9 * * *', // Cron 語法
    tz: 'America/New_York'
  }
});

// 工作器生成並寄送報告
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: `每日 ${type} 報告`,
    attachments: [{ filename: 'report.pdf', content: pdf }]
  });
});

模式 3:影片轉碼管道

// 多階段任務,含進度追蹤
await videoQueue.add('transcode', {
  videoId: 123,
  formats: ['720p', '1080p', '4k']
}, {
  attempts: 2,
  timeout: 3600000 // 1 小時逾時
});

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

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

    // 更新進度
    await job.updateProgress((i / formats.length) * 100);

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

  await job.updateProgress(100);
});

// 客戶端輪詢進度
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
  });
});

監控與可觀測性

必要指標

// 佇列健康儀表板
async function getQueueMetrics() {
  const [waiting, active, completed, failed, delayed] = await Promise.all([
    queue.getWaitingCount(),
    queue.getActiveCount(),
    queue.getCompletedCount(),
    queue.getFailedCount(),
    queue.getDelayedCount()
  ]);

  return {
    waiting,    // 等待處理的任務
    active,     // 正在處理的任務
    completed,  // 成功完成
    failed,     // 重試後失敗
    delayed,    // 排程在未來
    health: waiting < 1000 && failed < 100 ? 'healthy' : 'degraded'
  };
}

BullMQ Board (UI)

// 開發環境:視覺化監控任務
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());
// 造訪 http://localhost:3000/admin/queues

生產就緒檢查清單

□ 已設定死信佇列
□ 已設定指數退避重試策略
□ 已設定任務逾時限制
□ 已對第三方 API 設定速率限制
□ 關鍵操作具有冪等性鍵
□ 工作器並發數已調優 (CPU 核心數 * 2)
□ 已設定水平擴展(多個工作器)
□ 已設定佇列深度監控與警報
□ 已建立失敗任務檢查工作流程
□ 日誌中的任務資料不包含 PII
□ 已啟用 Redis 持久化(AOF 或 RDB)
□ 已處理優雅關閉(SIGTERM)

使用 vs 避免時機

情境使用背景任務?
註冊時發送歡迎郵件✅ 是 - 可能需要 2-5 秒
信用卡扣款⚠️ 可能 - 取決於支付提供者延遲
生成 PDF 報告(30 秒)✅ 是 - 絕對要用背景任務
從資料庫獲取用戶資料❌ 否 - 毫秒級,保持同步
處理影片上傳(5 分鐘)✅ 是 - 永遠使用背景任務
驗證表單輸入❌ 否 - 同步驗證
每日 Cron 任務✅ 是 - 使用可重複任務
即時聊天訊息❌ 否 - 使用 WebSocket

技術比較

功能BullMQCeleryAWS SQS
語言Node.jsPython任意 (HTTP API)
後端RedisRedis/RabbitMQ/SQS託管
優先級✅✅✅
速率限制✅❌✅ (透過屬性)
重複/Cron✅✅ (celery-beat)❌ (使用 EventBridge)
UI 儀表板Bull BoardFlowerCloudWatch
工作流程❌✅ (chains, groups)❌
學習曲線中等中等低
成本Redis 託管費Redis 託管費$0.40/百萬請求

參考資料

  • /references/bullmq-patterns.md - 進階 BullMQ 模式與範例
  • /references/celery-workflows.md - Celery chains、groups 和 chords
  • /references/job-observability.md - 監控、警報與除錯

腳本

  • scripts/setup_bullmq.sh - 使用 Redis 初始化 BullMQ
  • scripts/queue_health_check.ts - 佇列指標儀表板
  • scripts/retry_failed_jobs.ts - 大量重試失敗任務

此技能引導:背景任務實作 | 佇列架構 | 重試策略 | 工作器擴展 | 任務可觀測性

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

curiositech/windags-skills

Expert in 2000s-era music visualization (Milkdrop, AVS, Geiss) and modern WebGL implementations. Specializes in Butterchurn integration, Web Audio API AnalyserNode FFT data, GLSL shaders for audio-reactive visuals, and psychedelic generative art. Activate on "Milkdrop", "music visualization", "WebGL visualizer", "Butterchurn", "audio reactive", "FFT visualization", "spectrum analyzer". NOT for simple bar charts/waveforms (use basic canvas), video editing, or non-audio visuals.

curiositech/windags-skills

Expert legal research agent for finding and scraping expungement data state by state. Knows authoritative sources, URL patterns, Firecrawl configuration, and 2026 legal landscape.

curiositech/windags-skills

Expert in 3D computer vision labeling tools, workflows, and AI-assisted annotation for LiDAR, point clouds, and sensor fusion. Covers SAM4D/Point-SAM, human-in-the-loop architectures, and vertical-specific training strategies. Activate on '3D labeling', 'point cloud annotation', 'LiDAR labeling', 'SAM 3D', 'SAM4D', 'sensor fusion annotation', '3D bounding box', 'semantic segmentation point cloud'. NOT for 2D image labeling (use clip-aware-embeddings), general ML training (use ml-engineer), video annotation without 3D (use computer-vision-pipeline), or VLM prompt engineering (use prompt-engineer).

curiositech/windags-skills

Implement WCAG 2.2 AA/AAA compliance with automated testing, keyboard navigation, screen reader support, and focus management. Activate on: accessibility audit, WCAG compliance, keyboard navigation, screen reader, aria attributes, axe-core, focus trap. NOT for: design-level accessibility review (use design-accessibility-auditor), color contrast only (use css-in-js-architect).

curiositech/windags-skills

Time-blind friendly planning, executive function support, and daily structure for ADHD brains. Specializes in realistic time estimation, dopamine-aware task design, and building systems that actually work for neurodivergent minds.

curiositech/windags-skills

Designs digital experiences for ADHD brains using neuroscience research and UX principles. Expert in reducing cognitive load, time blindness solutions, dopamine-driven engagement, and compassionate design patterns. Activate on 'ADHD design', 'cognitive load', 'accessibility', 'neurodivergent UX', 'time blindness', 'dopamine-driven', 'executive function'. NOT for general accessibility (WCAG only), neurotypical UX design, or simple UI styling without ADHD context.

curiositech/windags-skills

>- Apply crisis decision-making research to agent routing, uncertainty triage, and coordination failure analysis in time-pressured systems. Use when diagnosing handoff failures, analytical paralysis, or expert judgment under incomplete information. NOT for routine coding, simple CRUD design, or static single-agent tasks with complete information.

curiositech/windags-skills

Extend and modify the admin dashboard, developer portal, and operations console. Use when adding new admin tabs, metrics, monitoring features, or internal tools. Activates for dashboard development, analytics, user management, and internal tooling.

curiositech/windags-skills

Conversation patterns and interaction protocols for multi-agent systems. Covers request/response, pub/sub, blackboard, delegation chains, debate, critique, consensus, fan-out/fan-in, supervisor-worker, and peer negotiation. Deep analysis of AutoGen conversation patterns, CrewAI delegation, LangGraph state passing, and FIPA-ACL performatives. Teaches how to design what agents say to each other and in what order. Activate on: "agent conversation", "agent protocol", "multi-agent debate", "agent delegation", "supervisor worker pattern", "agent voting", "consensus protocol", "fan-out fan-in", "agent negotiation", "blackboard pattern", "agent dialogue", "conversation topology", "agent handoff". NOT for: wire format or serialization (use agent-interchange-formats), orchestration infrastructure (use agentic-infrastructure-2026), single agent behavior (use agentic-patterns).

curiositech/windags-skills

Meta-agent for creating new custom agents, skills, and MCP integrations. Expert in agent design, MCP development, skill architecture, and rapid prototyping. Activate on 'create agent', 'new skill', 'MCP server', 'custom tool', 'agent design'. NOT for using existing agents (invoke them directly), general coding (use language-specific skills), or infrastructure setup (use deployment-engineer).

curiositech/windags-skills

AI-powered calendar management and agent-based scheduling coordination. Covers calendar APIs (Google Calendar, CalDAV/iCal), AI scheduling assistants (Reclaim, Clockwise, Motion, Cal.com), building custom calendar agents with MCP, multi-calendar merging, timezone management, focus block protection, meeting fatigue detection, and agent-to-agent meeting negotiation protocols. Activate on: "calendar agent", "AI scheduling", "calendar coordination", "meeting scheduling", "calendar API", "focus time protection", "calendar optimization", "Google Calendar MCP", "Reclaim", "Clockwise", "Motion", "Cal.com", "smart scheduling", "calendar-aware agent", "timezone scheduling", "agent negotiation meetings". NOT for: manual calendar UI component design (use form-validation-architect), project management scheduling or Gantt charts (use project-management-guru-adhd), general time-tracking or pomodoro apps (use adhd-daily-planner for time-awareness), building the agent itself from scratch (use agent-creator).

curiositech/windags-skills

Build and adopt production AI agent infrastructure in 2026. Covers framework selection (LangGraph, CrewAI, AutoGen, MCP), orchestration patterns, evaluation, observability, memory systems, and tool use. Also covers the SOCIAL dimension: how to sell agent infrastructure internally, change management, measuring ROI, building trust in autonomous systems, and scaling adoption across teams. Activate on: "agent infrastructure", "agent framework comparison", "which agent framework", "sell AI tools internally", "agent adoption", "agent observability", "agent evaluation", "MCP architecture", "agentic mesh", "enterprise AI agents", "AI change management", "agent ROI". NOT for: building specific agents (use ai-engineer), designing agent behavior patterns (use agentic-patterns), prompt tuning (use prompt-engineer).

curiositech/windags-skills

Fundamental patterns for effective agentic behavior. Teaches decomposition, tool orchestration, error recovery, context management, quality self-assessment, and knowing when to stop. Model-agnostic principles that make any agent more effective regardless of domain. Activate on: "how should I structure this agent", "agentic workflow", "agent patterns", "multi-step task", "tool orchestration", "/agentic-patterns", "decompose this", "agent best practices", "chain of actions", "when should the agent stop", "agent loop design". NOT for: creating agent infrastructure (use agent-creator), building DAGs (use windags-architect), specific tool implementation.

curiositech/windags-skills

Automated discovery and matching of agent skills for dynamic task routing and capability assessment

curiositech/windags-skills

Cryptographic security for agentic systems — zero-trust agent networking, signed message envelopes (JWS/JWE), capability-based security (ocaps), Merkle tree audit trails, WASM sandboxing, and formal verification. Covers CLI dev tool security, mTLS between agents, permission boundaries (least privilege for AI agents), and supply chain security for skills/plugins. Activate on: "agent security", "zero trust agents", "secure agent communication", "capability-based security", "ocap", "signed messages between agents", "agent audit trail", "sandbox agent execution", "agent permissions", "mTLS agents", "cryptographic verification", "agent supply chain", "OWASP agentic", "prove agent did X", "tamper-proof agent logs". NOT for: application-level SAST scanning (use security-auditor), network firewall rules (use infrastructure), SOC2/HIPAA compliance (organizational), or prompt injection defense (use prompt-engineer).

curiositech/windags-skills

Data structures and serialization formats for agent-to-agent communication. Covers message envelopes, structured output schemas, capability declarations, task handoff payloads, error/retry signaling, and context windows as data structures. Deep comparison of A2A protocol, MCP, OpenAI function calling, and LangChain message types. Teaches when to use rigid schemas vs free-form with validation, typed vs untyped, streaming vs batch. Activate on: "agent message format", "agent communication schema", "agent-to-agent protocol", "A2A protocol", "MCP message format", "structured output for agents", "agent interop", "interchange format", "agent serialization", "task handoff format", "capability declaration". NOT for: what agents say to each other (use agent-conversation-protocols), orchestration topology (use multi-agent-coordination), building agent infrastructure (use agentic-infrastructure-2026).

curiositech/windags-skills

Logic-based agent programming language implementing BDI architecture for practical autonomous agent development

curiositech/windags-skills

>- Design AgentSpeak(L)-style BDI agents with context-guarded plans, selection functions, and intention stacks. Use for interruptible autonomy, agent policy, and multi-agent orchestration in dynamic environments. NOT for simple rule engines, static planners, or centralized workflows.

curiositech/windags-skills

Foundational concurrent computation model where actors communicate exclusively through asynchronous message passing

curiositech/windags-skills

license: Apache-2.0 NOT for unrelated tasks outside this domain.

相關技能