Установка
SKILL.md
n8n Workflow Patterns
Proven architectural patterns for building n8n workflows.
The 6 Core Patterns
Based on analysis of real workflow usage:
-
Webhook Processing (Most Common)
- Receive HTTP requests → Process → Output
- Pattern: Webhook → Validate → Transform → Respond/Notify
-
HTTP API Integration
- Fetch from REST APIs → Transform → Store/Use
- Pattern: Trigger → HTTP Request → Transform → Action → Error Handler
-
Database Operations
- Read/Write/Sync database data
- Pattern: Schedule → Query → Transform → Write → Verify
-
AI Agent Workflow
- AI agents with tools and memory
- Pattern: Trigger → AI Agent (Model + Tools + Memory) → Output
-
Scheduled Tasks
- Recurring automation workflows
- Pattern: Schedule → Fetch → Process → Deliver → Log
-
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.
- Code - Custom JavaScript/Python
3. Transformation
- Set - Map/transform fields
- Code - Complex logic
- IF/Switch - Conditional routing
- Merge - Combine data streams
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 (Set, Code, IF)
- <!-- -->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
activateWorkflowoperation - <!-- -->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.
- Validate. Run
validate_workflowon the full JSON during build, orn8n_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. - Verify the connections. Pull the workflow with
n8n_get_workflow({ id })and read theconnectionsobject 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 whoseuseDataOfInputdoesn'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.) - Test. Run
n8n_test_workflowand inspect the output vian8n_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. - Activate only after the first three pass — using
n8n_update_partial_workflowwith theactivateWorkflowoperation. 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 completemain[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: 1is 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 usually don't need the loop — a single All Items Code node processes the whole set far cheaper.
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
For APIs without multi-ID filtering, use id_from + date windowing for efficient pagination:
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:
- Prefer fewer, fatter All-Items nodes over long transform chains. Every node→node hop re-copies all items (~0.05 ms/item per hop), so six chained Code/Set nodes cost ~7× one All-Items Code node doing the same steps. Consolidate the hot path.
- Use Code "Run Once for All Items," not "Each Item" — ~0.02 ms/item vs ~0.6 ms/item (≈25–30×). A chain of Each-Item Code nodes is the worst case; the per-item tax multiplies by node count.
- Maximize batchSize in SplitInBatches loops (see the Batch Processing pattern above) — iterations are the cost.
- 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
appendon sheets with formula columns — it breaks formulas. Use Google Sheets APIvalues.update(PUT) via HTTP Request node with agoogleApicredential - Write numbers, not strings for formula-dependent columns — string "4.98" breaks
ADD()formulas. UseparseFloat()in a Code node - Per-item execution trap: Google Sheets nodes execute once per input item. If you need a single bulk write, aggregate items into one in a Code node first
- UNFORMATTED_VALUE returns numbers, not text like "N/A" — filter explicitly in Code nodes
Google Drive
convertToGoogleDocument: truecreates 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/viewlinks
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: Используйте {{}} вокруг выражений
- Подробности см. в навыке n8n Expression Syntax
Интеграция с другими навыками
Эти навыки работают вместе с Workflow Patterns:
n8n MCP Tools Expert - Используйте для:
- Поиск узлов для вашего паттерна (search_nodes)
- Понимание операций узлов (get_node)
- Создание рабочих процессов (n8n_create_workflow)
- Развёртывание шаблонов (n8n_deploy_template)
- Используйте
tools_documentation({topic: "ai_agents_guide", depth: "full"})для руководства по AI-паттернам - Управление таблицами данных с помощью
n8n_manage_datatable
n8n Expression Syntax - Используйте для:
- Написание выражений в узлах преобразования
- Правильный доступ к данным webhook ({{$json.body.field}})
- Ссылка на предыдущие узлы ({{$node["Node Name"].json.field}})
n8n Node Configuration - Используйте для:
- Настройка конкретных операций для узлов паттерна
- Понимание требований, специфичных для узлов
n8n Validation Expert - Используйте для:
- Валидация структуры рабочего процесса
- Исправление ошибок валидации
- Обеспечение корректности рабочего процесса перед развёртыванием
Статистика паттернов
Распространённые паттерны рабочих процессов:
Самые распространённые триггеры:
- Webhook - 35%
- Schedule (периодические задачи) - 28%
- Manual (тестирование/администрирование) - 22%
- Триггеры сервисов (Slack, email и т.д.) - 15%
Самые распространённые преобразования:
- Set (сопоставление полей) - 68%
- Code (пользовательская логика) - 42%
- IF (условная маршрутизация) - 38%
- Switch (мультиусловие) - 18%
Самые распространённые выходы:
- HTTP Request (API) - 45%
- Slack - 32%
- Запись в базу данных - 28%
- Email - 24%
Средняя сложность рабочего процесса:
- Простой (3-5 узлов): 42%
- Средний (6-10 узлов): 38%
- Сложный (11+ узлов): 20%
Примеры быстрого старта
Пример 1: Простой Webhook → Slack
1. Webhook (path: "form-submit", POST)
2. Set (map form fields)
3. Slack (post message to #notifications)
Пример 2: Запланированный отчёт
1. Schedule (daily at 9 AM)
2. HTTP Request (fetch analytics)
3. Code (aggregate data)
4. Email (send formatted report)
5. Error Trigger → Slack (notify on failure)
Пример 3: Синхронизация базы данных
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)
Пример 4: AI-ассистент
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)
Пример 5: Интеграция с API
1. Manual Trigger (for testing)
2. HTTP Request (GET /api/users)
3. Split In Batches (process 100 at a time)
4. Set (transform user data)
5. Postgres (upsert users)
6. Loop (back to step 3 until done)
Подробные файлы паттернов
Для получения исчерпывающего руководства по каждому паттерну:
- webhook_processing.md - Паттерны webhook, структура данных, обработка ответов
- http_api_integration.md - REST API, аутентификация, пагинация, повторные попытки
- database_operations.md - Запросы, синхронизация, транзакции, пакетная обработка
- ai_agent_workflow.md - AI-агенты, инструменты, память, узлы langchain
- scheduled_tasks.md - Расписания Cron, отчёты, задачи обслуживания
Реальные примеры шаблонов
Из библиотеки шаблонов n8n:
Шаблон #2947: Погода в Slack
- Паттерн: Запланированная задача
- Узлы: Schedule → HTTP Request (API погоды) → Set → Slack
- Сложность: Простой (4 узла)
Обработка Webhook: Самый распространённый паттерн
- Наиболее часто: Отправка форм, платёжные webhook, интеграции чатов
HTTP API: Распространённый паттерн
- Наиболее часто: Получение данных, интеграции со сторонними сервисами
Операции с базой данных: Распространённый паттерн
- Наиболее часто: ETL, синхронизация данных, рабочие процессы резервного копирования
AI-агенты: Растущее использование
- Наиболее часто: Чат-боты, генерация контента, анализ данных
Используйте search_templates и get_template из инструментов n8n-mcp для поиска примеров!
Лучшие практики
✅ Do
- Начинайте с простейшего паттерна, который решает вашу задачу
- Планируйте структуру рабочего процесса перед созданием
- Используйте обработку ошибок во всех рабочих процессах
- Тестируйте с образцами данных перед активацией
- Следуйте контрольному списку создания рабочего процесса
- Используйте описательные имена узлов
- Документируйте сложные рабочие процессы (поле notes)
- Отслеживайте выполнения рабочих процессов после развёртывания
❌ Не
- Создавайте рабочие процессы за один раз (итерируйте! в среднем 56 с между правками)
- Пропускайте валидацию перед активацией
- Игнорируйте сценарии ошибок
- Используйте сложные паттерны, когда достаточно простых
- Жёстко кодируйте учётные данные в параметрах
- Забывайте обрабатывать случаи с пустыми данными
- Смешивайте несколько паттернов без чётких границ
- Развёртывайте без тестирования
Резюме
Ключевые моменты:
- 6 основных паттернов покрывают 90%+ вариантов использования рабочих процессов
- Обработка Webhook является самым распространённым паттерном
- Используйте контрольный список создания рабочего процесса для каждого рабочего процесса
- Планируйте паттерн → Выбирайте узлы → Создавайте → Валидируйте → Развёртывайте
- Интегрируйтесь с другими навыками для полной разработки рабочего процесса
Следующие шаги:
- Определите паттерн вашего варианта использования
- Прочитайте подробный файл паттерна
- Используйте n8n MCP Tools Expert для поиска узлов
- Следуйте контрольному списку создания рабочего процесса
- Используйте n8n Validation Expert для валидации
Связанные навыки:
- n8n MCP Tools Expert - Поиск и настройка узлов
- n8n Expression Syntax - Правильное написание выражений
- n8n Validation Expert - Валидация и исправление ошибок
- n8n Node Configuration - Настройка конкретных операций
Вставить в README
Ссылка на карточку для вашего README — без картинок и счётчиков.
[DarkPlay: n8n-workflow-patterns](https://darkplay.ru/ai/skills/czlonkowski-n8n-skills-n8n-workflow-patterns)
Из того же репозитория
Похожие скиллы и другие разделы каталога
Самые востребованные скиллов раздела по установкам и звёздам.
find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.Соседние разделы каталога: возможно, нужный инструмент живёт там.
superpowersobra · Базовая библиотека навыков для Claude Code: TDD, отладка, паттерны совместной работы и…
eccaffaan-m · Нативный для harness операторский слой ECC: 67 агентов, 278 навыков, 94 шима устаревших…
Add Language Rulesaffaan-m · Каркас команды workflow для add-language-rules в everything-claude-code.
Chief Of Staffaffaan-m · Личный руководитель коммуникаций, который сортирует почту, Slack, LINE и Messenger…
Code Architectaffaan-m · Проектирует архитектуру функций, анализируя существующие паттерны и соглашения кодовой…
Csharp Revieweraffaan-m · Ревьюер C#: конвенции .NET, async, безопасность, nullable-типы, производительность.
Database Migrationaffaan-m · Каркас команды workflow для database-migration в everything-claude-code.
Django Revieweraffaan-m · Ревьюер Django: ORM, DRF, миграции, безопасность и production-практики.
Feature Developmentaffaan-m · Каркас команды workflow для feature-development в everything-claude-code.
Flutter Revieweraffaan-m · Ревьюер кода Flutter и Dart: виджеты, управление состоянием, идиомы и архитектура.Лучшие ИИ-инструменты для автоматизации и ассистентов
Подборка ИИ-ассистентов для автоматизации рутины и ускорения рабочих процессов. Сервисы, которые берут на себя переписку, анализ данных, ведение базы знаний и подготовку продаж, эк
Give Me Public
AITunnelAitunnel
STIVAStiva
Wikibot (Викибот)Wikibot
mymeet.aiMymeet
InsighterInsighter
TGHuntTghunt
LegiscanLegiscan
RouterAIRouterai
Wikibot 1.0 (Викибот)WikibotЛучшие ИИ-инструменты для генерации видео
Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,
VEED.IOVeed
MootionMootion
Sora (OpenAI)OpenAI
viralpulse.appViralpulse
Viral Maker AIViral-makerЛучшие ИИ-инструменты для генерации текста и копирайтинга
Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра
NeuroscribeNeuroscribe
GoGPTGogpt
НейроТекстерNeuro-texter
ChatGPTOpenAI
Cosmo ScribeCosmoscribe
Memo HelperCopilot33
LibraChatLibrachat