Modo
Agendar llamada

n8n-workflow-patterns: diseñar flujos de n8n con los patrones que funcionan

Le da a Claude los seis patrones de arquitectura de los flujos de n8n y una lista de control para armarlos, validarlos, probarlos y recién después activarlos.

n8n-workflow-patterns: diseñar flujos de n8n con los patrones que funcionan

Respuesta rápida

Qué es
n8n-workflow-patterns es una skill de Romuald Członkowski (licencia MIT) que le enseña a Claude a diseñar flujos de n8n con seis patrones probados y a validarlos y probarlos antes de activarlos.
Qué le das
Qué quieres automatizar (qué lo dispara, de dónde salen los datos y adónde van) y, si lo conectas, tu instancia de n8n
Qué te devuelve
El diseño del flujo nodo por nodo con su manejo de errores y, con el MCP conectado, el flujo creado, validado y probado en tu n8n
Licencia
MIT
En GitHub
6,6 mil estrellas · actualizada el
Revisada por Claura

Instálala en una línea para todos tus proyectos, en Claude Code, Cursor, Codex y más:

npx skills add czlonkowski/n8n-skills --skill n8n-workflow-patterns -g

Funciona en

Claude CodeEn ~/.claude/skills/
CursorEn ~/.agents/skills/
CodexEn ~/.agents/skills/
Gemini CLIEn ~/.agents/skills/

Pedidos para probarla

Con la skill instalada, copia uno y pégaselo a tu agente tal cual, o cambia los datos por los tuyos.

  • Diseña un flujo de n8n que reciba los leads del formulario de mi web por webhook, los guarde en el CRM y avise por WhatsApp al vendedor.

  • Quiero un flujo programado que cada mañana junte las ventas del día anterior de mi tienda y me mande un resumen por mail.

  • Revisa este flujo de n8n que falla a veces [pega el JSON] y dime qué patrón le falta para manejar errores.

#Qué hace

n8n-workflow-patterns es una skill de Romuald Członkowski (licencia MIT), autor también del servidor MCP n8n-mcp, que le da a Claude la arquitectura de los flujos de n8n. Parte de seis patrones: procesar webhooks (el más común: recibir, validar, transformar, responder o avisar), integrar APIs, operar bases de datos, agentes de IA con modelo, herramientas y memoria, tareas programadas y procesamiento por lotes. Para cada uno explica cuándo conviene, con ejemplos como recibir el aviso de pago de Stripe, actualizar la base y mandar la confirmación, o armar cada mañana un informe y mandarlo por email.

Describe las piezas que comparten todos los flujos (disparadores, fuentes de datos, transformaciones, salidas y manejo de errores) con una regla: primero los nodos nativos (filtrar, resumir, unir, quitar duplicados) y el nodo de código solo en una lista cerrada de casos y con una nota que explique por qué. Trae una lista de control en cuatro fases (planificar, construir, validar, poner en marcha) y un ciclo de cuatro controles antes de activar: validar el flujo, revisar a mano las conexiones, probarlo con datos y recién entonces activarlo. Advierte que en la prueba los efectos son reales: los registros se escriben y los mensajes salen.

Profundiza en el procesamiento por lotes (qué salida del bucle dispara por cada lote y cuál una sola vez al final, bucles anidados, paginación), en el rendimiento cuando un flujo procesa miles de elementos y en trampas concretas de Google Sheets, Google Drive y webhooks. Cierra con cinco ejemplos de flujos y la lista de lo que conviene hacer y evitar. La carpeta suma cinco archivos con el detalle de cada patrón (webhooks, APIs, bases de datos, agentes de IA y tareas programadas), y la skill remite a otras del mismo paquete para expresiones, configuración de nodos y validación.

#Cómo aplicarla a tu negocio

Caso de ejemplo: una clínica dental en Buenos Aires con n8n en la nube. Cada consulta que entra por el formulario de la web se copia a mano a una planilla y al CRM, y a veces nadie la contesta en el día.

  1. Describe el proceso. «Cuando alguien completa el formulario de turnos, guárdalo en la planilla, créalo en el CRM y avísale a recepción por Slack. Si algo falla, que me llegue un aviso.»
  2. Deja que elija el patrón. La skill lo resuelve como procesamiento de webhook: webhook, validación, transformación de campos, escritura en la planilla y en el CRM, aviso por Slack y un flujo aparte de errores.
  3. Evita las trampas conocidas. Los datos del formulario se leen dentro del cuerpo del webhook, y la planilla se actualiza sin romper las columnas con fórmulas.
  4. Valida, revisa y prueba. Con n8n-mcp conectado, Claude crea el flujo, lo valida, revisa las conexiones y lo prueba con una consulta inventada, avisándote antes porque la prueba escribe en la planilla y manda el mensaje de verdad.
  5. Activa y mira las primeras ejecuciones. Recién después de esos tres controles se activa, y se revisan las primeras consultas reales (por ejemplo, las de la primera semana) para confirmar que ninguna se pierde.

#Cómo instalarla

La skill sola funciona como guía en cualquier agente, pero rinde de verdad junto al resto del paquete n8n-skills y al MCP n8n-mcp, ambos del mismo autor.

  • Con una línea, para cualquier agente: npx skills add czlonkowski/n8n-skills --skill n8n-workflow-patterns -g la deja instalada en todos tus proyectos. Sin --skill puedes elegir las 14 del paquete.
  • Claude Code, como plugin (lo que recomienda el autor): /plugin install czlonkowski/n8n-skills, o /plugin marketplace add czlonkowski/n8n-skills y después /plugin install. Trae las 14 skills y unos avisos automáticos que solo funcionan en el plugin.
  • A mano: copia la carpeta skills/n8n-workflow-patterns/ completa (con sus cinco archivos de patrones) a ~/.claude/skills/ para Claude Code, o a ~/.agents/skills/ para Cursor, Codex y Gemini CLI.
  • App de Claude: comprime la carpeta en un ZIP (o baja los ZIP ya armados de la última versión del repo) y súbela desde Customize, Skills, «Upload a skill».
  • El MCP n8n-mcp: es un servidor de código abierto que deja a Claude leer, crear, validar y probar flujos en tu n8n. Hay dos caminos. El servicio alojado del autor en dashboard.n8n-mcp.com, sin instalar nada, con un plan gratis de 100 llamadas por día. O correrlo tú con Node: en Claude Code, claude mcp add n8n-mcp -e MCP_MODE=stdio -e LOG_LEVEL=error -e DISABLE_CONSOLE_OUTPUT=true -e N8N_API_URL=https://tu-n8n.com -e N8N_API_KEY=tu-clave -- npx n8n-mcp, como indica su guía para Claude Code (sin las dos últimas variables, solo da la documentación de nodos y la validación). La clave sale de la configuración de la API pública de tu n8n. Antes de editar flujos importantes, guarda una copia: el MCP hace una instantánea antes de cada cambio, pero el autor pide probar en una copia o en una instancia de pruebas.

El SKILL.md completo (con la licencia y la fuente) está más abajo.

El SKILL.md completo

Skill original de Romuald Członkowski (MIT). Fuente: github.com/czlonkowski/n8n-skills/tree/main/skills/n8n-workflow-patterns.

El archivo original está en inglés y va tal cual, sin traducir. Lo de arriba de esta ficha es el resumen en español: qué hace, cómo aplicarla y cómo instalarla.

Leer el archivo (557 líneas)

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)

    • Receive HTTP requests → Process → Output
    • Pattern: Webhook → Validate → Transform → Respond/Notify
  2. HTTP API Integration

    • Fetch from REST APIs → Transform → Store/Use
    • Pattern: Trigger → HTTP Request → Transform → Action → Error Handler
  3. Database Operations

    • Read/Write/Sync database data
    • Pattern: Schedule → Query → Transform → Write → Verify
  4. AI Agent Workflow

    • AI agents with tools and memory
    • Pattern: Trigger → AI Agent (Model + Tools + Memory) → Output
  5. Scheduled Tasks

    • Recurring automation workflows
    • Pattern: Schedule → Fetch → Process → Deliver → Log
  6. Batch Processing (below)

    • Process large datasets in chunks with API rate limits
    • Pattern: Prepare → SplitInBatches → Process per batch → Accumulate → Aggregate

Pattern Selection Guide

When to use each pattern:

Webhook Processing - Use when:

  • Receiving data from external systems
  • Building integrations (Slack commands, form submissions, GitHub webhooks)
  • Need instant response to events
  • Example: "Receive Stripe payment webhook → Update database → Send confirmation"

HTTP API Integration - Use when:

  • Fetching data from external APIs
  • Synchronizing with third-party services
  • Building data pipelines
  • Example: "Fetch GitHub issues → Transform → Create Jira tickets"

Database Operations - Use when:

  • Syncing between databases
  • Running database queries on schedule
  • ETL workflows
  • Example: "Read Postgres records → Transform → Write to MySQL"

AI Agent Workflow - Use when:

  • Building conversational AI
  • Need AI with tool access
  • Multi-step reasoning tasks
  • Example: "Chat with AI that can search docs, query database, send emails"

Scheduled Tasks - Use when:

  • Recurring reports or summaries
  • Periodic data fetching
  • Maintenance tasks
  • Example: "Daily: Fetch analytics → Generate report → Email team"

Batch Processing - Use when:

  • Processing large datasets that exceed API batch limits
  • Need to accumulate results across multiple API calls
  • Nested loops (e.g., multiple categories × paginated API calls per category)
  • Example: "Fetch products for 4 markets × 1000 per API call → Aggregate all results"

Common Workflow Components

All patterns share these building blocks:

1. Triggers
  • Webhook - HTTP endpoint (instant)
  • Schedule - Cron-based timing (periodic)
  • Manual - Click to execute (testing)
  • Polling - Check for changes (intervals)
2. Data Sources
  • HTTP Request - REST APIs
  • Database nodes - Postgres, MySQL, MongoDB
  • Service nodes - Slack, Google Sheets, etc.
  • Extract From File - CSV / XLSX / PDF from a downloaded or uploaded file
3. Transformation (native first)
  • Filter / IF / Switch - Drop items, route
  • Edit Fields (Set) - Named steps: constant items, payload objects, error and return items
  • Summarize / Aggregate / Split Out - Group and total, collect into an array, explode an array
  • Merge / Compare Datasets - Join two lists, diff them for a sync
  • Remove Duplicates / Sort / Limit - Dedupe (also across runs), top-N
  • Date & Time, XML, HTML, Crypto - Dates, markup, hashes and signatures
  • Code - Only the closed list (loops or recursion no node expresses, state across runs, parsing no node handles), with a Why Code: note

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
  • HTTP Request - Call APIs
  • Database - Write data
  • Communication - Email, Slack, Discord
  • Storage - Files, cloud storage
5. Error Handling
  • Error Trigger - Catch workflow errors
  • IF - Check for error conditions
  • Stop and Error - Explicit failure
  • Continue On Fail - Per-node setting

Workflow Creation Checklist

When building ANY workflow, follow this checklist:

Planning Phase
  • Identify the pattern (webhook, API, database, AI, scheduled)
  • List required nodes (use search_nodes)
  • Understand data flow (input → transform → output)
  • Plan error handling strategy
Implementation Phase
  • Create workflow with appropriate trigger
  • Add data source nodes
  • Configure authentication/credentials
  • Add transformation nodes (native first: Filter, IF, Summarize, Merge…; Code only with a Why Code: note)
  • Add output/action nodes
  • Configure error handling
Validation Phase
  • Validate each node configuration (validate_node)
  • Validate complete workflow (validate_workflow)
  • Test with sample data
  • Handle edge cases (empty data, errors)
Deployment Phase
  • Review workflow settings (execution order, timeout, error handling)
  • Activate workflow using activateWorkflow operation
  • Monitor first executions
  • Document workflow purpose and data flow

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:

  • main[0] = done — fires ONCE after all batches complete
  • main[1] = each batch — fires per batch (this is the loop body)
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:

  • Pick the largest batch your real constraint allows (API page size, rate limit, memory). Bigger batches = fewer iterations = less overhead; the body still sees every item.
  • batchSize: 1 is the expensive extreme — one full engine pass per item. Use it only when you must act on a single item at a time (nested-loop control, or an API that takes exactly one id).
  • If you're looping only to "go over the items" with no external constraint, you don't need the loop: connect the source to the consumer. Per-item execution handles it, and native transform nodes process all items in one call.
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
  • NEVER use append on sheets with formula columns — it breaks formulas. Use Google Sheets API values.update (PUT) via HTTP Request node with a googleApi credential
  • Write numbers, not strings for formula-dependent columns — string "4.98" breaks ADD() formulas. Convert in the column's expression: {{ $json.price.toNumber() }} or {{ parseFloat($json.price) }}
  • Per-item execution trap: Google Sheets nodes execute once per input item. If you need a single bulk write, collect the rows into one item with an Aggregate node first
  • UNFORMATTED_VALUE returns numbers, not text like "N/A" — filter explicitly with a Filter node
Google Drive
  • convertToGoogleDocument: true creates a Google Doc (text), NOT a Google Sheet — to upload a CSV for download, omit this option entirely
  • CSV download link format: https://drive.google.com/uc?id={fileId}&export=download — use instead of /view links
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:

  • Configure credentials properly
  • Use the "Credentials" section, not parameters
  • Test credentials before workflow activation
4. Node Execution Order

Problem: Nodes executing in unexpected order

Solution: Check workflow settings → Execution Order

  • v0: Top-to-bottom (legacy)
  • v1: Connection-based (recommended)
5. Expression Errors

Problem: Expressions showing as literal text

Solution: Use {{}} around expressions

  • See n8n Expression Syntax skill for details

Integration with Other Skills

These skills work together with Workflow Patterns:

n8n MCP Tools Expert - Use to:

  • Find nodes for your pattern (search_nodes)
  • Understand node operations (get_node)
  • Create workflows (n8n_create_workflow)
  • Deploy templates (n8n_deploy_template)
  • Use tools_documentation({topic: "ai_agents_guide", depth: "full"}) for AI pattern guidance
  • Manage data tables with n8n_manage_datatable
  • Organize workflows into folders with n8n_manage_folders

n8n Expression Syntax - Use to:

  • Write expressions in transformation nodes
  • Access webhook data correctly ({{$json.body.field}})
  • Reference previous nodes ({{$node["Node Name"].json.field}})

n8n Node Configuration - Use to:

  • Configure specific operations for pattern nodes
  • Understand node-specific requirements

n8n Validation Expert - Use to:

  • Validate workflow structure
  • Fix validation errors
  • Ensure workflow correctness before deployment

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:

  • Simple (3-5 nodes): 42%
  • Medium (6-10 nodes): 38%
  • Complex (11+ nodes): 20%

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

  • Pattern: Scheduled Task
  • Nodes: Schedule → HTTP Request (weather API) → Set → Slack
  • Complexity: Simple (4 nodes)

Webhook Processing: Most common pattern

  • Most common: Form submissions, payment webhooks, chat integrations

HTTP API: Common pattern

  • Most common: Data fetching, third-party integrations

Database Operations: Common pattern

  • Most common: ETL, data sync, backup workflows

AI Agents: Growing in usage

  • Most common: Chatbots, content generation, data analysis

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


Best Practices

✅ Do
  • Start with the simplest pattern that solves your problem
  • Plan your workflow structure before building
  • Use error handling on all workflows
  • Test with sample data before activation
  • Follow the workflow creation checklist
  • Use descriptive node names
  • Document complex workflows (notes field)
  • Monitor workflow executions after deployment
❌ Don't
  • Build workflows in one shot (iterate! avg 56s between edits)
  • Skip validation before activation
  • Ignore error scenarios
  • Use complex patterns when simple ones suffice
  • Hardcode credentials in parameters
  • Forget to handle empty data cases
  • Mix multiple patterns without clear boundaries
  • Deploy without testing

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:

  • n8n MCP Tools Expert - Find and configure nodes
  • n8n Expression Syntax - Write expressions correctly
  • n8n Validation Expert - Validate and fix errors
  • n8n Node Configuration - Configure specific operations
Copiar el archivo tal cual
---
name: n8n-workflow-patterns
description: 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 processing, or scheduled tasks. Always consult this skill when the user asks to create, build, or design an n8n workflow, automate a process, or connect services — even if they don't explicitly mention 'patterns'. Covers webhook, API, database, AI, batch processing, and scheduled automation architectures. Also use when optimizing a slow workflow or speeding up large-item-count processing (node count, batchSize, all-items vs per-item).
---

<!--
Skill original: n8n-workflow-patterns, de Romuald Członkowski (https://github.com/czlonkowski/n8n-skills/tree/main/skills/n8n-workflow-patterns)
Licencia: MIT. Reproducida con atribución según los términos de la licencia.
Copia publicada en claura-ai.com/skills.
-->

# n8n Workflow Patterns

Proven architectural patterns for building n8n workflows.

---

## The 6 Core Patterns

Based on analysis of real workflow usage:

1. **[Webhook Processing](webhook_processing.md)** (Most Common)
   - Receive HTTP requests → Process → Output
   - Pattern: Webhook → Validate → Transform → Respond/Notify

2. **[HTTP API Integration](http_api_integration.md)**
   - Fetch from REST APIs → Transform → Store/Use
   - Pattern: Trigger → HTTP Request → Transform → Action → Error Handler

3. **[Database Operations](database_operations.md)**
   - Read/Write/Sync database data
   - Pattern: Schedule → Query → Transform → Write → Verify

4. **[AI Agent Workflow](ai_agent_workflow.md)**
   - AI agents with tools and memory
   - Pattern: Trigger → AI Agent (Model + Tools + Memory) → Output

5. **[Scheduled Tasks](scheduled_tasks.md)**
   - Recurring automation workflows
   - Pattern: Schedule → Fetch → Process → Deliver → Log

6. **Batch Processing** (below)
   - Process large datasets in chunks with API rate limits
   - Pattern: Prepare → SplitInBatches → Process per batch → Accumulate → Aggregate

---

## Pattern Selection Guide

### When to use each pattern:

**Webhook Processing** - Use when:
- Receiving data from external systems
- Building integrations (Slack commands, form submissions, GitHub webhooks)
- Need instant response to events
- Example: "Receive Stripe payment webhook → Update database → Send confirmation"

**HTTP API Integration** - Use when:
- Fetching data from external APIs
- Synchronizing with third-party services
- Building data pipelines
- Example: "Fetch GitHub issues → Transform → Create Jira tickets"

**Database Operations** - Use when:
- Syncing between databases
- Running database queries on schedule
- ETL workflows
- Example: "Read Postgres records → Transform → Write to MySQL"

**AI Agent Workflow** - Use when:
- Building conversational AI
- Need AI with tool access
- Multi-step reasoning tasks
- Example: "Chat with AI that can search docs, query database, send emails"

**Scheduled Tasks** - Use when:
- Recurring reports or summaries
- Periodic data fetching
- Maintenance tasks
- Example: "Daily: Fetch analytics → Generate report → Email team"

**Batch Processing** - Use when:
- Processing large datasets that exceed API batch limits
- Need to accumulate results across multiple API calls
- Nested loops (e.g., multiple categories × paginated API calls per category)
- Example: "Fetch products for 4 markets × 1000 per API call → Aggregate all results"

---

## Common Workflow Components

All patterns share these building blocks:

### 1. Triggers
- **Webhook** - HTTP endpoint (instant)
- **Schedule** - Cron-based timing (periodic)
- **Manual** - Click to execute (testing)
- **Polling** - Check for changes (intervals)

### 2. Data Sources
- **HTTP Request** - REST APIs
- **Database nodes** - Postgres, MySQL, MongoDB
- **Service nodes** - Slack, Google Sheets, etc.
- **Extract From File** - CSV / XLSX / PDF from a downloaded or uploaded file

### 3. Transformation (native first)
- **Filter / IF / Switch** - Drop items, route
- **Edit Fields (Set)** - Named steps: constant items, payload objects, error and return items
- **Summarize / Aggregate / Split Out** - Group and total, collect into an array, explode an array
- **Merge / Compare Datasets** - Join two lists, diff them for a sync
- **Remove Duplicates / Sort / Limit** - Dedupe (also across runs), top-N
- **Date & Time, XML, HTML, Crypto** - Dates, markup, hashes and signatures
- **Code** - Only the closed list (loops or recursion no node expresses, state across runs, parsing no node handles), with a `Why Code:` note

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
- **HTTP Request** - Call APIs
- **Database** - Write data
- **Communication** - Email, Slack, Discord
- **Storage** - Files, cloud storage

### 5. Error Handling
- **Error Trigger** - Catch workflow errors
- **IF** - Check for error conditions
- **Stop and Error** - Explicit failure
- **Continue On Fail** - Per-node setting

---

## Workflow Creation Checklist

When building ANY workflow, follow this checklist:

### Planning Phase
- [ ] Identify the pattern (webhook, API, database, AI, scheduled)
- [ ] List required nodes (use search_nodes)
- [ ] Understand data flow (input → transform → output)
- [ ] Plan error handling strategy

### Implementation Phase
- [ ] Create workflow with appropriate trigger
- [ ] Add data source nodes
- [ ] Configure authentication/credentials
- [ ] Add transformation nodes (native first: Filter, IF, Summarize, Merge…; Code only with a `Why Code:` note)
- [ ] Add output/action nodes
- [ ] Configure error handling

### Validation Phase
- [ ] Validate each node configuration (validate_node)
- [ ] Validate complete workflow (validate_workflow)
- [ ] Test with sample data
- [ ] Handle edge cases (empty data, errors)

### Deployment Phase
- [ ] Review workflow settings (execution order, timeout, error handling)
- [ ] Activate workflow using `activateWorkflow` operation
- [ ] Monitor first executions
- [ ] Document workflow purpose and data flow

---

## 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:

- `main[0]` = **done** — fires ONCE after all batches complete
- `main[1]` = **each batch** — fires per batch (this is the loop body)

```
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:

- Pick the **largest batch your real constraint allows** (API page size, rate limit, memory). Bigger batches = fewer iterations = less overhead; the body still sees every item.
- `batchSize: 1` is the expensive extreme — one full engine pass per item. Use it only when you must act on a single item at a time (nested-loop control, or an API that takes exactly one id).
- If you're looping only to "go over the items" with no external constraint, you don't need the loop: connect the source to the consumer. Per-item execution handles it, and native transform nodes process all items in one call.

### 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:

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

- **NEVER use `append`** on sheets with formula columns — it breaks formulas. Use Google Sheets API `values.update` (PUT) via HTTP Request node with a `googleApi` credential
- **Write numbers, not strings** for formula-dependent columns — string "4.98" breaks `ADD()` formulas. Convert in the column's expression: `{{ $json.price.toNumber() }}` or `{{ parseFloat($json.price) }}`
- **Per-item execution trap**: Google Sheets nodes execute once per input item. If you need a single bulk write, collect the rows into one item with an Aggregate node first
- **UNFORMATTED_VALUE returns numbers**, not text like "N/A" — filter explicitly with a Filter node

### Google Drive

- **`convertToGoogleDocument: true` creates a Google Doc (text)**, NOT a Google Sheet — to upload a CSV for download, omit this option entirely
- **CSV download link format**: `https://drive.google.com/uc?id={fileId}&export=download` — use instead of `/view` links

### Bidirectional Threshold Checking

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

```javascript
// ❌ 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`
```javascript
❌ {{$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
```javascript
{{$json[0].field}}  // First item only
```

### 3. Authentication Issues
**Problem**: API calls failing with 401/403

**Solution**:
- Configure credentials properly
- Use the "Credentials" section, not parameters
- Test credentials before workflow activation

### 4. Node Execution Order
**Problem**: Nodes executing in unexpected order

**Solution**: Check workflow settings → Execution Order
- v0: Top-to-bottom (legacy)
- v1: Connection-based (recommended)

### 5. Expression Errors
**Problem**: Expressions showing as literal text

**Solution**: Use {{}} around expressions
- See n8n Expression Syntax skill for details

---

## Integration with Other Skills

These skills work together with Workflow Patterns:

**n8n MCP Tools Expert** - Use to:
- Find nodes for your pattern (search_nodes)
- Understand node operations (get_node)
- Create workflows (n8n_create_workflow)
- Deploy templates (n8n_deploy_template)
- Use `tools_documentation({topic: "ai_agents_guide", depth: "full"})` for AI pattern guidance
- Manage data tables with `n8n_manage_datatable`
- Organize workflows into folders with `n8n_manage_folders`

**n8n Expression Syntax** - Use to:
- Write expressions in transformation nodes
- Access webhook data correctly ({{$json.body.field}})
- Reference previous nodes ({{$node["Node Name"].json.field}})

**n8n Node Configuration** - Use to:
- Configure specific operations for pattern nodes
- Understand node-specific requirements

**n8n Validation Expert** - Use to:
- Validate workflow structure
- Fix validation errors
- Ensure workflow correctness before deployment

---

## 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**:
- Simple (3-5 nodes): 42%
- Medium (6-10 nodes): 38%
- Complex (11+ nodes): 20%

---

## 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:

- **[webhook_processing.md](webhook_processing.md)** - Webhook patterns, data structure, response handling
- **[http_api_integration.md](http_api_integration.md)** - REST APIs, authentication, pagination, retries
- **[database_operations.md](database_operations.md)** - Queries, sync, transactions, batch processing
- **[ai_agent_workflow.md](ai_agent_workflow.md)** - AI agents, tools, memory, langchain nodes
- **[scheduled_tasks.md](scheduled_tasks.md)** - Cron schedules, reports, maintenance tasks

---

## Real Template Examples

From n8n template library:

**Template #2947**: Weather to Slack
- Pattern: Scheduled Task
- Nodes: Schedule → HTTP Request (weather API) → Set → Slack
- Complexity: Simple (4 nodes)

**Webhook Processing**: Most common pattern
- Most common: Form submissions, payment webhooks, chat integrations

**HTTP API**: Common pattern
- Most common: Data fetching, third-party integrations

**Database Operations**: Common pattern
- Most common: ETL, data sync, backup workflows

**AI Agents**: Growing in usage
- Most common: Chatbots, content generation, data analysis

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

---

## Best Practices

### ✅ Do

- Start with the simplest pattern that solves your problem
- Plan your workflow structure before building
- Use error handling on all workflows
- Test with sample data before activation
- Follow the workflow creation checklist
- Use descriptive node names
- Document complex workflows (notes field)
- Monitor workflow executions after deployment

### ❌ Don't

- Build workflows in one shot (iterate! avg 56s between edits)
- Skip validation before activation
- Ignore error scenarios
- Use complex patterns when simple ones suffice
- Hardcode credentials in parameters
- Forget to handle empty data cases
- Mix multiple patterns without clear boundaries
- Deploy without testing

---

## 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**:
- n8n MCP Tools Expert - Find and configure nodes
- n8n Expression Syntax - Write expressions correctly
- n8n Validation Expert - Validate and fix errors
- n8n Node Configuration - Configure specific operations

Preguntas frecuentes sobre la skill n8n-workflow-patterns

¿Qué es la skill n8n-workflow-patterns y para qué sirve?

n8n-workflow-patterns es una skill de Romuald Członkowski (github.com/czlonkowski/n8n-skills, licencia MIT) que le da a Claude los seis patrones con los que se arman casi todos los flujos de n8n: procesar webhooks, integrar APIs, operar bases de datos, agentes de IA, tareas programadas y procesamiento por lotes. Para cada uno dice cuándo usarlo, qué nodos lleva y cómo manejar errores, y suma una lista de control de cuatro fases. Es parte de un paquete de 14 skills de n8n del mismo autor y está pensada para trabajar junto a su servidor MCP, n8n-mcp.

¿Cómo la aplico para automatizar algo de mi negocio?

Describe el proceso con sus tres partes: qué lo dispara (un formulario, una hora del día, un mensaje), de dónde salen los datos y adónde tienen que llegar. La skill elige el patrón, por ejemplo un webhook que recibe el formulario, valida, transforma y avisa, y arma el flujo priorizando los nodos propios de n8n antes que el código. Con n8n-mcp conectado, Claude crea el flujo en tu instancia, lo valida, revisa las conexiones a mano y lo prueba antes de activarlo. Si quieres revisar un flujo con la herramienta de n8n antes de prenderlo, lee cómo revisar el flujo antes de activarlo.

¿En qué se diferencia de pedirle a Claude que me arme un flujo de n8n?

Sin la skill, Claude suele inventar estructuras que se ven bien y fallan en detalles: leer el cuerpo del webhook donde no está, conectar mal la salida de un bucle o escribir nodos de código donde alcanzaba uno nativo. La skill trae esos errores anotados, reglas de lotes (la salida de un bucle que dispara una sola vez al terminar, el tamaño de lote como palanca de velocidad) y trampas de Google Sheets y Google Drive. Sobre todo impone una regla: que el flujo pase la validación no alcanza, porque puede estar bien formado y aun así perder datos. Por eso exige revisar conexiones y probar antes de activar.

¿Qué necesito además de la skill?

Una instancia de n8n (en la nube o propia) y, para que Claude trabaje sobre ella, el servidor MCP n8n-mcp del mismo autor, conectado con la URL de tu n8n y una clave de su API pública. Sin clave, el MCP igual da documentación de nodos y validación, pero no crea ni edita flujos. Puede cambiar flujos reales, así que el autor recomienda probar en una copia y no editar en la interfaz de n8n mientras trabaja el agente. La skill está en inglés: pide las explicaciones y los nombres de los nodos en español. Si prefieres que te lo armen, mira el servicio de automatización.

Más skills de Automatización

Para seguir con este tema

Elegí qué cookies usamos