Communitygithub.com

curiositech/windags-skills

バックグラウンドジョブ処理のエキスパート。Bull/BullMQ(Redis)、Celery、クラウドキューを使用し、リトライ、スケジューリング、優先度キュー、ワーカー管理を実装します。非同期タスク処理、メールキャンペーン、レポート生成、バッチ操作に使用します。「background job」「async task」「queue」「worker」「BullMQ」「Celery」で起動します。リアルタイムWebSocket通信、同期API呼び出し、単純なsetTimeout操作には使用しません。

windags-skills とは?

このスキルは、バックグラウンドジョブシステムの設計と実装、特にNode.jsのBullMQ、PythonのCelery、AWS SQSやGoogle Cloud Tasksなどのクラウドネイティブキューに焦点を当てています。メール送信やレポート生成、ビデオトランスコーディングなどの長時間実行タスクをAPIレスポンスをブロックせずに処理する方法を提供します。リトライ戦略、優先度キュー、レート制限、べき等性、ワーカースケーリング、デッドレターキューなどの重要なパターンとアンチパターンを網羅し、本番環境で信頼性の高いジョブ処理を実現します。また、キュー深度監視や失敗ジョブ検査など、モニタリングと可観測性のベストプラクティスも含まれています。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/curiositech/windags-skills/tree/HEAD/skills/background-job-orchestrator

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

バックグラウンドジョブオーケストレーター

APIレスポンスをブロックせずに長時間実行タスクを処理する、本番グレードのバックグラウンドジョブシステムの設計と実装のエキスパート。

使用するタイミング

✅ 使用するケース:

  • 長時間実行タスク(メール送信、レポート生成、画像処理)
  • バッチ操作(一括インポート、エクスポート、データ移行)
  • スケジュールタスク(日次ダイジェスト、クリーンアップジョブ、定期レポート)
  • リトライロジックが必要なタスク(外部API呼び出し、不安定な操作)
  • 優先度ベースの処理(プレミアムユーザー優先、重要なアラート)
  • レート制限操作(APIクォータ、サードパーティサービスの制限)

❌ 使用しないケース:

  • リアルタイム双方向通信(WebSocketを使用)
  • サブミリ秒のレイテンシ要件(インメモリキャッシュを使用)
  • 単純な遅延(setTimeoutで5秒未満は十分)
  • 同期APIレスポンス(リクエストハンドラ内でロジックを維持)

クイック判定ツリー

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

技術選択

Node.js: BullMQ(推奨 2024+)

使用するタイミング:

  • TypeScriptプロジェクト
  • スタックにRedisがすでにある
  • 高度な機能が必要(レート制限、優先度、繰り返しジョブ)

BullよりもBullMQを選ぶ理由:

  • Bull (v3) → BullMQ (v4+): TypeScriptによる完全な書き直し
  • より優れたRedis接続処理
  • 改良された並行性とパフォーマンス
  • 活発なメンテナンス(Bullはメンテナンスモード)

Python: Celery

使用するタイミング:

  • Python/Djangoプロジェクト
  • 分散タスク実行が必要
  • 複雑なワークフロー(チェーン、グループ、コード)

代替手段:

  • RQ (Redis Queue): よりシンプル、少ない機能
  • Dramatiq: モダン、エコシステムが小さい
  • Huey: 軽量、小規模プロジェクトに最適

クラウドネイティブ: AWS SQS、Google Cloud Tasks

使用するタイミング:

  • サーバーレスアーキテクチャ
  • Redis/RabbitMQを管理したくない
  • 配信保証とデッドレターキューが必要

よくあるアンチパターン

アンチパターン1: デッドレターキューがない

初心者の考え方: 「3回リトライして、静かに失敗させる」

問題: 失敗したジョブが可視性や復旧パスなしに消える。

正しいアプローチ:

// 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();

タイムライン:

  • 2020年以前: リトライして忘れる
  • 2020年以降: デッドレターキューが標準
  • 2024年以降: ジョブ失敗の可観測性が必須

アンチパターン2: 同期ジョブ処理

症状: APIエンドポイントがジョブの完了を待つ

問題:

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

なぜ間違っているか: タイムアウト、ユーザー体験の悪化、サーバーリソースの浪費

正しいアプローチ:

// ✅ 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);
});

アンチパターン3: べき等性がない

問題: ジョブが2回実行される → 二重請求、二重メール

なぜ起こるか:

  • 処理中にRedis接続が切断される
  • ジョブ完了前にワーカーがクラッシュする
  • ジョブタイムアウトがトリガーされ、まだ実行中にリトライが発生する

正しいアプローチ:

// ✅ 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;
});

アンチパターン4: レート制限がない

問題: サードパーティAPIを圧迫する、またはクォータを使い果たす

症状: Sendgrid、Stripeなどからの「Rate limit exceeded」エラー

正しいアプローチ:

// 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
  }
});

アンチパターン5: ワーカースケーリングを忘れる

問題: 単一ワーカーがキュー深度に追いつけない

症状: キューがバックログし、ジョブが数時間/日遅延する

正しいアプローチ:

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

モニタリング:

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

実装パターン

パターン1: メールキャンペーン

// 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
});

パターン2: スケジュールレポート

// 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 }]
  });
});

パターン3: ビデオトランスコーディングパイプライン

// 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
  });
});

モニタリングと可観測性

必須メトリクス

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

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

本番環境チェックリスト

□ デッドレターキューが設定されている
□ 指数バックオフ付きのリトライ戦略
□ ジョブタイムアウト制限が設定されている
□ サードパーティAPIのレート制限
□ 重要な操作のべき等性キー
□ ワーカー並行性の調整(CPUコア * 2)
□ 水平スケーリングが設定されている(複数ワーカー)
□ アラート付きキュー深度モニタリング
□ 失敗ジョブ検査ワークフロー
□ ログにジョブデータにPIIが含まれない
□ Redisの永続性が有効(AOFまたはRDB)
□ グレースフルシャットダウン処理(SIGTERM)

使用すべきか回避すべきかの判断

シナリオバックグラウンドジョブを使用するか?
サインアップ時にウェルカムメールを送信✅ はい - 2〜5秒かかる可能性あり
クレジットカードに請求⚠️ 場合による - 支払いプロバイダーのレイテンシに依存
PDFレポートを生成(30秒)✅ はい - 間違いなくバックグラウンド
DBからユーザープロファイルを取得❌ いいえ - ミリ秒、同期のまま
動画アップロードを処理(5分)✅ はい - 常にバックグラウンド
フォーム入力を検証❌ いいえ - 同期バリデーション
日次cronジョブ✅ はい - 繰り返しジョブを使用
リアルタイムチャットメッセージ❌ いいえ - WebSocketを使用

技術比較

機能BullMQCeleryAWS SQS
言語Node.jsPython任意 (HTTP API)
バックエンドRedisRedis/RabbitMQ/SQS管理型
優先度✅✅✅
レート制限✅❌✅ (属性経由)
繰り返し/Cron✅✅ (celery-beat)❌ (EventBridgeを使用)
UIダッシュボードBull BoardFlowerCloudWatch
ワークフロー❌✅ (チェーン、グループ)❌
学習曲線中中低
コストRedisホスティングRedisホスティング100万リクエストあたり$0.40

参考資料

  • /references/bullmq-patterns.md - BullMQの高度なパターンと例
  • /references/celery-workflows.md - Celeryのチェーン、グループ、コード
  • /references/job-observability.md - モニタリング、アラート、デバッグ

スクリプト

  • scripts/setup_bullmq.sh - BullMQをRedisで初期化
  • 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.

関連スキル