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:


🏗️ 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:

Solutions:

  1. Check Logs in Railway Dashboard

    • Look for MongoDB connection errors
    • Check for port binding issues
    • Verify RAILWAY_ENVIRONMENT is set
  2. 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);
    
  3. Check MongoDB Indexes

    • Background services (DatabaseIndexesService, etc.) use OnApplicationBootstrap not OnModuleInit
    • App should start listening before indexes are created

Issue: Authentication Fails

Symptoms:

Solutions:

  1. 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_SECRET
    
  2. Check 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:

Solutions:

  1. Verify Connection String

    • Check for proper URL encoding of special characters
    • Ensure IP whitelist includes 0.0.0.0/0 or Railway IPs
  2. Test Connection Locally

    # Use mongosh to test connection
    mongosh "your-connection-string"
    

Issue: Build Fails on Railway

Symptoms:

Solutions:

  1. Check Dockerfile

    • deployment/Dockerfile.railway.backend-ai should NOT use --frozen-lockfile
    • Current version allows lockfile updates during build
  2. Clear Railway Cache

    • Railway Dashboard → Service → Settings → Clear Build Cache

Issue: Local EADDRINUSE Error

Symptoms:

Solutions:

  1. Kill Process on Port

    # Find process
    lsof -ti:3001
    
    # Kill it
    lsof -ti:3001 | xargs kill -9
    
  2. Verify AI_API_PORT in .env.local

    AI_API_PORT=3001
    

📊 Monitoring

Railway Dashboard Metrics

Monitor in Railway Dashboard:

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:


📁 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:


💰 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


🆘 Support Resources

Documentation

Dashboards


✅ Deployment Complete!

Your backend-ai-api should now be deployed and accessible at:

Next steps:

  1. Test all endpoints from frontend
  2. Verify authentication works with backend-api token
  3. Set up monitoring and alerts
  4. Document any custom configuration
  5. Train team on maintenance procedures

Need Help? Check the Troubleshooting section or review the Railway logs!