N8n workflow patterns

From WilkoMarketing/antigravity-n8n-skills · View interactive version

N8n workflow patterns is an AI agent skill from the GitHub repository WilkoMarketing/antigravity-n8n-skills. Proven workflow architectural patterns from real n8n workflows. Use when building new workflows, designing workflow structure, choosing workflow patterns, planning workflow architecture, or asking about webhook processing, HTTP API integration, database operations, AI agent workflows, batch processi

How to use this skill

Skill file

n8n Workflow Patterns

Proven architectural patterns for building n8n workflows.


The 6 Core Patterns

Based on analysis of real workflow usage:

  1. Webhook Processing (Most Common)
  1. HTTP API Integration
  1. Database Operations
  1. AI Agent Workflow
  1. Scheduled Tasks
  1. Batch Processing (below)

Pattern Selection Guide

When to use each pattern:

Webhook Processing - Use when:

HTTP API Integration - Use when:

Database Operations - Use when:

AI Agent Workflow - Use when:

Scheduled Tasks - Use when:

Batch Processing - Use when:


Common Workflow Components

All patterns share these building blocks:

1. Triggers

2. Data Sources

3. Transformation (native first)

The job-to-node table in using-n8n-mcp-skills maps jobs to these nodes; configs are in n8n-node-configuration → NATIVE_NODES.md. Reading a filtered slice of a nested API response for one field? A single {{ $jmespath($json, "…") }} in that field does it without extra nodes (quoting rules in n8n-expression-syntax).

4. Outputs

5. Error Handling


Workflow Creation Checklist

When building ANY workflow, follow this checklist:

Planning Phase

Implementation Phase

Validation Phase

Deployment Phase


Workflow lifecycle: validate, verify, test before activating

Building the nodes is the start, not the finish. Before a workflow goes live, run it through four gates — and remember the headline rule: validation passing is necessary, not sufficient. A workflow can validate clean and still drop items, pick the wrong Merge input, or post Slack messages as plain text. Clean validation means the shapes are right, not that the logic is.

  1. Validate. Run validate_workflow on the full JSON during build, or n8n_validate_workflow({ id }) once the workflow exists on the instance. Fix every error and re-validate. This catches schema, node-config, expression, and reference errors — the structural layer.
  2. Verify the connections. Pull the workflow with n8n_get_workflow({ id }) and read the connections object directly. Validation confirms connections aren't broken; it doesn't confirm they're correct. This is where you catch the valid-but-wrong wiring: a Merge whose useDataOfInput doesn't line up with the connection slot, a Switch fallback that connects to nothing, a fan-out branch that was never wired onward, an error output that goes nowhere. (See the n8n Node Configuration skill's NODE_FAMILY_GOTCHAS.md for the silent ones.)
  3. Test. Run n8n_test_workflow and inspect the output via n8n_executions. Confirm the output shape matches what consumers expect, fan-outs all produced data, and (for webhook APIs) the status/body/headers are right. Real side effects fire during a test — writes commit, messages send, external APIs are called. If any node has a user-visible side effect, confirm with the user before running, or test against safe data first.
  4. Activate only after the first three pass — using n8n_update_partial_workflow with the activateWorkflow operation. Don't activate straight off a clean validation; an active workflow that drops data or double-sends is worse than one that never started.

Skipping any gate trades a few minutes now for debugging a live, possibly stateful, possibly traffic-bearing workflow later. The trade is never worth it.


Data Flow Patterns

Linear Flow

Trigger → Transform → Action → End

Use when: Simple workflows with single path

Branching Flow

Trigger → IF → [True Path]
             └→ [False Path]

Use when: Different actions based on conditions

Parallel Processing

Trigger → [Branch 1] → Merge
       └→ [Branch 2] ↗

Use when: Independent operations that can run simultaneously

Loop Pattern

Trigger → Split in Batches → Process → Loop (until done)

Use when: Processing large datasets in chunks

Error Handler Pattern

Main Flow → [Success Path]
         └→ [Error Trigger → Error Handler]

Use when: Need separate error handling workflow


Batch Processing Pattern

SplitInBatches Loop

The SplitInBatches node splits a large dataset into smaller chunks for processing. Understanding its outputs is critical:

Prepare Items → SplitInBatches → [main[1]: Process Batch] → (loops back)
                                  [main[0]: Done] → Limit 1 → Aggregate

Always add a Limit 1 node after the done output.

Choosing batchSize (the cost lever)

A SplitInBatches loop re-runs its whole body once per iteration — ~0.8 ms/iteration of engine overhead plus the body's own cost — so total ≈ ⌈items / batchSize⌉ × (overhead + body). batchSize is a direct speed dial:

Cross-Iteration Data

After the loop, $('Node Inside Loop').all() returns ONLY the last batch's items. To accumulate across all iterations, use $getWorkflowStaticData('global') in a Code node inside the loop. See the n8n Code JavaScript skill for the full pattern.

Nested Loops

When processing N categories × M items per category (where an API has a batch limit):

Define Categories (N items)
  → Outer Loop (SplitInBatches, batchSize=1)
    → Prepare category data
    → Inner Loop (SplitInBatches, batchSize=1000)
      → API Call → Verify → (loops back to Inner Loop via main[1])
    → Inner done[0] → Rate Limit Delay → back to Outer Loop
  → Outer done[0] → Limit 1 → Final Aggregate

Wiring gotcha: The inner done[0] must connect back to the OUTER loop input, not to the aggregate. The outer done[0] feeds the final aggregate.

API Pagination

Paging through one endpoint is HTTP Request's pagination option, not a loop (page-number, offset, cursor and next-URL APIs, with a page cap — see n8n-node-configuration → NATIVE_NODES.md). The loop below is for sweeps the option can't express, such as an API without multi-ID filtering that you walk with id_from + date windows, each window its own query:

Schedule → Set Date Window → Fetch Page → Process
  → IF has more? → [true] Update id_from → Fetch Page (loop)
                  → [false] → Aggregate → Output

Dry-Run / Verification Tolerance

When testing with API write nodes disabled (for dry runs), downstream verification nodes receive the request body instead of the response. Make verification tolerant:

// In verification Code node
const body = $input.first().json;
const looksLikeRequest = body.method && body.parameters && !body.status;
if (looksLikeRequest) {
  return [{ json: { status: 'SKIPPED', message: 'Upstream disabled for testing' }}];
}
// Normal response verification below...

Performance on the hot path

When a workflow processes thousands of items with little I/O, its speed is set by how many times n8n crosses a per-item / per-iteration boundary — each crossing sets up an execution context and copies the items. Four architecture choices dominate:

  1. Consolidating a hot chain into one Code node is an exception, not a default. Every node→node hop re-copies all items, so on a measured hot path — thousands of items per run, transform work rather than I/O dominating — one All-Items Code node can beat a long chain. That is the closed list's "heavy all-items work" case: record it in the node's Why Code: note. Below that, native nodes win on readability.
  2. If Code stays, use "Run Once for All Items," not "Each Item." Each Item pays a full sandbox per item; a chain of Each-Item Code nodes is the worst case, because the per-item tax multiplies by node count.
  3. Maximize batchSize in SplitInBatches loops (see the Batch Processing pattern above) — iterations are the cost.
  4. Don't micro-optimize expressions — complexity is free; node and iteration count are what you pay for.

But profile first. Most production workflows are I/O-bound — sequential HTTP / DB / Sheets calls (hundreds of ms each) dwarf all of the above. These rules matter when transform work is the floor, or when an anti-pattern (Each-Item Code, batchSize 1, long per-item chains) turns a cheap operation into a slow one. Below a few hundred items, none of it matters. The n8n Code JavaScript skill has the full measured model.


Integration-Specific Gotchas

Google Sheets

Google Drive

Bidirectional Threshold Checking

When comparing values (prices, quantities, metrics), always check both directions:

// ❌ Only catches increases
if (diff > threshold) { flag(); }

// ✅ Catches both spikes AND crashes — both are data-quality signals
if (Math.abs(diff) > threshold) { flag(); }

Common Gotchas

1. Webhook Data Structure

Problem: Can't access webhook payload data

Solution: Data is nested under $json.body

❌ {{$json.email}}
✅ {{$json.body.email}}

See: n8n Expression Syntax skill

2. Multiple Input Items

Problem: Node processes all input items, but I only want one

Solution: Use "Execute Once" mode or process first item only

{{$json[0].field}}  // First item only

3. Authentication Issues

Problem: API calls failing with 401/403

Solution:

4. Node Execution Order

Problem: Nodes executing in unexpected order

Solution: Check workflow settings → Execution Order

5. Expression Errors

Problem: Expressions showing as literal text

Solution: Use {{}} around expressions


Integration with Other Skills

These skills work together with Workflow Patterns:

n8n MCP Tools Expert - Use to:

n8n Expression Syntax - Use to:

n8n Node Configuration - Use to:

n8n Validation Expert - Use to:


Pattern Statistics

Common workflow patterns:

Most Common Triggers:

  1. Webhook - 35%
  2. Schedule (periodic tasks) - 28%
  3. Manual (testing/admin) - 22%
  4. Service triggers (Slack, email, etc.) - 15%

Most Common Transformations:

  1. Set (field mapping) - 68%
  2. Code (custom logic) - 42%
  3. IF (conditional routing) - 38%
  4. Switch (multi-condition) - 18%

Most Common Outputs:

  1. HTTP Request (APIs) - 45%
  2. Slack - 32%
  3. Database writes - 28%
  4. Email - 24%

Average Workflow Complexity:


Quick Start Examples

Example 1: Simple Webhook → Slack

1. Webhook (path: "form-submit", POST)
2. Slack (post message to #notifications; the text maps $json.body fields with expressions)

Example 2: Scheduled Report

1. Schedule (daily at 9 AM)
2. HTTP Request (fetch analytics)
3. Summarize (totals per group)
4. Email (send formatted report)
5. Error Trigger → Slack (notify on failure)

Example 3: Database Sync

1. Schedule (every 15 minutes)
2. Postgres (query new records)
3. IF (check if records exist)
4. MySQL (insert records)
5. Postgres (update sync timestamp)

Example 4: AI Assistant

1. Webhook (receive chat message)
2. AI Agent
   ├─ OpenAI Chat Model (ai_languageModel)
   ├─ HTTP Request Tool (ai_tool)
   ├─ Database Tool (ai_tool)
   └─ Window Buffer Memory (ai_memory)
3. Webhook Response (send AI reply)

Example 5: API Integration

1. Manual Trigger (for testing)
2. HTTP Request (GET /api/users; pagination option if the API pages)
3. Postgres (upsert users; map the fields in the node's column slots)

No loop and no Set: Postgres processes every item, and the column slots take the mapping expressions.


Detailed Pattern Files

For comprehensive guidance on each pattern:


Real Template Examples

From n8n template library:

Template #2947: Weather to Slack

Webhook Processing: Most common pattern

HTTP API: Common pattern

Database Operations: Common pattern

AI Agents: Growing in usage

Use search_templates and get_template from n8n-mcp tools to find examples!


Best Practices

✅ Do

❌ Don't


Summary

Key Points:

  1. 6 core patterns cover 90%+ of workflow use cases
  2. Webhook processing is the most common pattern
  3. Use the workflow creation checklist for every workflow
  4. Plan pattern → Select nodes → Build → Validate → Deploy
  5. Integrate with other skills for complete workflow development

Next Steps:

  1. Identify your use case pattern
  2. Read the detailed pattern file
  3. Use n8n MCP Tools Expert to find nodes
  4. Follow the workflow creation checklist
  5. Use n8n Validation Expert to validate

Related Skills:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.