Blog
n8n in Production 2026: My Complete Self-Hosted Setup, AI Pipelines & Real Cost Breakdown
Spis treści
I've been running n8n in production for over two years. Multiple clients, dozens of active workflows, millions of tasks executed. And I still get the same question from developers and business owners:
"Is n8n actually production-ready, or is it a toy you self-host and then everything breaks at 3am?"
Fair question. The answer is: it depends entirely on how you set it up.
I've seen n8n installations that crash weekly and I've seen ones that handle 50,000+ tasks per day without breaking a sweat. The difference isn't the software — it's the setup, the architecture decisions, and knowing what n8n is actually good at versus where you should write custom code instead.
This post is the guide I wish I had two years ago. No YouTube fluff, no "just click this button" tutorials. We're talking Docker Compose with PostgreSQL backend, nginx reverse proxy, automated backups, proper monitoring, and on top of that — real AI workflow pipelines with GPT-4 that I've deployed for actual clients.
Let's get into it.
Table of Contents
1. Why n8n Self-Hosted Beats SaaS at Scale
Let me give you the numbers first.
One of my clients was on Zapier Team plan: $449/month for 50,000 tasks. They had AI steps in their workflows (Zapier AI add-ons), which pushed it to ~$600/month with overages.
After migrating to n8n self-hosted on a $40/month VPS (4 vCPU, 8GB RAM, 160GB SSD — a standard Hetzner CX31): same workflows, same task volume, same AI integrations via direct OpenAI API. Monthly cost dropped to ~$65/month total (VPS + OpenAI API usage).
That's a 90% cost reduction for identical functionality.
But cost isn't the only argument. n8n self-hosted gives you:
No task limits — execute 1M tasks/month on the same $40 VPS if your server handles it
Full data sovereignty — customer data never touches Zapier's servers
Custom nodes — build any integration in TypeScript that doesn't exist in the marketplace
Direct database access — query your PostgreSQL right inside workflows, no API wrapper needed
Unlimited credentials — Zapier charges per connected app, n8n doesn't care
The tradeoff: you own the ops. Server goes down, that's on you. But with proper Docker setup and basic monitoring, uptime isn't really a concern.
2. Production Docker Compose — The Full Config
Here's my actual production docker-compose.yml. Not a tutorial toy — this is what runs real client workloads.
version: "3.8"
services:
n8n:
image: n8nio/n8n:latest
container_name: n8n
restart: unless-stopped
ports:
- "127.0.0.1:5678:5678"
environment:
- DB_TYPE=postgresdb
- DB_POSTGRESDB_HOST=postgres
- DB_POSTGRESDB_PORT=5432
- DB_POSTGRESDB_DATABASE=${POSTGRES_DB}
- DB_POSTGRESDB_USER=${POSTGRES_USER}
- DB_POSTGRESDB_PASSWORD=${POSTGRES_PASSWORD}
- N8N_BASIC_AUTH_ACTIVE=false
- N8N_HOST=${N8N_HOST}
- N8N_PORT=5678
- N8N_PROTOCOL=https
- WEBHOOK_URL=https://${N8N_HOST}/
- EXECUTIONS_PROCESS=main
- EXECUTIONS_DATA_SAVE_ON_ERROR=all
- EXECUTIONS_DATA_SAVE_ON_SUCCESS=none
- EXECUTIONS_DATA_SAVE_MANUAL_EXECUTIONS=true
- EXECUTIONS_DATA_PRUNE=true
- EXECUTIONS_DATA_MAX_AGE=168
- GENERIC_TIMEZONE=Europe/Warsaw
- N8N_ENCRYPTION_KEY=${N8N_ENCRYPTION_KEY}
- N8N_USER_MANAGEMENT_JWT_SECRET=${JWT_SECRET}
- QUEUE_BULL_REDIS_HOST=redis
- QUEUE_BULL_REDIS_PORT=6379
- EXECUTIONS_MODE=queue
volumes:
- n8n_data:/home/node/.n8n
- /var/local/n8n/custom-nodes:/home/node/.n8n/custom
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
networks:
- n8n_network
n8n_worker:
image: n8nio/n8n:latest
container_name: n8n_worker
restart: unless-stopped
command: worker
environment:
- DB_TYPE=postgresdb
- DB_POSTGRESDB_HOST=postgres
- DB_POSTGRESDB_PORT=5432
- DB_POSTGRESDB_DATABASE=${POSTGRES_DB}
- DB_POSTGRESDB_USER=${POSTGRES_USER}
- DB_POSTGRESDB_PASSWORD=${POSTGRES_PASSWORD}
- QUEUE_BULL_REDIS_HOST=redis
- QUEUE_BULL_REDIS_PORT=6379
- EXECUTIONS_MODE=queue
- N8N_ENCRYPTION_KEY=${N8N_ENCRYPTION_KEY}
depends_on:
- n8n
networks:
- n8n_network
postgres:
image: postgres:16-alpine
container_name: n8n_postgres
restart: unless-stopped
environment:
- POSTGRES_DB=${POSTGRES_DB}
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
interval: 10s
timeout: 5s
retries: 5
networks:
- n8n_network
redis:
image: redis:7-alpine
container_name: n8n_redis
restart: unless-stopped
command: redis-server --requirepass ${REDIS_PASSWORD} --maxmemory 512mb --maxmemory-policy allkeys-lru
healthcheck:
test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD}", "ping"]
interval: 10s
timeout: 5s
retries: 5
volumes:
- redis_data:/data
networks:
- n8n_network
volumes:
n8n_data:
postgres_data:
redis_data:
networks:
n8n_network:
driver: bridgeKey decisions here:
EXECUTIONS_MODE=queue — this is critical. Without queue mode, n8n runs all executions in the main process. Under any real load, this causes memory issues and blocks the UI. Queue mode separates execution into workers (the n8n_worker service), keeping the main instance responsive.
EXECUTIONS_DATA_SAVE_ON_SUCCESS=none — by default n8n saves ALL execution data. For high-volume workflows this bloats your database fast. I only save failures for debugging.
PostgreSQL instead of SQLite — SQLite is fine for development and testing 10 workflows. In production with concurrent executions, SQLite locks become a problem. Switch to Postgres from day one.
127.0.0.1:5678 — note the bind address. Never expose n8n directly on 0.0.0.0:5678 in production. It goes behind nginx only.
3. nginx + SSL + Rate Limiting
server {
listen 443 ssl http2;
server_name automation.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/automation.yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/automation.yourdomain.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384;
ssl_session_cache shared:SSL:10m;
# Rate limiting — adjust based on your usage
limit_req_zone $binary_remote_addr zone=n8n_api:10m rate=30r/m;
limit_req_zone $binary_remote_addr zone=n8n_webhook:10m rate=100r/m;
# n8n UI
location / {
limit_req zone=n8n_api burst=20 nodelay;
proxy_pass http://127.0.0.1:5678;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
}
# Webhook endpoint — higher rate limit
location /webhook/ {
limit_req zone=n8n_webhook burst=50 nodelay;
proxy_pass http://127.0.0.1:5678;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 60s;
}
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' https: data: blob: 'unsafe-inline' 'unsafe-eval'" always;
}
server {
listen 80;
server_name automation.yourdomain.com;
return 301 https://$host$request_uri;
}The separate rate limits for /webhook/ vs the rest are important. Your API integrations hitting webhooks need more headroom than someone browsing the UI. The proxy_read_timeout 300s on the main location handles long-running workflow executions that you trigger manually.
4. PostgreSQL + Redis for Real Throughput
The .env file I use (store this securely — never commit to git):
POSTGRES_DB=n8n_production
POSTGRES_USER=n8n_user
POSTGRES_PASSWORD=<strong-random-password-32-chars>
REDIS_PASSWORD=<another-strong-password>
N8N_HOST=automation.yourdomain.com
N8N_ENCRYPTION_KEY=<random-32-char-hex>
JWT_SECRET=<random-64-char-hex>For the encryption key and JWT secret, generate them properly:
openssl rand -hex 32 # for N8N_ENCRYPTION_KEY
openssl rand -hex 64 # for JWT_SECRETPostgreSQL tuning — the default Postgres config is optimized for minimal memory usage, not throughput. For n8n workloads add to postgres.conf or pass as Docker command args:
shared_buffers = 256MB
effective_cache_size = 1GB
work_mem = 16MB
maintenance_work_mem = 128MB
max_connections = 50With the worker pattern, n8n opens multiple DB connections. max_connections = 50 is more than enough for a single server setup.
5. Automated Backups That Actually Work
Most n8n tutorials skip this. Don't.
I run this cron job daily at 3am:
#!/bin/bash
# /opt/n8n-backup.sh
set -euo pipefail
BACKUP_DIR="/opt/backups/n8n"
DATE=$(date +%Y%m%d_%H%M%S)
RETENTION_DAYS=30
# Load env
source /opt/n8n/.env
mkdir -p "$BACKUP_DIR"
# Dump PostgreSQL
docker exec n8n_postgres pg_dump \
-U "$POSTGRES_USER" \
-d "$POSTGRES_DB" \
--no-owner \
--clean \
| gzip > "$BACKUP_DIR/postgres_${DATE}.sql.gz"
# Backup n8n data directory (credentials, settings)
docker exec n8n tar czf - /home/node/.n8n \
> "$BACKUP_DIR/n8n_data_${DATE}.tar.gz"
# Sync to S3 / Backblaze B2
aws s3 sync "$BACKUP_DIR" "s3://your-bucket/n8n-backups/" \
--storage-class STANDARD_IA \
--delete
# Cleanup old local backups
find "$BACKUP_DIR" -name "*.gz" -mtime +${RETENTION_DAYS} -delete
echo "Backup completed: $DATE"Add to crontab:
0 3 * * * /opt/n8n-backup.sh >> /var/log/n8n-backup.log 2>&1The credentials in n8n are encrypted with your N8N_ENCRYPTION_KEY. Back up that key separately and securely — without it, restoring the n8n_data directory is useless. I keep it in a password manager and a sealed physical envelope. Sounds paranoid until you need it.
6. AI-Powered Lead Enrichment Pipeline
This is the workflow I've built in various forms for 4+ clients. The pattern is: incoming lead → enrich with external data → score with AI → route to appropriate team → personalized outreach.
Here's what it looks like in n8n's HTTP Request + Code nodes:
Trigger: Webhook receives new lead from form/CRM
Step 1 — Enrich with Clearbit/Apollo:
// HTTP Request node → Apollo.io API
// GET https://api.apollo.io/v1/people/match
// Returns: company size, industry, LinkedIn, funding stage, tech stack usedStep 2 — AI scoring with GPT-4 (Code node):
const { default: OpenAI } = await import('openai');
const client = new OpenAI({ apiKey: $env.OPENAI_API_KEY });
const leadData = {
name: $input.item.json.name,
email: $input.item.json.email,
company: $input.item.json.enriched?.company,
industry: $input.item.json.enriched?.industry,
companySize: $input.item.json.enriched?.employees,
fundingStage: $input.item.json.enriched?.funding_stage,
technologies: $input.item.json.enriched?.tech_stack,
message: $input.item.json.message,
};
const response = await client.chat.completions.create({
model: 'gpt-4o',
temperature: 0.3,
messages: [
{
role: 'system',
content: `You are a B2B sales qualification assistant. Score leads from 1-100 based on ICP fit.
ICP: SaaS companies, 10-500 employees, Series A+ funding or profitable, technology-forward, looking for automation/integration services.
Return JSON only: { score: number, tier: "hot"|"warm"|"cold", reasoning: string (max 2 sentences), priority: "urgent"|"normal"|"low" }`
},
{
role: 'user',
content: `Score this lead: ${JSON.stringify(leadData)}`
}
],
response_format: { type: 'json_object' }
});
const qualification = JSON.parse(response.choices[0].message.content);
return {
...leadData,
qualification,
processedAt: new Date().toISOString()
};Step 3 — Route based on score:
score >= 80 → Slack alert to sales channel + add to "Hot Leads" HubSpot list
score 50-79 → Add to CRM nurture sequence
score < 50 → Auto-reply email + tag as coldStep 4 — Personalized email generation:
const lead = $input.item.json;
const emailResponse = await client.chat.completions.create({
model: 'gpt-4o',
temperature: 0.7,
messages: [
{
role: 'system',
content: `Write a personalized first-touch email from Matteo Zurelli (automation consultant).
Tone: direct, technical, no fluff. Reference their specific tech stack and company context.
Max 150 words. End with a specific CTA. No generic opener.`
},
{
role: 'user',
content: `Lead: ${lead.name} at ${lead.company} (${lead.industry}, ${lead.companySize} employees)
Tech stack: ${lead.technologies?.join(', ')}
Their message: "${lead.message}"
Qualification: ${lead.qualification.reasoning}`
}
]
});
return {
to: lead.email,
subject: `re: ${lead.company} × automation`,
body: emailResponse.choices[0].message.content
};This full pipeline runs in under 8 seconds end-to-end. The OpenAI API is the bottleneck — GPT-4o is ~2-3s per call and you're making two calls (scoring + email generation).
For cost: at 500 leads/month, the OpenAI usage is roughly $2-3. Not a rounding error.
7. Custom Nodes in TypeScript
The official n8n marketplace has 400+ integrations. At some point you'll need something it doesn't have. Custom nodes are the answer.
Example: a client needed a node for a Polish ERP system (Enova365) with a non-standard SOAP API. Nothing in the marketplace, obviously.
// custom-nodes/Enova365Node/Enova365.node.ts
import {
IExecuteFunctions,
INodeExecutionData,
INodeType,
INodeTypeDescription,
NodeOperationError,
} from 'n8n-workflow';
export class Enova365 implements INodeType {
description: INodeTypeDescription = {
displayName: 'Enova365 ERP',
name: 'enova365',
icon: 'file:enova365.svg',
group: ['transform'],
version: 1,
description: 'Interact with Enova365 ERP via SOAP/REST API',
defaults: { name: 'Enova365' },
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'enova365Api',
required: true,
}
],
properties: [
{
displayName: 'Operation',
name: 'operation',
type: 'options',
noDataExpression: true,
options: [
{ name: 'Get Invoice', value: 'getInvoice' },
{ name: 'Create Invoice', value: 'createInvoice' },
{ name: 'List Contractors', value: 'listContractors' },
],
default: 'getInvoice',
},
{
displayName: 'Invoice ID',
name: 'invoiceId',
type: 'string',
default: '',
displayOptions: {
show: { operation: ['getInvoice'] }
},
required: true,
}
],
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const operation = this.getNodeParameter('operation', 0) as string;
const credentials = await this.getCredentials('enova365Api');
const results: INodeExecutionData[] = [];
for (let i = 0; i < items.length; i++) {
try {
let responseData;
if (operation === 'getInvoice') {
const invoiceId = this.getNodeParameter('invoiceId', i) as string;
const response = await this.helpers.httpRequest({
method: 'GET',
url: `${credentials.baseUrl}/api/invoices/${invoiceId}`,
headers: {
Authorization: `Bearer ${credentials.apiKey}`,
'Content-Type': 'application/json',
},
});
responseData = response;
}
results.push({ json: responseData });
} catch (error) {
if (this.continueOnFail()) {
results.push({ json: { error: (error as Error).message } });
continue;
}
throw new NodeOperationError(this.getNode(), error as Error, { itemIndex: i });
}
}
return [results];
}
}Build and drop the compiled node into your custom nodes volume path (/var/local/n8n/custom-nodes in our Docker setup). Restart n8n. The node appears in the editor like any built-in node.
The TypeScript types from n8n-workflow package make this straightforward — proper IntelliSense, no guessing at the API.
8. Monitoring & Alerting
The bare minimum setup I run on every client deployment:
Uptime monitoring: UptimeRobot (free tier) pinging the n8n health endpoint every 5 minutes:
GET https://automation.yourdomain.com/healthzn8n returns {"status":"ok"} when healthy. If it doesn't respond within 30s, I get a Telegram message.
Disk usage alert (cron job):
#!/bin/bash
THRESHOLD=85
USAGE=$(df /var/lib/docker | awk 'NR==2 {print $5}' | tr -d '%')
if [ "$USAGE" -gt "$THRESHOLD" ]; then
curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
-d "chat_id=${TELEGRAM_CHAT_ID}" \
-d "text=⚠️ n8n server disk usage: ${USAGE}% — clean up execution logs"
fiFailed execution alert — in n8n itself, I have a meta-workflow: Error Trigger node → Telegram node. Whenever any workflow fails, I get a message with the workflow name and error. Takes 2 minutes to set up and has saved me multiple times.
Database size monitoring — execution data accumulates. I check monthly:
SELECT
schemaname,
tablename,
pg_size_pretty(pg_total_relation_size(schemaname || '.' || tablename)) AS size
FROM pg_tables
WHERE schemaname = 'public'
ORDER BY pg_total_relation_size(schemaname || '.' || tablename) DESC
LIMIT 10;The execution_entity table is usually the biggest. The EXECUTIONS_DATA_PRUNE=true setting handles this automatically, but it's good to verify.
9. Real Cost Breakdown vs Zapier/Make.com
Let me make this concrete with actual client scenarios I've seen:
Scenario A: E-commerce automation (500 orders/day)
| Platform | Monthly tasks | Cost |
|---|---|---|
| Zapier Professional | ~15,000 | $149/mo |
| Make.com Core | ~15,000 | $16/mo |
| n8n self-hosted | unlimited | $40/mo (Hetzner CX31) |
Make.com wins on price here. n8n self-hosted is close but you have overhead. For this scenario, Make.com is actually the right call unless you need custom integrations.
Scenario B: SaaS with AI-powered workflows (50k tasks/month, 5k AI calls)
| Platform | Monthly tasks | AI steps | Cost |
|---|---|---|---|
| Zapier Teams + AI add-on | 50,000 | 5,000 | $449 + |
| Make.com Pro + OpenAI direct | 50,000 | 5,000 | $59 + $15 OpenAI = ~$74/mo |
| n8n self-hosted + OpenAI direct | unlimited | unlimited | $40 VPS + $15 OpenAI = ~$55/mo |
At this scale, both Make.com and n8n beat Zapier by a mile.
Scenario C: High-volume data processing (500k+ tasks/month)
| Platform | Cost |
|---|---|
| Zapier | $799+/mo (custom) |
| Make.com | $299+/mo |
| n8n self-hosted (2x VPS) | $80-120/mo |
Here n8n is the clear winner. The self-hosted cost scales with server infrastructure, not task count.
Bottom line: If you're running under 10,000 tasks/month with no AI steps — just use Make.com. For anything with significant AI integration or volume, n8n self-hosted pays for itself in month one.
10. When n8n Is the Wrong Tool
I'll be honest about where I stop using n8n and write custom code instead.
Complex data transformation at scale — n8n's Code node runs Node.js, which is fine, but if you're doing serious data processing (think: parsing 10MB CSV files, complex aggregations, ML preprocessing) you want a proper service. n8n becomes a trigger/orchestrator, not the execution engine.
Real-time sub-second latency requirements — n8n has overhead. A workflow that makes a webhook call and responds takes 200-500ms minimum. If you're building something that needs <100ms response times, write a serverless function.
Complex branching logic with 20+ conditions — at some point the visual flow becomes harder to reason about than code. When I'm writing the same logic 5 times in different branches, I refactor it into a custom node or external service.
Multi-tenant SaaS where each client needs isolated credentials — n8n's credential system isn't designed for this. You'd end up managing dozens of credential sets manually. Better to build a thin service layer.
The pattern I've settled on: n8n handles orchestration (triggers, routing, API calls, notifications), custom Node.js services handle business logic, PostgreSQL/Redis handle state. n8n is the glue, not the application.
Closing Thoughts
Two years into running n8n in production, I'm still on it. The ecosystem has matured significantly — AI nodes, better queue handling, improved UI, solid TypeScript SDK for custom nodes.
The setup I've described above is overkill for a side project. If you're just trying n8n out, start with the Docker single-container version and SQLite. Migrate to PostgreSQL + queue mode when you need it.
But if you're deploying for a real client or building something that needs to be reliable 24/7, start with the production setup from day one. Migrating from SQLite to PostgreSQL after the fact is painful and the data migration is non-trivial.
Any questions or war stories from your own n8n setups — I'm on Twitter/X and LinkedIn. Happy to trade notes.
Matteo Zurelli is a full-stack developer and automation consultant specializing in n8n, workflow automation pipelines, and custom integration development. Based in Poland, working with clients globally.