Build AI Agents with n8n Workflows: Complete Tutorial (2026)
Master building production AI agents in n8n. Step-by-step tutorial covers the Tools Agent node, Redis memory, MCP servers, multi-agent sub-workflows, and loop prevention.
Building a production n8n AI agent workflow centers on the unified Tools Agent node, Redis Chat Memory, and horizontal Queue Mode workers that consume 400MB to 800MB RAM per process while keeping Redis job enqueue latency under 5ms. Decoupling webhook ingestion from multi-step LLM reasoning eliminates per-step SaaS fees and prevents runaway API loops.
Engineering teams inspect every tool call payload, memory key, and error branch directly on the visual canvas without maintaining boilerplate orchestration code. This n8n AI agent tutorial covers Tools Agent internals, Model Context Protocol (MCP) servers, Supervisor-Worker sub-workflows, and self-hosted Docker Queue Mode.
Key Takeaways
- The n8n AI Agent node standardizes on the unified Tools Agent runtime, deprecating legacy Conversational, SQL, and Plan-and-Execute modes while supporting native MCP Client Tool and sub-workflow delegation.
- Window Buffer Memory stores dialog history inside a single worker’s local Node.js heap and loses context across horizontal containers, making Redis Chat Memory mandatory for Queue Mode deployments.
- Self-hosted Queue Mode clusters run PostgreSQL 16, Redis 7, a main ingress container, and two worker containers on 6 to 9 vCPU and 6GB to 7GB RAM for roughly $45 to $85 monthly.
- Reaching Max Iterations on an n8n AI Agent node can terminate with an execution status of
Success, so production graphs require a downstreamIFvalidation branch and zero-quota Error Trigger workflows.- Routing complex planning to GPT-6.2 Sol ($2.00/$10.00 per 1M tokens) or Claude Sonnet 5.5 ($2.00/$10.00 per 1M) while offloading high-volume triage to Gemini 4 Hydrogen ($1.50/$7.50 per 1M) balances accuracy and spend.
n8n vs LangGraph, CrewAI, and Make: When Visual Workflows Win
Choosing between n8n, Make, CrewAI, and LangGraph depends on whether your bottleneck is SaaS connector plumbing or custom cyclic state machines. Teams comparing n8n vs raw Python code save weeks of integration boilerplate because n8n ships over 400 native nodes alongside live step-by-step payload inspection on the canvas.
Visual Orchestration vs Code-First Agent Frameworks
Evaluating n8n vs Make AI agents highlights a fundamental architectural divide between deterministic data mapping and autonomous tool loops. Make excels at rigid linear routers and array iterators, whereas n8n embeds a LangChain-backed Tools Agent engine that dynamically chooses tools across multi-step reasoning turns.
Comparing n8n vs CrewAI comes down to deterministic guardrails versus conversational persona teams. CrewAI spawns role-playing Python agents that collaborate quickly in prototypes, yet unrestricted inter-agent chatter frequently inflates token consumption and degrades context accuracy in production.
| Platform | Execution Model | State & Loop Control | Self-Hosting Support | Best Production Fit |
|---|---|---|---|---|
| n8n | Visual node runtime + JS/Python Code | Tools Agent + Max Iterations + Sub-workflows |
Full Docker / Queue Mode | SaaS glue, webhooks, MCP bridges, HITL approvals |
| Make | Visual cloud integration router | Deterministic linear branches only | Cloud-only SaaS | Rigid API-to-API sync without autonomous loops |
| CrewAI | Code-first Python role-playing crews | Sequential or hierarchical task handoffs | Self-hosted Python service | Open-ended research and multi-persona drafting |
| LangGraph | Code-first Python/TS state graph | Explicit cyclic nodes, checkpoints, time-travel | Self-hosted Python/TS | Complex stateful loops and strict schema recovery |
Cost structure separates n8n from per-task automation vendors when agent loops execute multiple tool calls. According to n8n Cloud and Self-Hosted Pricing, n8n Cloud bills per completed workflow run rather than per intermediate step, offering 2,500 monthly executions on Starter (EUR 20/month billed annually) and 10,000 on Pro (EUR 50/month billed annually).
Reviewing the core execution boundaries of tool-using AI agents clarifies when visual workflows outperform custom scripts. For small teams, n8n workflow automation AI replaces fragile webhook glue while keeping sensitive CRM and database credentials inside private virtual networks.
The Hybrid Production Pattern: n8n Edge and Stateful Reasoning
When evaluating n8n vs LangGraph for deep enterprise applications, mature teams often deploy both tools in a hybrid split rather than forcing one runtime to handle every layer. Under this pattern, n8n acts as the integration edge handling Slack webhooks, email triggers, OAuth2 token refreshes, and CRM updates.
When an incoming payload requires complex cyclic state machines, multi-branch rollback, or checkpointed time-travel debugging, n8n forwards the sanitized JSON payload to an internal LangGraph API endpoint via HTTP Request. Keep single-loop and two-tier workflows natively inside n8n, and introduce LangGraph only when cyclic state transitions exceed visual canvas clarity.
AI Agent Architecture in n8n: The Tools Agent Engine
The modern n8n AI Agent node runs on the unified Tools Agent engine, which replaces legacy Conversational Agent, SQL Agent, and Plan-and-Execute modes with one standardized tool-calling loop. As documented in the n8n AI Agent Node Documentation, the node binds a chat model, optional memory store, and connected tools into a single iterative cycle.
| Runtime Phase | Connected n8n Component | Execution Responsibility |
|---|---|---|
| 1. Trigger Input | Webhook / Chat Trigger | Captures user prompt and sessionId metadata |
| 2. State Hydration | Redis Chat Memory | Loads serialized conversation history across workers |
| 3. Reasoning & Tool Call | Tools Agent + Chat Model | Evaluates prompt, system contract, and tool JSON schemas |
| 4. Action Execution | MCP Client Tool / HTTP / Code | Runs external API or sub-workflow and feeds result back |
When an upstream trigger delivers a message or webhook payload, the Tools Agent loads prior conversation turns from its attached memory sub-node. It builds a prompt payload containing the system message, conversation history, user input, and JSON schemas for every active tool, then sends that request to the language model.
The Four Core Sub-Nodes: Model, Memory, Tools, and System Message
Every production n8n AI agent architecture relies on four distinct components wired to the central node:
- Chat Model Sub-Node: Connects reasoning backends such as OpenAI, Anthropic, Google Gemini, or local Ollama servers to generate responses and structured tool calls.
- Memory Sub-Node: Persists multi-turn dialog history keyed by a dynamic
sessionIdso follow-up questions retain prior context. - Tool Sub-Nodes: Exposes native SaaS connectors, HTTP Request endpoints, custom JavaScript Code tools, MCP servers, or sub-workflows to the model.
- System Message: Establishes the behavioral contract, output formatting rules, explicit tool selection boundaries, and failure stop conditions.
Engineers can inspect the underlying LangChain TypeScript node definitions directly in the n8n GitHub Repository. Teams moving from standard deterministic flows can review our n8n AI automation tutorial to master trigger routing before adding non-deterministic agent loops.
Why Window Buffer Memory Breaks in Multi-Worker Queue Mode
Comparing Window Buffer Memory vs Redis Chat Memory reveals a critical production failure mode when scaling n8n horizontally. Window Buffer Memory (also labeled Simple Memory) stores conversation turns inside the local RAM of the single Node.js process executing that run.
In Queue Mode, n8n dispatches incoming requests across multiple independent worker containers. When turn one hits n8n-worker-1 and turn two routes to n8n-worker-2, local worker memory has zero knowledge of the first turn, causing the agent to lose session context silently.
Switching to the Redis Chat Memory node solves multi-worker state drift by persisting serialized conversation keys in a centralized Redis instance. As specified in the n8n Redis Chat Memory Node Reference, any worker pulling a job from the queue reads and updates the exact same session key deterministically.
Frontier LLM Selection for n8n Agents: GPT-6.2 vs Claude 5.5 vs Gemini 4
Selecting the right language model for an n8n Tools Agent directly governs tool-call accuracy, structured JSON compliance, and per-run API spend. Frontier releases differ sharply across context ceilings, maximum output tokens, and prompt caching discounts.
| Model | Context Window | Max Output | Input / Output Cost (per 1M) | Cached Read (per 1M) | Best Production Role in n8n |
|---|---|---|---|---|---|
| GPT-6.2 Sol | 200K tokens | 64K tokens | $2.00 / $10.00 | $0.10 | Balanced default for multi-step agentic tool calling |
| GPT-6.2 Astra | 200K tokens | 100K tokens | $8.00 / $40.00 | $0.40 | Heavy architectural planning and complex multi-file synthesis |
| Claude Sonnet 5.5 | 200K - 1M tokens | 128K tokens | $2.00 / $10.00 | $0.10 | Strict JSON extraction, multi-page documents, long-horizon tools |
| Gemini 4 Hydrogen | 1M tokens | 64K tokens | $1.50 / $7.50 | $0.075 | High-throughput triage, low-latency webhooks, 1M-token context |
| DeepSeek-V4.1-Flash | 128K - 1M tokens | 32K tokens | Low-cost API / Open Weights | Provider dependent | Budget batch classification and self-hosted vLLM clusters |
Deterministic Tool Calling and Schema Adherence
Always pin the Chat Model Temperature between 0.2 and 0.4 for n8n AI agent workflows that invoke databases or external APIs. Higher sampling values introduce parameter hallucination when the model fills nested JSON arguments.
Use Claude Sonnet 5.5 (claude-5-5-sonnet-20260928) when extracting structured ERP or invoice fields from messy documents because it adheres tightly to strict output schemas. Select GPT-6.2 Sol (gpt-6.2-sol) as a balanced general orchestrator, and route high-volume classification or routing pre-checks to Gemini 4 Hydrogen (gemini-4-hydrogen) to cut input token spend by 25%.
You can cross-check how these model capabilities map to orchestration trade-offs in our AI agent framework comparison. Prototyping with a high-reasoning model first and migrating deterministic sub-tasks to faster tiers keeps quality high without overpaying at scale.
Self-Hosted Inference with Ollama and vLLM
For air-gapped environments or strict compliance boundaries where prompts cannot leave private infrastructure, attach an Ollama Chat Model or OpenAI-compatible vLLM node. DeepSeek-V4.1-Flash, Muse Ember, and Llama 4 Maverick execute tool schemas locally with zero external token fees.
Self-hosted inference requires verifying that your chosen quantization preserves JSON function-calling syntax. Test at least 20 representative tool invocations locally before promoting an open-weight model into production workflows.
Step-by-Step Tutorial: Building a Tool-Enabled Research Agent
This n8n ai agent tutorial walks through building a multi-tool research assistant that accepts natural language queries, queries live documentation, runs exact arithmetic, and returns grounded answers. Every step uses native nodes available in modern n8n releases.
Steps 1-3: Chat Trigger, Tools Agent, and Model Binding
Create a blank workflow and drop a When chat message received trigger node onto the canvas to expose an interactive test pane. For live integrations, swap this node for a Webhook trigger configured to accept HTTP POST requests with a sessionId field.
- Add an AI Agent node after the trigger and confirm its Agent mode is set to Tools Agent.
- Open Options inside the AI Agent node and set Max Iterations to
10to enforce a hard ceiling on reasoning turns. - Connect an OpenAI Chat Model or Anthropic Chat Model node to the
Chat Modelport, selectgpt-6.2-solorclaude-5-5-sonnet-20260928, and setTemperatureto0.3.
Setting Max Iterations to 10 gives the agent enough turns to recover from a single search refinement without allowing runaway token consumption. Keep complex tasks bounded between 5 and 10 iterations whenever possible.
Steps 4-5: Attaching Redis Chat Memory and Tavily Search
Connect a Redis Chat Memory node (or Window Buffer Memory for single-instance local testing only) to the Memory port of the Tools Agent. Map Session ID dynamically to {{ $json.sessionId }} and set Context Window Length to 10 turns so prompts stay compact.
| Execution Stage | n8n Node Type | Key Configuration | Data Contract |
|---|---|---|---|
| 1. Entry Trigger | Chat Trigger / Webhook | POST JSON payload |
Passes chatInput and unique sessionId |
| 2. Orchestrator | AI Agent (Tools Agent) |
Max Iterations: 10 |
Manages thought, tool call, and observation loop |
| 3. Reasoning Brain | Chat Model (gpt-6.2-sol) |
Temperature: 0.3 |
Emits structured tool arguments or final text |
| 4. Shared State | Redis Chat Memory | Context Window: 10 |
Reads and writes serialized history by sessionId |
| 5. Live Tools | Tavily Search + Calculator | Tool descriptions explicit | Returns pre-filtered snippets and exact math |
Attach a Tavily Search tool node and a Calculator tool node to the Tools port. Unlike raw search scrapers, Tavily returns clean text snippets tailored for LLM context windows, as detailed in the Tavily Search API Endpoint Reference.
Step 6: Writing a Deterministic System Prompt Template
Open the System Message field inside the AI Agent node and define explicit tool boundaries, error-stopping rules, and output formatting instructions. Structured XML tags prevent prompt instructions from colliding with retrieved tool snippets.
<role>
You are a technical research assistant answering engineering questions with verified web data and exact arithmetic.
</role>
<rules>
1. Always invoke the Tavily Search tool for software versions, pricing figures, and release facts.
2. Always invoke the Calculator tool for arithmetic comparisons and cost totals.
3. If a tool fails or returns empty results twice, stop retrying immediately and state the exact missing data.
4. Format responses with concise markdown headings and bullet points, ending immediately after the final answer.
</rules>
Open the built-in chat panel and submit: "Calculate the input token cost difference between Claude Sonnet 5.5 and Gemini 4 Hydrogen for 500,000 input tokens." Inspect the Execution Log to verify that the agent queries Tavily or uses verified context, calls the Calculator node, and emits the result in under three turns.
Connecting MCP Servers, Custom APIs, and Enterprise Knowledge Bases
Enterprise workflows rarely stop at built-in search and math tools. To build AI agents n8n teams rely on in production, connect external Model Context Protocol servers, custom JavaScript functions, and internal REST APIs with explicit parameter schemas.
Dynamic Tool Discovery with the MCP Client Tool
The MCP Client Tool (n8n-nodes-langchain.toolmcp) sits under AI > Tools > MCP servers in the node panel and connects your AI Agent directly to external MCP tool servers. Built on the Model Context Protocol Specification, it discovers remote tools dynamically over Streamable HTTP or SSE transports.
When configuring the node to connect MCP server to n8n AI agent, use the Tools to Include dropdown to enforce least privilege by choosing All, Selected, or All Except. Modern n8n releases also support generic OAuth2 API credentials alongside native MCP OAuth2, letting you reuse existing enterprise app tokens across HTTP Request and MCP tools as covered in the n8n MCP Client Tool Documentation.
[!IMPORTANT] If you expose n8n workflows via an MCP Server Trigger in Queue Mode with multiple webhook replicas, Streamable HTTP and SSE sessions will drop when requests bounce between containers. Configure your Nginx or cloud ingress to pin all
/mcp*traffic to a single dedicated webhook replica and disable proxy buffering (proxy_buffering off;).
Custom Logic Tools via the Code Node
When business rules live in internal lookup tables or require deterministic validation before returning data to the LLM, wire a Custom n8n Tool using the Code node. Give the tool a clear name such as query_inventory and a precise description explaining when to invoke it and what arguments it expects.
// Parse structured SKU parameter supplied by the Tools Agent
const queryParams = $input.first().json;
const targetSku = String(queryParams.sku || '').trim().toUpperCase();
const inventoryDatabase = {
'SKU-SRV-01': { item: 'Compute Node Alpha', stock: 14, unitPrice: 1200, restockDays: 0 },
'SKU-SRV-02': { item: 'Storage Array Beta', stock: 0, unitPrice: 3400, restockDays: 5 },
'SKU-NET-01': { item: 'Managed Switch 10G', stock: 8, unitPrice: 650, restockDays: 0 }
};
const record = inventoryDatabase[targetSku];
if (!record) {
return [{ json: { found: false, error: `SKU ${targetSku} not found in catalog.` } }];
}
return [{
json: {
found: true,
sku: targetSku,
productName: record.item,
inStock: record.stock > 0,
availableUnits: record.stock,
priceUsd: record.unitPrice,
estimatedRestockDays: record.restockDays
}
}];
Returning compact, explicit JSON fields (found, inStock, availableUnits) prevents the language model from guessing missing fields. Always truncate massive arrays or raw database dumps inside the Code node so oversized tool responses never flood the agent’s context window.
HTTP Request Tools and Notion Rate-Limit Guardrails
When an internal microservice lacks a dedicated integration node, configure an n8n custom HTTP Request tool using $fromAI() placeholders so the Tools Agent populates path or query parameters dynamically. Define strict parameter descriptions and authentication headers rather than exposing raw unauthenticated endpoints.
| Parameter | Configuration Value | Purpose |
|---|---|---|
| HTTP Method | GET |
Read-only customer record lookup |
| Endpoint URL | https://api.company.internal/v2/customers/{{ $fromAI('customerId', 'Unique customer ID string') }} |
Binds LLM argument safely to URL path |
| Authentication | Header Auth (Authorization: Bearer ...) |
Injects encrypted n8n credential without exposing secrets to prompt |
| Timeout / Retries | 15000ms timeout, 3 retries at 2000ms |
Prevents hung TCP sockets from stalling worker threads |
For internal company wikis, wire a Notion tool node to fetch database pages filtered dynamically by topic. Because the Notion REST API enforces an average limit of 3 requests per second per integration token, follow the Notion API Rate Limits Documentation and cap Page Size between 3 and 5 records with a 350ms wait interval during batch syncs.
| Notion Tool Field | Setting | Operational Guardrail |
|---|---|---|
| Resource & Operation | Database Page / Get Many |
Restricts agent to read-only policy lookups |
| Filter Expression | Title contains "{{ $fromAI('searchTopic', 'Concise topic phrase') }}" |
Prevents full-database table scans |
| Sort Order | Last Edited Time (Descending) |
Surfaces current SOPs first |
| Page Size Limit | 3 |
Caps returned tokens and respects 3 req/sec rate limit |
When documentation libraries grow past simple keyword filters, swap basic database queries for semantic retrieval backed by Qdrant or Pinecone. Follow our RAG chatbot architecture guide to pair dense embeddings with n8n Vector Store tools.
Multi-Agent Workflows and Production Blueprints in n8n
Scaling an n8n multi agent workflow past simple chat assistants requires separating domain responsibilities across modular workflows. Packing ten tools and a 2,000-token system prompt into one monolithic Tools Agent degrades tool selection accuracy and complicates testing.
Supervisor-Worker Multi-Agent Orchestration with Sub-Workflows
To build a clean n8n sub workflow AI agent, adopt a two-tier Supervisor-Worker topology backed by the Execute Sub-workflow tool node and When Executed by Another Workflow triggers. The top-level Supervisor workflow owns the user trigger and routes specialized tasks to independent worker workflows (such as a Research Worker, SQL Order Worker, or Billing Worker).
As detailed in the n8n Sub-Workflows Architecture Guide, isolating worker agents in separate workflows lets teams version, test, and swap prompts per domain without touching the master canvas. Crucially, every worker sub-workflow must maintain an atomic input-to-output contract: accept structured parameters, run its isolated task, and return one consolidated string or JSON object.
Never embed mid-run user clarification prompts inside a worker sub-workflow called as a tool. Because the Supervisor’s tool call expects a synchronous final response, pausing a sub-workflow for conversational user input breaks the parent execution context; keep multi-turn chat loops strictly in the top-level workflow and place n8n human in the loop wait node approvals (Slack or Teams confirmation cards) before high-risk write tools.
Reviewing multi-agent coordination workflows helps teams decide between hierarchical supervisors and parallel fan-out topologies.
Production Blueprint: Tier-1 Support Triage and Invoice Extraction
Production teams routinely deploy two deterministic-plus-agentic patterns across customer operations and finance:
| Blueprint | Trigger & Pre-Processing | Agent & Memory Layer | Downstream Verification & Escalation |
|---|---|---|---|
| Tier-1 Support Triage | Incoming Webhook or Slack event | Tools Agent (GPT-6.2 Sol) + Redis Chat Memory + Notion & Zendesk tools |
IF check verifies confidence; unresolved tickets create Zendesk issue and page on-call Slack |
| Invoice Extraction | Email Trigger (PDF attachment) + OCR binary parser | Tools Agent (Claude Sonnet 5.5) enforcing strict line-item JSON schema |
Schema validator posts valid records to ERP API; invalid rows route to quarantine queue for human review |
Separating deterministic OCR and schema validation nodes outside the LLM call guarantees malformed vendor PDFs never write partial totals into accounting databases. Keep high-risk financial mutations gated behind strict validation nodes.
Production Blueprint: Bi-Directional Slack Bot with Thread Continuity
Building an n8n slack bot thread continuity workflow starts with a Webhook listening for Slack app_mention events. Before invoking any LLM node, verify the incoming X-Slack-Signature header using HMAC-SHA256 and your app signing secret per the Slack Request Verification Documentation to block spoofed requests.
Acknowledge Slack within 3 seconds, filter out bot self-mentions deterministically, and bind Redis Chat Memory using the incoming thread_ts value as the Session ID. Passing the same thread_ts back to the final Slack reply node keeps channel conversations organized while isolating per-thread memory across parallel team discussions.
Production Error Handling, Loop Prevention, and Guardrails
Unhandled API timeouts, ambiguous tool errors, and unbounded retries turn autonomous workflows into expensive incidents. Implementing layered n8n error handling ai agent patterns isolates failures before they exhaust token budgets or crash worker containers.
| Guardrail Layer | Enforcement Mechanism | Failure Mode Prevented |
|---|---|---|
| 1. Ingress Validation | HMAC-SHA256 verification + Split In Batches |
Spoofed webhooks and bulk heap exhaustion |
| 2. Tool & Prompt Bounds | Active tools only + two-retry stop rule | Deactivated tool loop bugs and blind retries |
| 3. Turn Cap Breaker | Max Iterations (5 to 10) + staticData counter |
Unbounded reasoning loops and runaway token spend |
| 4. Output Gate | Downstream IF validation node |
Silent Success termination on capped or empty output |
| 5. Async Recovery | Dedicated Error Trigger workflow | Unmonitored crashes without burning Cloud quotas |
Max Iterations, Downstream IF Checks, and Deactivated Tool Hygiene
To prevent infinite loop n8n ai agent failures, start by configuring an explicit n8n max iterations circuit breaker between 5 and 10 inside the Tools Agent options. However, n8n max iterations returns success as the execution status even when the agent halts early without completing the task.
Always wire an IF node immediately downstream from the AI Agent node to inspect whether the output string is empty, malformed, or matches a fallback timeout marker. Route failed validations directly to a safe user reply and ops alert.
Watch out for the n8n deactivated tool loop bug during iterative testing. Leaving a tool node toggled off while still wired to the AI Agent canvas can confuse model tool routers into retrying the missing tool until Max Iterations expires, so disconnect disabled tools physically instead of muting them.
When processing bulk records, never feed hundreds of items directly into one agent execution. Wrap the pipeline with an n8n split in batches ai agent pattern (Split In Batches set to 1 to 5 items) paired with a Code node circuit breaker using $workflow.staticData to enforce a hard batch ceiling:
// Hard batch safety breaker placed before the AI Agent node
const state = $workflow.staticData;
state.agentStepCount = (state.agentStepCount || 0) + 1;
const MAX_BATCH_CALLS = 20;
if (state.agentStepCount > MAX_BATCH_CALLS) {
state.agentStepCount = 0;
throw new Error('Safety ceiling exceeded: halting batch AI Agent execution.');
}
return $input.all();
Reset state.agentStepCount cleanly at the end of a completed batch run so subsequent triggers start from zero. Pairing batch chunking with prompt-level stop rules (“never retry an identical failing tool call more than twice”) eliminates nearly all n8n ai agent infinite loop incidents.
Zero-Quota Error Trigger Workflows and Timeout Policies
Attach a dedicated Error Trigger workflow to every production agent pipeline so unhandled exceptions fire asynchronous alerts to Slack or PagerDuty with the exact workflow ID, failing node name, and execution URL. Per the n8n Error Trigger Node Documentation, Error Trigger runs do not count against monthly Cloud plan execution quotas.
Align logging and external API retries with the OWASP Error Handling Cheat Sheet so raw stack traces and bearer tokens never leak into user-facing chat replies. Enforce strict 30-second execution timeouts on LLM and HTTP Request nodes and ensure no agent tool emits an event that re-triggers its own parent webhook.
Self-Hosted Queue Mode: Docker Compose, Redis Sizing, and Benchmarks
In default single-process mode, long-running LLM reasoning loops and heavy JSON transformations block the Node.js event loop, causing incoming webhooks to time out and the editor UI to freeze. Switching to Queue Mode decouples webhook ingestion from execution workers using PostgreSQL and Redis.
Self-Hosted Docker Queue Mode vs n8n Cloud Economics
Comparing n8n self hosted vs cloud architectures shows a clear crossover point for high-frequency agent pipelines. n8n Cloud eliminates server maintenance, database backups, and TLS setup, making Starter and Pro ideal for moderate volumes under 10,000 monthly runs.
Self-hosting Community Edition removes monthly execution caps completely, leaving you paying only for raw VPS compute and direct model API tokens. Benchmarks from production n8n queue mode docker compose deployments show that active workers executing concurrent AI Agent loops consume 400MB to 800MB RAM per worker process (compared to ~150MB for standard utility flows), while Redis job hand-off adds under 5ms of latency under normal load.
| Cluster Component | Baseline Spec | Estimated RAM | Monthly Infrastructure Cost |
|---|---|---|---|
| n8n Main + Webhook Ingress | 2 vCPU | 2 GB | $10 to $20 |
| Redis 7 (Queue + Chat Memory) | 1 vCPU | 1 GB | $5 to $10 |
| PostgreSQL 16 | 1 to 2 vCPU | 1 to 2 GB | $10 to $15 |
| n8n Workers (2 Containers) | 2 to 4 vCPU | 2 GB (1 GB each) | $20 to $40 |
| Total Baseline Cluster | 6 to 9 vCPU | 6 to 7 GB RAM | $45 to $85 / month |
Scale worker replicas horizontally whenever sustained worker CPU utilization exceeds 70% during peak agent traffic. Remember that n8n redis queue mode worker memory requires sizing Redis separately when it serves both Bull queues and Redis Chat Memory (~1KB to 5KB per stored dialog turn, totaling 512MB to 1GB RAM for busy environments).
Production Docker Compose with PostgreSQL and Redis
Queue Mode requires PostgreSQL (SQLite is unsupported for concurrent multi-container writes) and Redis, with EXECUTIONS_MODE=queue and identical QUEUE_BULL_REDIS_HOST settings across main and worker containers as outlined in the n8n Queue Mode Scaling Documentation. Enable EXECUTIONS_DATA_PRUNE=true so verbose LLM tool JSON logs do not bloat PostgreSQL storage.
services:
postgres:
image: postgres:16-alpine
restart: always
environment:
POSTGRES_USER: n8n_user
POSTGRES_PASSWORD: change_me_strong_password
POSTGRES_DB: n8n_production
volumes:
- postgres_storage:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -h localhost -U n8n_user -d n8n_production"]
interval: 5s
timeout: 5s
retries: 10
redis:
image: redis:7-alpine
restart: always
command: redis-server --appendonly yes
volumes:
- redis_storage:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 5s
retries: 10
n8n-main:
image: n8nio/n8n:latest
restart: always
ports:
- "127.0.0.1:5678:5678"
environment:
- DB_TYPE=postgresdb
- DB_POSTGRESDB_HOST=postgres
- DB_POSTGRESDB_PORT=5432
- DB_POSTGRESDB_DATABASE=n8n_production
- DB_POSTGRESDB_USER=n8n_user
- DB_POSTGRESDB_PASSWORD=change_me_strong_password
- EXECUTIONS_MODE=queue
- QUEUE_BULL_REDIS_HOST=redis
- QUEUE_BULL_REDIS_PORT=6379
- EXECUTIONS_DATA_PRUNE=true
- EXECUTIONS_DATA_MAX_AGE=168
- N8N_ENCRYPTION_KEY=replace_with_openssl_rand_hex_32
- WEBHOOK_URL=https://n8n.yourdomain.com/
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
volumes:
- n8n_storage:/home/node/.n8n
n8n-worker:
image: n8nio/n8n:latest
restart: always
command: worker
environment:
- DB_TYPE=postgresdb
- DB_POSTGRESDB_HOST=postgres
- DB_POSTGRESDB_PORT=5432
- DB_POSTGRESDB_DATABASE=n8n_production
- DB_POSTGRESDB_USER=n8n_user
- DB_POSTGRESDB_PASSWORD=change_me_strong_password
- EXECUTIONS_MODE=queue
- QUEUE_BULL_REDIS_HOST=redis
- QUEUE_BULL_REDIS_PORT=6379
- EXECUTIONS_DATA_PRUNE=true
- EXECUTIONS_DATA_MAX_AGE=168
- N8N_ENCRYPTION_KEY=replace_with_openssl_rand_hex_32
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
volumes:
- n8n_storage:/home/node/.n8n
volumes:
postgres_storage:
redis_storage:
n8n_storage:
Bind port 5678 to 127.0.0.1 behind a Caddy or Nginx reverse proxy handling TLS termination, and back up both PostgreSQL and N8N_ENCRYPTION_KEY daily to encrypted object storage.
Troubleshooting Queue Mode Jobs Stuck and OOM Crashes
Three infrastructure issues account for most self-hosted scaling failures when running AI agents:
- n8n Queue Mode Jobs Stuck (“Starting Soon”): Verify that
EXECUTIONS_MODE=queue,QUEUE_BULL_REDIS_HOST, andN8N_ENCRYPTION_KEYmatch identically onn8n-mainand alln8n-workercontainers. If Redis throwsERR Error running scripton Bull keys after an upgrade or mode switch, confirm Redis 7+ is running with Lua scripting enabled and flush stale test keys cleanly. - n8n JavaScript Heap Out of Memory: Massive PDF extracts or verbose MCP responses inside concurrent loops spike V8 heap usage rapidly. Strip unnecessary HTML and binary fields inside tool nodes before returning data to the AI Agent, and isolate heavy Code nodes using n8n Task Runners.
- Redis OOM Evicting Queue Keys: Separate your Bull job queue Redis database or configure
noevictionfor queue workloads so active jobs are never evicted mid-execution, while applying explicit TTLs toRedis Chat Memorysession keys.
Frequently Asked Questions
Can you build AI agents in n8n without coding?
Yes, n8n wires the Tools Agent node, chat model sub-nodes, Redis Chat Memory, and over 400 native app integrations visually on the canvas without writing orchestration code. Custom JavaScript or Python inside Code nodes is only needed for specialized payload sanitization, batch circuit breakers, or internal lookup logic.
How do you build a multi-agent workflow in n8n?
Use a two-tier Supervisor-Worker pattern where a primary AI Agent delegates specialized tasks to independent sub-workflows via the Execute Sub-workflow tool and When Executed by Another Workflow triggers. Keep each worker sub-workflow atomic so it returns one structured response without pausing for mid-run conversational input.
What is the difference between n8n and LangGraph or CrewAI?
n8n is a visual low-code workflow runtime built for SaaS glue, webhook triggers, and node-level payload debugging, whereas LangGraph builds code-first cyclic state machines and CrewAI focuses on Python role-playing teams. Production engineering teams frequently run n8n as the integration edge and call a LangGraph service for complex cyclic reasoning.
How do you prevent infinite loops in n8n AI Agent workflows?
Set Max Iterations between 5 and 10 on the AI Agent node and add a downstream IF node to catch empty or capped outputs, since hitting the iteration cap can still report Success. Physically disconnect deactivated tools from the canvas, add a two-retry stop rule in the system prompt, and wrap bulk runs with Split In Batches plus a staticData counter.
Why does n8n Queue Mode require Redis Chat Memory instead of Window Buffer Memory?
Window Buffer Memory stores dialog turns inside the local Node.js RAM of whichever single worker executed that request. Because Queue Mode routes consecutive user turns across separate worker containers, Redis Chat Memory is required to share serialized conversation state across all workers.
How does n8n count executions and pricing for AI agent loops?
n8n Cloud bills per completed workflow execution rather than per intermediate tool call, providing 2,500 monthly executions on Starter (EUR 20/month billed annually) and 10,000 on Pro (EUR 50/month billed annually). Dedicated Error Trigger runs do not count against Cloud quotas, and self-hosted Community Edition removes execution limits completely.
How do you connect an MCP server to an n8n AI Agent?
Attach the MCP Client Tool node under the AI Tools MCP servers panel to your AI Agent, configure its Streamable HTTP or SSE URL with Bearer or OAuth2 credentials, and filter exposed tools using All, Selected, or All Except. When self-hosting MCP Server Triggers in Queue Mode, pin all /mcp* ingress traffic to a single webhook replica with proxy buffering disabled.