Backend AI API - Railway Deployment Guide
Complete guide for deploying backend-ai-api to Railway
Backend AI API - Railway Deployment Guide
📋 Quick Reference
| Key | Value |
|---|---|
| Project ID | 3990549d-4313-47e4-9682-d17b382bdba2 |
| Environment ID | a54fd342-e354-4a69-a8b8-e7d71894a59b |
| Local Port | 3001 |
| API Prefix | /ai-api |
| Health Check | /ai-api/health |
| Dashboard | Railway Dashboard |
| Production URL | https://backend-ai-api-production.up.railway.app |
🎯 Overview
The backend-ai-api is a dedicated Railway service separate from backend-api, providing:
- Platform AI training & agent orchestration
- MCP (Model Context Protocol) services
- Vector memory & embeddings
- AI agent registry & capabilities
- Platform intelligence layer
- Training dataset management
🏗️ Architecture
┌─────────────────────────────────────────────────────────────────────────┐
│ RAILWAY DEPLOYMENT │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────┐ ┌─────────────────────────────┐ │
│ │ backend-api │ │ backend-ai-api │ │
│ │ (Railway Service) │ │ (Railway Service) │ │
│ ├─────────────────────┤ ├─────────────────────────────┤ │
│ │ Port: dynamic │ │ Port: dynamic │ │
│ │ Prefix: /api │ │ Prefix: /ai-api │ │
│ │ Health: /api/health │ │ Health: /ai-api/health │ │
│ │ │ │ │ │
│ │ Services: │ │ Services: │ │
│ │ - Auth │ │ - Platform AI Training │ │
│ │ - Users │ │ - MCP Tools │ │
│ │ - Spaces │ │ - Agent Orchestration │ │
│ │ - Modules │ │ - Vector Memory │ │
│ │ - Analytics │ │ - Intelligence Layer │ │
│ └─────────────────────┘ └─────────────────────────────┘ │
│ │ │ │
│ │ SHARED RESOURCES │ │
│ └─────────────┬───────────────────┘ │
│ │ │
│ ┌──────────────────────▼──────────────────────────────────────┐ │
│ │ MongoDB Atlas Cluster (Shared) │ │
│ │ ├── gograb-api (backend-api) │ │
│ │ ├── ai-agents (backend-ai-api) │ │
│ │ ├── ai-memory (backend-ai-api) │ │
│ │ ├── ai-tenants (backend-ai-api) │ │
│ │ └── ai-context (shared) │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ Shared Environment Variables (CRITICAL!) │ │
│ │ ├── JWT_SECRET (MUST match for auth!) │ │
│ │ ├── SYSTEM_TOKEN │ │
│ │ ├── MONGODB_CONNECTION_STRING │ │
│ │ └── ALLOWED_ORIGINS │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
🚀 Quick Deploy
Option 1: Using Yarn Script (Recommended)
# Deploy backend-ai-api to Railway
yarn railway:deploy:backend-ai
Option 2: Using Deploy Script Directly
# From project root
./deployment/deploy-backend-ai.sh
Option 3: Using Railway CLI
# Login to Railway
railway login
# Switch to backend-ai project
railway link 3990549d-4313-47e4-9682-d17b382bdba2
# Deploy
railway up --service Backend-ai-api --detach
📦 Prerequisites
1. Railway Project Token
Create a project token in Railway Dashboard → Project Settings → Tokens
Add to .env.local:
# Railway Deployment Tokens
RAILWAY_AI_TOKEN=your-backend-ai-api-token-here
2. Environment Variables in Railway
Go to Railway Dashboard → Variables
Set the following:
# Required - Must match backend-api!
JWT_SECRET=<same-as-backend-api>
SYSTEM_TOKEN=<same-as-backend-api>
# MongoDB
MONGODB_CONNECTION_STRING=<your-mongodb-connection-string>
# CORS - Include frontend AND backend-api URLs
ALLOWED_ORIGINS=https://gograb.space,https://admin.gograb.space,https://backend-api-production-97c0.up.railway.app
# Node Environment
NODE_ENV=production
RAILWAY_ENVIRONMENT=true
# Optional - AI Provider Keys
ANTHROPIC_API_KEY=<if-needed>
OPENAI_API_KEY=<if-needed>
⚠️ CRITICAL: JWT_SECRET must exactly match the one in backend-api or authentication will fail!
🔧 Local Development
1. Setup .env.local
Create or update .env.local in project root:
# ============================================
# 🚀 RAILWAY DEPLOYMENT TOKENS
# ============================================
RAILWAY_BACKEND_TOKEN=your-backend-api-token
RAILWAY_AI_TOKEN=your-backend-ai-api-token
# ============================================
# 🔧 LOCAL DEVELOPMENT PORTS
# ============================================
API_PORT=3000
AI_API_PORT=3001
# ============================================
# 🔐 SECRETS (MUST MATCH RAILWAY!)
# ============================================
JWT_SECRET=<YOUR_JWT_SECRET_FROM_ENV_LOCAL>
MONGODB_CONNECTION_STRING=your-mongodb-uri
ANTHROPIC_API_KEY=sk-ant-xxx
OPENAI_API_KEY=sk-xxx
2. Start Both Backends
# Option A: Start both together
yarn serve:backends
# Option B: Start individually
# Terminal 1:
yarn serve:backend-api
# Terminal 2:
yarn serve:backend-ai
3. Verify Both Running
# Backend API (port 3000)
curl http://localhost:3000/api/health
# Backend AI API (port 3001)
curl http://localhost:3001/ai-api/health
🌐 Frontend Configuration
Update your frontend environment files to use both backends:
Production (environment.prod.ts or environment.railway.ts)
export const environment = {
production: true,
backendApiUrl: 'https://backend-api-production-97c0.up.railway.app/api',
aiApiUrl: 'https://backend-ai-api-production.up.railway.app/ai-api',
// ...
};
Local (environment.local.ts)
export const environment = {
production: false,
useMockApi: false,
backendApiUrl: 'http://localhost:3000/api',
aiApiUrl: 'http://localhost:3001/ai-api',
// ...
};
Proxy Configuration (proxy.conf.json)
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
},
"/ai-api": {
"target": "http://localhost:3001",
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
}
✅ Post-Deployment Verification
1. Check Health Endpoint
curl https://backend-ai-api-production.up.railway.app/ai-api/health
Expected response:
{
"status": "operational",
"version": "1.0.0",
"service": "backend-ai-api",
"timestamp": "2025-12-15T12:00:00.000Z"
}
2. Test Platform Agents Endpoint
curl https://backend-ai-api-production.up.railway.app/ai-api/platform/agents
3. Test Platform Stats
curl https://backend-ai-api-production.up.railway.app/ai-api/platform/stats
4. Test Authentication (should match backend-api)
# Get token from backend-api
TOKEN=$(curl -X POST https://backend-api-production-97c0.up.railway.app/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"yourpassword"}' \
| jq -r '.accessToken')
# Test with backend-ai-api (should work!)
curl https://backend-ai-api-production.up.railway.app/ai-api/platform/agents \
-H "Authorization: Bearer $TOKEN"
🐛 Troubleshooting
Issue: Health Check Fails
Symptoms:
- Railway shows "service is offline"
- Health check timeout
Solutions:
Check Logs in Railway Dashboard
- Look for MongoDB connection errors
- Check for port binding issues
- Verify RAILWAY_ENVIRONMENT is set
Verify Port Configuration
// apis/backend-ai-api/src/main.ts should have: const port = process.env.RAILWAY_ENVIRONMENT === 'true' ? process.env.PORT : (process.env.AI_API_PORT || 3001);Check MongoDB Indexes
- Background services (DatabaseIndexesService, etc.) use
OnApplicationBootstrapnotOnModuleInit - App should start listening before indexes are created
- Background services (DatabaseIndexesService, etc.) use
Issue: Authentication Fails
Symptoms:
- "No token provided" error
- "Invalid token" error
- Token from backend-api doesn't work on backend-ai-api
Solutions:
Verify JWT_SECRET Matches
# Check both Railway services have SAME JWT_SECRET # backend-api: Railway Dashboard → Variables → JWT_SECRET # backend-ai-api: Railway Dashboard → Variables → JWT_SECRETCheck CORS Configuration
# Ensure ALLOWED_ORIGINS includes frontend URL curl -I https://backend-ai-api-production.up.railway.app/ai-api/health \ -H "Origin: https://gograb.space" # Should return: # access-control-allow-origin: https://gograb.space
Issue: MongoDB Connection Fails
Symptoms:
- "MongoServerError: bad auth"
- "Failed to connect to MongoDB"
Solutions:
Verify Connection String
- Check for proper URL encoding of special characters
- Ensure IP whitelist includes
0.0.0.0/0or Railway IPs
Test Connection Locally
# Use mongosh to test connection mongosh "your-connection-string"
Issue: Build Fails on Railway
Symptoms:
- "yarn install --frozen-lockfile" fails
- Dependency resolution errors
Solutions:
Check Dockerfile
deployment/Dockerfile.railway.backend-aishould NOT use--frozen-lockfile- Current version allows lockfile updates during build
Clear Railway Cache
- Railway Dashboard → Service → Settings → Clear Build Cache
Issue: Local EADDRINUSE Error
Symptoms:
EADDRINUSE: address already in use 0.0.0.0:3001
Solutions:
Kill Process on Port
# Find process lsof -ti:3001 # Kill it lsof -ti:3001 | xargs kill -9Verify AI_API_PORT in .env.local
AI_API_PORT=3001
📊 Monitoring
Railway Dashboard Metrics
Monitor in Railway Dashboard:
- CPU Usage
- Memory Usage
- Network Traffic
- Request Counts
- Error Rates
- Deployment Status
Logs
# Via Railway CLI
railway logs --service Backend-ai-api
# Via Dashboard
# Railway Dashboard → Service → Logs tab
Health Check Monitoring
Railway automatically monitors /ai-api/health:
- Interval: 30 seconds
- Timeout: 300 seconds (5 minutes)
- Retries: 10
- Auto-restart on failure
📁 Key Files Reference
| File | Purpose |
|---|---|
deployment/Dockerfile.railway.backend-ai |
Production Docker build |
deployment/railway.backend-ai.toml |
Railway deployment config |
deployment/deploy-backend-ai.sh |
Deployment script |
apis/backend-ai-api/.railway-cors.config |
CORS configuration guide |
apis/backend-ai-api/src/main.ts |
Application entry point |
apis/backend-ai-api/project.json |
NX project configuration |
.env.local |
Local development secrets |
🔐 Security Checklist
Before deploying to production:
- New JWT_SECRET generated and matches backend-api
- SYSTEM_TOKEN set and matches backend-api
- MongoDB connection string uses production database
- ALLOWED_ORIGINS configured with production domains
- API keys for AI providers are production keys
- Environment variables reviewed and secured
- Health check endpoint tested
- HTTPS enabled (automatic with Railway)
- Database IP whitelist configured (0.0.0.0/0)
- Monitoring and alerts set up
- CORS tested from frontend origin
💰 Cost Estimate
Railway costs for backend-ai-api:
Hobby Plan ($5-20/month):
- Always-on service
- 500-1000 hours/month
- Automatic scaling
Typical Monthly Cost:
- Small AI API (< 1k requests/day): $5-10/mo
- Medium AI API (1k-10k requests/day): $20-50/mo
- Large AI API (10k+ requests/day): $50-200/mo
🔗 Related Documentation
- Backend API Deployment - General backend deployment
- Multi-Project Railway Guide - Managing multiple Railway projects
- Backend AI API Architecture - System architecture
- MCP System Documentation - MCP implementation details
🆘 Support Resources
Documentation
- Railway: https://docs.railway.app/
- NestJS: https://docs.nestjs.com/
- MongoDB Atlas: https://docs.atlas.mongodb.com/
Dashboards
- Backend AI API: https://railway.com/project/3990549d-4313-47e4-9682-d17b382bdba2
- Backend API: https://railway.com/project/3990549d-4313-47e4-9682-d17b382bdba2
- Frontend: https://railway.com/project/3990549d-4313-47e4-9682-d17b382bdba2
✅ Deployment Complete!
Your backend-ai-api should now be deployed and accessible at:
- Production:
https://backend-ai-api-production.up.railway.app/ai-api - Health Check:
https://backend-ai-api-production.up.railway.app/ai-api/health
Next steps:
- Test all endpoints from frontend
- Verify authentication works with backend-api token
- Set up monitoring and alerts
- Document any custom configuration
- Train team on maintenance procedures
Need Help? Check the Troubleshooting section or review the Railway logs!