{"data":{"slug":"github-lobehub-lobehub-agents-skills-upstash-workflow-3205fdceaa63","title":"Implement Upstash Workflow with QStash","summary":"Process large batches of data asynchronously using QStash, implement dry-run mode to preview workflow execution, and split oversized batches into smaller chunks for parallel processing with Upstash Workflow.","url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-upstash-workflow-3205fdceaa63","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-lobehub-lobehub-agents-skills-upstash-workflow-3205fdceaa63","markdown_url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-upstash-workflow-3205fdceaa63.md","download_url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-upstash-workflow-3205fdceaa63\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Ensure `APP_URL` and `QSTASH_TOKEN` are set in your environment before starting. Define payload types with TypeScript interfaces and create a workflow class with static trigger methods. Use dry-run mode to preview execution without processing actual items.","instructions":"---\nname: upstash-workflow\ndescription: 'Use for Upstash Workflow\/QStash handlers, triggers, durable steps and async fan-out.'\nuser-invocable: false\n---\n\n# Upstash Workflow Implementation Guide\n\nStandard patterns for implementing Upstash Workflow + QStash async workflows in the LobeHub codebase.\n\n## \ud83c\udfaf The Three Core Patterns\n\nEvery workflow in LobeHub combines these three patterns. They exist because the platform constrains you in three ways: rate limits make blind fan-out dangerous, step limits cap a single workflow's size, and idempotency demands that retries don't double-process.\n\n1. **\ud83d\udd0d Dry-Run Mode** \u2014 get statistics without triggering actual execution\n2. **\ud83c\udf1f Fan-Out Pattern** \u2014 split large batches into smaller chunks for parallel processing\n3. **\ud83c\udfaf Single Task Execution** \u2014 each workflow execution processes **exactly ONE item**\n\n---\n\n## Architecture Overview\n\nAll workflows follow the same 3-layer architecture:\n\n```text\nLayer 1: Entry Point (process-*)\n  \u251c\u2500 Validates prerequisites\n  \u251c\u2500 Calculates total items to process\n  \u251c\u2500 Filters existing items\n  \u251c\u2500 Supports dry-run mode (statistics only)\n  \u2514\u2500 Triggers Layer 2 if work is needed\n\nLayer 2: Pagination (paginate-*)\n  \u251c\u2500 Handles cursor-based pagination\n  \u251c\u2500 Implements fan-out for large batches\n  \u251c\u2500 Recursively processes all pages\n  \u2514\u2500 Triggers Layer 3 for each item\n\nLayer 3: Single Task Execution (execute-* \/ generate-*)\n  \u2514\u2500 Performs actual business logic for ONE item\n```\n\n**Real examples in this codebase:** `topicAutoSummary`, `agentEvalRun` \u2014 see [`references\/examples.md`](.\/references\/examples.md).\n\n---\n\n## The Three Patterns in 60 Seconds\n\n### 1. Dry-Run Mode\n\nShort-circuit Layer 1 before any side effects so callers can preview what would happen:\n\n```typescript\nif (dryRun) {\n  return {\n    ...result,\n    dryRun: true,\n    message: `[DryRun] Would process ${itemsNeedingProcessing.length} items`,\n  };\n}\n```\n\nUse case: check how many items will be processed before committing.\n\n### 2. Fan-Out Pattern\n\nLayer 2 splits oversized batches into chunks and recursively re-triggers itself with each chunk. This avoids hitting workflow step limits when one page contains too many items:\n\n```typescript\nconst CHUNK_SIZE = 20;\n\nif (itemIds.length > CHUNK_SIZE) {\n  const chunks = chunk(itemIds, CHUNK_SIZE);\n  await Promise.all(\n    chunks.map((ids, idx) =>\n      context.run(`workflow:fanout:${idx + 1}\/${chunks.length}`, () =>\n        WorkflowClass.triggerPaginateItems({ itemIds: ids }),\n      ),\n    ),\n  );\n}\n```\n\nDefaults: `PAGE_SIZE = 50` (items per page), `CHUNK_SIZE = 20` (items per fan-out chunk).\n\n### 3. Single Task Execution\n\nLayer 3 always processes exactly one item per invocation. Parallelism comes from Layer 2 fanning out to many Layer 3 invocations, controlled by `flowControl`:\n\n```typescript\napp.post(\n  '\/execute-item',\n  serve<ExecutePayload>(\n    async (context) => {\n      const { itemId } = context.requestPayload ?? {};\n      if (!itemId) return { success: false, error: 'Missing itemId' };\n\n      const item = await context.run('workflow:get-item', () => getItem(itemId));\n      const result = await context.run('workflow:execute', () => processItem(item));\n      await context.run('workflow:save', () => saveResult(itemId, result));\n\n      return { success: true, itemId, result };\n    },\n    {\n      flowControl: { key: 'workflow.execute', parallelism: 10, ratePerSecond: 5 },\n    },\n  ),\n);\n```\n\n---\n\n## File Structure\n\n```text\nsrc\/app\/(backend)\/api\/workflows\/\n\u2514\u2500\u2500 [[...route]]\/route.ts             # Single catch-all \u2014 forwards every request to the Hono app below\n\napps\/server\/src\/router-hono\/workflows\/\n\u251c\u2500\u2500 index.ts                          # Mounts each workflow's Hono app at \/api\/workflows\/{workflow-name}\n\u2514\u2500\u2500 {workflow-name}\/\n    \u251c\u2500\u2500 index.ts                       # Hono app \u2014 one `app.post('\/{layer}', serve(handler, options))` per layer\n    \u251c\u2500\u2500 dispatch.ts \/ paginate-*.ts    # Layer 1 + 2 handler(s) \u2014 entry point, dry-run, pagination, fan-out\n    \u2514\u2500\u2500 execute.ts \/ execute-*.ts      # Layer 3 handler \u2014 single-task execution\n\napps\/server\/src\/workflows\/\n\u2514\u2500\u2500 {workflowName}\/\n    \u2514\u2500\u2500 index.ts                       # Workflow class \u2014 static trigger*() methods that POST to the routes above\n```\n\nEvery layer is a handler mounted on a per-workflow Hono app under `apps\/server\/src\/router-hono\/workflows\/`; the Next.js route under `src\/app` only dispatches into it.\n\n---\n\n## Where to Go Next\n\nPick the reference that matches what you're doing:\n\n| You want to...                                       | Read                                                             |\n| ---------------------------------------------------- | ---------------------------------------------------------------- |\n| Write the Workflow class + 3 routes from scratch     | [`references\/implementation.md`](.\/references\/implementation.md) |\n| Tune flowControl, error handling, logging, testing   | [`references\/best-practices.md`](.\/references\/best-practices.md) |\n| See two real workflows end-to-end                    | [`references\/examples.md`](.\/references\/examples.md)             |\n| Deploy on lobehub-cloud (re-exports, cloud-only ops) | [`references\/cloud.md`](.\/references\/cloud.md)                   |\n\n---\n\n## Environment Variables\n\n```bash\n# Required for all workflows\nAPP_URL=https:\/\/your-app.com # Base URL for workflow endpoints\nQSTASH_TOKEN=qstash_xxx      # QStash authentication token\n\n# Optional (for custom QStash URL)\nQSTASH_URL=https:\/\/custom-qstash.com\n```\n\n---\n\n## Checklist for New Workflows\n\n### Planning\n\n- [ ] Identify the entity to process (users, agents, items, \u2026)\n- [ ] Define the per-item business logic\n- [ ] Determine filtering logic (Redis cache, database state, \u2026)\n\n### Implementation\n\n- [ ] Define payload types with TypeScript interfaces\n- [ ] Create workflow class with static trigger methods\n- [ ] **Layer 1:** entry point with **dry-run** support\n- [ ] **Layer 1:** filtering logic to avoid duplicate work\n- [ ] **Layer 2:** pagination with **fan-out**\n- [ ] **Layer 3:** **single-task execution** (ONE item per run)\n- [ ] Configure appropriate `flowControl` for each layer\n- [ ] Consistent logging with workflow prefixes\n- [ ] Validate all required payload parameters\n- [ ] Unique `context.run()` step names\n\n### Quality & Deployment\n\n- [ ] Return consistent response shapes\n- [ ] Configure cloud deployment ([`references\/cloud.md`](.\/references\/cloud.md) if on lobehub-cloud)\n- [ ] Write integration tests (`dryRun` path + full path)\n- [ ] Smoke-test with dry-run first\n- [ ] Test with a small batch before full rollout\n\n---\n\n## Additional Resources\n\n- [Upstash Workflow Documentation](https:\/\/upstash.com\/docs\/workflow)\n- [QStash Documentation](https:\/\/upstash.com\/docs\/qstash)\n- [Example Workflows in Codebase](<..\/..\/..\/src\/app\/(backend)\/api\/workflows\/>)\n- [Workflow Classes](..\/..\/..\/apps\/server\/src\/workflows\/)\n","use_cases":["Process large batches of data asynchronously using QStash","Implement dry-run mode to preview workflow execution","Split oversized batches into smaller chunks for parallel processing"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/lobehub\/lobehub\/blob\/54382b5c8e81544da454fa6d7b50f461a562c1ee\/.agents\/skills\/upstash-workflow\/SKILL.md","source_commit":"54382b5c8e81544da454fa6d7b50f461a562c1ee","license":null,"version":null,"listing_approved_at":"2026-11-22","created_at":"2026-11-21T11:40:40.000000Z","updated_at":"2026-11-22T11:17:19.000000Z","seo_title":"Implement Upstash Workflow with QStash","seo_description":"Learn how to implement Upstash Workflow with QStash for async processing and fan-out patterns in your application.","seo_keywords":["Upstash Workflow implementation","QStash async processing","Workflow fan-out pattern","Dry-run mode for workflows","Asynchronous task processing"]}}