I Self-Host n8n with AI Agents on Railway for Under $10/mo — Here's My Exact Setup
A step-by-step guide to deploying n8n on Railway with PostgreSQL, setting up AI agent workflows, and keeping the whole thing under $10/month.
I've been running n8n in production for about eight months now. It handles everything from lead qualification to content scheduling to monitoring my side projects. The managed n8n Cloud plan would cost me around $50/month for the volume I run — instead, I pay roughly $7-9 on Railway.
Here's the full setup, including the AI agent workflows I've built on top of it.
Why Self-Host n8n at All
The managed n8n Cloud works fine if you're running a handful of workflows. But the moment you start building AI agent pipelines — the kind that chain multiple LLM calls, hit APIs, and process data in loops — you burn through execution limits fast.
Self-hosted n8n gives you unlimited executions. No throttling, no per-execution billing, no awkward "you've exceeded your plan" emails. You pay for compute and storage, and that's it.
I tried a few hosting options before settling on Railway:
- VPS (Hetzner): Cheapest option (~€4/mo), but I got tired of managing Docker, SSL certs, and backups manually. I'm not running a DevOps team here.
- DigitalOcean App Platform: Solid, but the $12/mo minimum for the container plus a managed database pushed costs north of $20.
- Railway: One-click deploy template, managed PostgreSQL included, usage-based billing. I was up and running in under five minutes.
The Railway Deploy — Step by Step
1. Create a Railway Account
Head to railway.com and sign up with GitHub. You get a $5 free trial credit, which is enough to run n8n for about a month while you decide if you like the setup.
2. Deploy the n8n Template
Railway has an official n8n template that bundles n8n with PostgreSQL. Click the deploy button from railway.com/deploy/n8n and Railway provisions both services automatically.
You'll want to set a few environment variables right away:
N8N_BASIC_AUTH_ACTIVE=true
N8N_BASIC_AUTH_USER=your_username
N8N_BASIC_AUTH_PASSWORD=a_strong_password_here
WEBHOOK_URL=https://your-app.up.railway.app
N8N_ENCRYPTION_KEY=generate_a_random_32_char_string
GENERIC_TIMEZONE=Europe/Warsaw
The N8N_ENCRYPTION_KEY is critical — it encrypts your stored credentials. Generate one with openssl rand -hex 16 and save it somewhere safe. If you lose this key, all your saved credentials become unreadable.
3. Configure PostgreSQL
The template sets up Postgres automatically, but I recommend bumping the connection pool settings for AI workflows that make lots of parallel calls:
DB_POSTGRESDB_DATABASE=${{Postgres.PGDATABASE}}
DB_POSTGRESDB_HOST=${{Postgres.PGHOST}}
DB_POSTGRESDB_PORT=${{Postgres.PGPORT}}
DB_POSTGRESDB_USER=${{Postgres.PGUSER}}
DB_POSTGRESDB_PASSWORD=${{Postgres.PGPASSWORD}}
DB_POSTGRESDB_SSL_REJECT_UNAUTHORIZED=false
DB_POSTGRESDB_POOL_SIZE=20
Railway's template handles most of this through variable references, but explicitly setting DB_POSTGRESDB_POOL_SIZE=20 (default is 10) prevents connection exhaustion when you have multiple AI agent workflows running concurrently.
4. Set Up a Custom Domain (Optional but Recommended)
Railway gives you a .up.railway.app subdomain for free, but I route mine through a custom domain for cleaner webhook URLs. In Railway's settings, add your domain and point a CNAME record to the Railway-provided target. SSL is automatic.
My webhook URLs look like https://auto.bytecore.dev/webhook/xxx instead of a random Railway subdomain — much easier to manage.
Building the AI Agent Workflow
Here's where it gets interesting. n8n's AI Agent node, combined with the tool-use pattern, lets you build workflows that actually reason about what to do next.
My Lead Qualification Agent
This is the workflow I'm most proud of. It triggers on a webhook (from a Webflow contact form), runs the lead through an AI agent, and routes them to different follow-up sequences.
The flow looks like this:
Webhook Trigger
→ AI Agent (OpenAI GPT-4o)
→ Tool: Google Search (company research)
→ Tool: HTTP Request (check LinkedIn profile)
→ Tool: Code Node (score the lead)
→ Switch Node (based on score)
→ High Score → Add to CRM + Send personalized email
→ Medium Score → Add to nurture sequence
→ Low Score → Log and skip
The AI Agent node configuration:
{
"agent": "openAiFunctionsAgent",
"model": "gpt-4o",
"systemMessage": "You are a lead qualification assistant. Given a contact form submission, research the person and their company, then score them 1-10 based on: company size, relevance to our services (web dev & AI automation), and apparent budget. Return a JSON with: score, reasoning, company_summary, and suggested_action.",
"maxIterations": 5,
"temperature": 0.3
}
I keep the temperature low (0.3) because I want consistent, predictable scoring — not creative writing. The maxIterations: 5 cap prevents runaway tool-calling loops that could burn through API credits.
The Tool Nodes
Each tool the agent can call is a separate n8n sub-workflow connected to the Agent node:
Company Research Tool:
{
"name": "research_company",
"description": "Search the web for information about a company",
"parameters": {
"company_name": {
"type": "string",
"description": "The name of the company to research"
}
}
}
This calls the SerpAPI node to search Google, then passes results back to the agent for analysis.
Lead Scoring Code Node:
// Score calculation based on agent's research
const data = $input.first().json;
let score = 5; // base score
// Company size signals
if (data.employee_count > 50) score += 2;
if (data.employee_count > 200) score += 1;
// Tech stack alignment
const techKeywords = ['react', 'next', 'node', 'ai', 'automation', 'saas'];
const matchCount = techKeywords.filter(kw =>
data.company_summary.toLowerCase().includes(kw)
).length;
score += Math.min(matchCount, 2);
// Budget signals
if (data.has_funding || data.revenue_signals) score += 1;
return [{ json: { ...data, score: Math.min(score, 10) } }];
Cost Breakdown for AI Workflows
This is what people always want to know — what does it actually cost to run?
| Component | Monthly Cost | |---|---| | Railway n8n instance | ~$5-7 | | Railway PostgreSQL | ~$1-3 | | OpenAI API (GPT-4o) | ~$8-15 | | SerpAPI (100 searches) | Free tier | | Total | ~$14-25 |
The Railway portion stays under $10. The OpenAI cost depends on volume — I process about 30-50 leads per month, and each qualification run uses roughly 2,000-4,000 tokens including tool calls.
Compare that to a managed solution: n8n Cloud Pro at $50/mo + the same API costs. The self-hosted route saves me at least $40/month.
Three More AI Workflows Worth Building
Once you have n8n + AI running, you start seeing automation opportunities everywhere. Here are three more I've deployed:
1. Content Idea Generator (Runs Weekly)
A cron-triggered workflow that:
- Pulls trending topics from Hacker News API
- Checks Google Trends for search volume
- Uses Claude (via Anthropic API) to generate 5 blog post ideas with estimated search potential
- Posts the list to a Slack channel
I've been using Claude Sonnet for this because it's better at understanding what developers actually search for versus what sounds impressive but nobody Googles.
2. Error Monitor + Summarizer
Connected to my DigitalOcean droplet logs:
- Webhook receives error alerts from my monitoring setup
- AI agent categorizes the error (critical/warning/noise)
- For critical errors: creates a GitHub issue with suggested fix
- For warnings: batches them into a daily summary email
- For noise: silently logs and moves on
This replaced a janky bash script + cron job setup that I was embarrassed to maintain.
3. Invoice Processor
For freelance work:
- Watches a specific email label for incoming invoices
- Extracts data using GPT-4o's vision capabilities (forwards the email attachment)
- Creates entries in a Supabase table
- Sends a Slack notification with the parsed details
Before this, I was manually entering invoice data into a spreadsheet like it was 2015.
Production Tips I Learned the Hard Way
Back up your encryption key and database. Railway makes database backups easy (it's in the dashboard), but I also run a weekly pg_dump to an S3 bucket. I learned this after a test deployment lost all my credential configs.
Set execution timeout limits. Add EXECUTIONS_TIMEOUT=300 (5 minutes) to prevent runaway workflows from eating your Railway credits. AI agent loops can get stuck if an API is slow to respond.
Use the queue mode for heavy workflows. If you're running more than a few AI agent workflows simultaneously, enable queue mode:
EXECUTIONS_MODE=queue
QUEUE_BULL_REDIS_HOST=${{Redis.REDISHOST}}
QUEUE_BULL_REDIS_PORT=${{Redis.REDISPORT}}
QUEUE_BULL_REDIS_PASSWORD=${{Redis.REDISPASSWORD}}
This requires adding a Redis service to your Railway project (another ~$1-2/mo), but it prevents workflow execution from blocking the main n8n process.
Pin your n8n version. Railway's template uses latest by default. Change the Docker image to a specific version like n8nio/n8n:1.76.1 to avoid surprise breaking changes. I update manually every 2-3 weeks after checking the changelog.
Monitor your Railway usage. Railway's billing is usage-based, which is great until an infinite loop runs for 6 hours. Set up billing alerts in the Railway dashboard. I have mine set to notify at $15 — anything above that means something is wrong.
The Bottom Line
Self-hosting n8n on Railway is the best balance I've found between cost, convenience, and capability. You get the flexibility of self-hosted (unlimited executions, full API access, custom domains) without the headache of managing servers.
The whole setup takes about 15 minutes if you follow the steps above. And once you add AI agent workflows, the ROI is hard to beat — especially if you're a freelancer or indie hacker automating parts of your business that used to eat hours of manual work.
My monthly spend: ~$8 for hosting, plus whatever the LLM APIs cost. That's it. No seat licenses, no execution caps, no enterprise sales calls.
If you're still copy-pasting data between apps manually, this is your sign to stop.
Some links in this article are affiliate links. If you sign up through them, I may earn a small commission at no extra cost to you. I only recommend tools I actually use and pay for myself.