Workflow Automation
Master workflow design, n8n patterns, automation triggers, error handling, and monitoring for reliable business process automation
cosmicstack-labs · 已有 AI 审核记录
安装与使用
运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。
npx skills add cosmicstack-labs/mercury-agent-skills --skill Workflow Automation技能说明
name: Workflow Automation description: Master workflow design, n8n patterns, automation triggers, error handling, and monitoring for reliable business process automation metadata: author: cosmicstack-labs version: 1.0.0 category: automation tags: - workflow-automation - n8n - triggers - error-handling - business-process - orchestration - monitoring
Workflow Automation
Core Principles
1. Reliability First
Every workflow must handle failure gracefully. Automations should degrade predictably, not silently. A workflow that fails noisily is better than one that fails silently — at least you know to fix it.
2. Idempotency
Design every action to be safe to run multiple times. If a workflow retries mid-way, running the same step twice should produce the same result as running it once. This is the single most important property for building reliable automations.
3. Observability
You cannot improve what you cannot see. Every workflow must log key events, expose execution traces, and alert on failures. Treat your workflows as production systems — because they are.
4. Loose Coupling
Workflow steps should communicate through well-defined interfaces (files, databases, APIs), not through shared mutable state. This allows steps to be replaced, tested, and scaled independently.
5. Fail Fast, Recover Gracefully
Validate inputs immediately at the start of a workflow. Catch known error conditions early. For unexpected errors, have a fallback path — don't let a single failure cascade through the entire system.
Automation Maturity Model
| Level | Name | Description |
|---|---|---|
| 0 | Ad-hoc | Manual processes, no automation. Everything done by hand. |
| 1 | Basic | Simple single-step automations. No error handling. Manual retries. |
| 2 | Structured | Multi-step workflows with basic error handling. Logs exist but aren't monitored. |
| 3 | Reliable | Idempotent steps, retry with backoff, dead letter queues. Alerts on failure. |
| 4 | Observable | Full execution tracing, dashboards, performance metrics. Proactive alerting. |
| 5 | Self-healing | Automatic rollback, compensating transactions, adaptive error handling. |
Target at least Level 3 for any workflow that touches production data.
Workflow Design Patterns
Triggers → Actions → Error Handling
Every workflow follows a three-phase structure:
// Conceptual workflow structure
Phase 1: TRIGGER — webhook receives event, cron fires, form submitted
Phase 2: ACTION — transform data, call APIs, update databases, send notifications
Phase 3: HANDLE — on success: log, confirm. On error: retry, notify, dead-letter
Pattern: Guard Clause at Entry
Before executing any actions, validate that you have everything you need:
// n8n pseudocode
if (!input.payload.email) {
throw new Error('Missing required field: email');
// This routes to error handler, not the success path
}
Idempotency
Make every operation idempotent by design:
- Create operations: Check if a record already exists before creating. Use upsert patterns.
- API calls: Include an idempotency key in headers. If the call retries, the server recognizes the duplicate.
- File operations: Use atomic writes — write to a temp file, then rename into place.
// Idempotent webhook handler pattern
// n8n: Before creating a record, search for duplicates
const existing = await searchDatabase({ email: $json.email });
if (existing) {
// Update existing record instead of creating duplicate
return { id: existing.id, action: 'updated' };
}
return { id: await createRecord($json), action: 'created' };
Fan-Out / Fan-In
Distribute work across parallel paths, then aggregate results:
- Fan-Out: Split a batch of items into individual items, process each in parallel.
- Fan-In: Collect results from parallel branches, merge, and proceed.
// n8n pattern: Loop Over Items node
// Input: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
// Each item is processed independently by subsequent nodes
// Results merge back automatically in n8n's item-based execution model
// For explicit fan-in with aggregation:
const results = $input.all();
const summary = {
total: results.length,
succeeded: results.filter(r => r.success).length,
failed: results.filter(r => !r.success).length
};
Best Practice: Set concurrency limits on fan-outs. Don't fire 10,000 requests at once — use batch sizes of 10–50.
Saga Pattern for Distributed Workflows
For operations spanning multiple systems, use the Saga pattern to maintain data consistency:
Choreography-based Saga: Each service publishes events that trigger the next step. If a step fails, each previous step runs a compensating action.
// Saga transaction example
Steps:
1. Order Service: Reserve inventory → publish "InventoryReserved"
2. Payment Service: Charge customer → publish "PaymentCharged"
3. Shipping Service: Create shipment → publish "ShipmentCreated"
4. Notification: Send confirmation → complete
// On failure at step 2:
// → Trigger compensating transactions:
// - Payment service: Void charge
// - Order service: Release inventory reservation
Orchestration-based Saga: A central coordinator (your n8n workflow) calls each service and manages compensation.
// n8n orchestration pattern
try {
await reserveInventory(orderId, items);
await chargeCustomer(orderId, amount);
await createShipment(orderId);
} catch (error) {
// Compensating transactions in reverse order
await voidShipment(orderId); // if created
await refundCustomer(orderId); // if charged
await releaseInventory(orderId); // if reserved
throw error; // Re-raise after cleanup
}
Rule: Compensating transactions must themselves be idempotent and reliable.
n8n-Specific Patterns
Webhook Triggers
阅读完整来源 ↗