# Railway Deployment Guide

Complete guide for deploying the slide-system Motia.dev application to Railway.

**Production URL:** https://slide-system-production-5813.up.railway.app

---

## Table of Contents

1. [Prerequisites](#prerequisites)
2. [Initial Setup](#initial-setup)
3. [Environment Configuration](#environment-configuration)
4. [Deployment Process](#deployment-process)
5. [Verification](#verification)
6. [Updating the Application](#updating-the-application)
7. [Rollback Procedures](#rollback-procedures)
8. [Troubleshooting](#troubleshooting)

---

## Prerequisites

### Required Accounts

- [x] GitHub account with repository access
- [x] Railway account (sign up at https://railway.app)
- [x] Supabase project created
- [x] GitHub Pages repository (optional for full deployment)

### Required Tools

```bash
# Install Railway CLI
npm install -g @railway/cli

# Verify installation
railway --version

# Login to Railway
railway login
```

### Repository Setup

Ensure your repository has the correct structure:

```
your-repo/
├── apps/
│   └── slide-system/
│       ├── steps/
│       │   ├── slidev-generate.step.ts
│       │   ├── slidev-control.step.ts
│       │   └── demo-session-create.step.ts
│       └── package.json
├── package.json
└── pnpm-workspace.yaml
```

---

## Initial Setup

### 1. Create Railway Project

**Via Railway Dashboard:**

1. Go to https://railway.app/dashboard
2. Click "New Project"
3. Select "Deploy from GitHub repo"
4. Choose your repository
5. Railway will auto-detect the project

**Via Railway CLI:**

```bash
# Navigate to your repository
cd /path/to/your/repo

# Initialize Railway project
railway init

# Link to existing project (if already created)
railway link <project-id>
```

### 2. Configure Root Directory

Railway needs to know where the slide-system app is located:

**Via Railway Dashboard:**

1. Go to your project settings
2. Find "Root Directory" setting
3. Set to: `apps/slide-system`
4. Save changes

**Via Railway CLI:**

```bash
railway service --root-directory apps/slide-system
```

### 3. Link to GitHub

Ensure Railway is connected to your GitHub repository for automatic deployments:

1. Go to Settings → Deployments
2. Connect GitHub repository
3. Select branch: `main`
4. Enable automatic deployments on push

---

## Environment Configuration

### Required Environment Variables

Configure these in Railway Dashboard → Variables:

```bash
# Supabase Configuration (Required)
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_SERVICE_KEY=your-service-key-here

# Slidev API Key (Required for control endpoint)
SLIDEV_API_KEY=your-generated-api-key-here

# GitHub Token (Future - for GitHub Pages publishing)
# GITHUB_TOKEN=your-github-token-here
```

### Setting Variables via Dashboard

1. Go to Railway Dashboard
2. Select your project
3. Click "Variables" tab
4. Click "New Variable"
5. Enter name and value
6. Click "Add"
7. Deploy to apply changes

### Setting Variables via CLI

```bash
# Set individual variables
railway variables set SUPABASE_URL=https://your-project.supabase.co
railway variables set SUPABASE_SERVICE_KEY=your-service-key
railway variables set SLIDEV_API_KEY=your-api-key

# View all variables
railway variables

# Delete a variable
railway variables delete VARIABLE_NAME
```

### Generating SLIDEV_API_KEY

Generate a secure random API key:

```bash
# Using OpenSSL
openssl rand -hex 32

# Using Node.js
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

# Example output:
# f0b1323a70bbaa1fcdf34bcabaa8ca2dc14b880225c41c8d337d9a60ceeee2de
```

### Getting Supabase Credentials

1. Go to https://supabase.com/dashboard
2. Select your project
3. Go to Settings → API
4. Copy:
   - URL: `SUPABASE_URL`
   - Service Role Key: `SUPABASE_SERVICE_KEY`

⚠️ **Security:** Never commit these values to git!

---

## Deployment Process

### Automatic Deployment (Recommended)

When Railway is connected to GitHub, deployments happen automatically:

1. Push changes to `main` branch
2. Railway detects the push
3. Railway builds and deploys automatically
4. Check deployment status in Railway Dashboard

```bash
# Push to GitHub
git add .
git commit -m "Deploy: your changes"
git push origin main

# Railway will automatically deploy
```

### Manual Deployment via CLI

```bash
# Deploy current branch
railway up

# Deploy specific service
railway up --service slide-system

# Watch deployment logs
railway logs --follow
```

### First-Time Deployment Checklist

Before deploying for the first time:

- [x] Root directory set to `apps/slide-system`
- [x] Environment variables configured
- [x] Supabase database tables created
- [x] GitHub repository connected
- [x] Branch set to `main`

---

## Verification

### 1. Check Deployment Status

**Via Dashboard:**

1. Go to Railway Dashboard
2. View "Deployments" tab
3. Latest deployment should show "Success"

**Via CLI:**

```bash
# Check deployment status
railway status

# View recent deployments
railway deployments
```

### 2. Test Health Endpoint

```bash
# Test that service is responding
curl https://slide-system-production-5813.up.railway.app/

# Should return service info or homepage
```

### 3. Test API Endpoints

**Test Session Creation:**

```bash
curl -X POST https://slide-system-production-5813.up.railway.app/demo-sessions \
  -H "Content-Type: application/json" \
  -d '{"session_type":"test","environment":"prod"}' \
  | jq

# Expected: {session_id, status, created_at}
```

**Test Deck Generation:**

```bash
# First, create a session and get session_id
SESSION_ID=$(curl -s -X POST https://slide-system-production-5813.up.railway.app/demo-sessions \
  -H "Content-Type: application/json" \
  -d '{"session_type":"test","environment":"prod"}' \
  | jq -r '.session_id')

# Then generate a deck
curl -X POST https://slide-system-production-5813.up.railway.app/api/slidev/generate \
  -H "Content-Type: application/json" \
  -d "{
    \"sessionId\":\"$SESSION_ID\",
    \"templateId\":\"starter\",
    \"data\":{\"company\":\"Test Corp\"}
  }" \
  | jq

# Expected: {deckId, deckUrl, message}
```

**Test Control Endpoint:**

```bash
curl -X POST https://slide-system-production-5813.up.railway.app/api/slidev/control \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_SLIDEV_API_KEY" \
  -d '{"deckId":"test-deck-id","command":"next"}' \
  | jq

# Expected: {success: true, command: "next", message: "..."}
# Note: Will return 404 if deck doesn't exist
```

### 4. Check Logs

```bash
# View recent logs
railway logs

# Follow logs in real-time
railway logs --follow

# Filter logs
railway logs | grep ERROR
railway logs | grep SlidevGenerate
```

### 5. Monitor Metrics

**Via Railway Dashboard:**

1. Go to "Metrics" tab
2. View:
   - CPU usage
   - Memory usage
   - Network traffic
   - Response times

---

## Updating the Application

### Standard Update Process

```bash
# 1. Make changes locally
# 2. Test locally (if possible)
# 3. Commit changes
git add .
git commit -m "feat: your feature description"

# 4. Push to GitHub (triggers automatic deployment)
git push origin main

# 5. Monitor deployment
railway logs --follow

# 6. Verify deployment
curl https://slide-system-production-5813.up.railway.app/
```

### Update Environment Variables

```bash
# Update a variable
railway variables set SLIDEV_API_KEY=new-key-here

# Trigger redeploy
railway up

# Verify new variable is active
railway logs | grep SLIDEV_API_KEY
```

### Update Dependencies

```bash
# Update package.json dependencies
npm update

# Or manually edit package.json

# Commit and push
git add package.json pnpm-lock.yaml
git commit -m "chore: update dependencies"
git push origin main

# Railway will rebuild with new dependencies
```

---

## Rollback Procedures

### Rollback to Previous Deployment

**Via Dashboard:**

1. Go to "Deployments" tab
2. Find previous successful deployment
3. Click "..." menu
4. Select "Redeploy"
5. Confirm rollback

**Via CLI:**

```bash
# List recent deployments
railway deployments

# Rollback to specific deployment
railway rollback <deployment-id>

# Or use shorthand for previous deployment
railway rollback --previous
```

### Emergency Rollback

If the application is completely broken:

```bash
# Stop the service
railway service stop

# Rollback to last known good deployment
railway rollback --previous

# Restart the service
railway service start

# Verify
curl https://slide-system-production-5813.up.railway.app/
```

### Rollback Environment Variables

```bash
# If a variable change caused issues
railway variables set VARIABLE_NAME=previous-value

# Redeploy
railway up
```

---

## Troubleshooting

### Deployment Fails

**Symptom:** Railway shows "Failed" deployment status

**Check:**

```bash
# View deployment logs
railway logs

# Common issues:
# - Build errors (check package.json, TypeScript errors)
# - Missing dependencies
# - Environment variable issues
```

**Solution:**

1. Fix the issue locally
2. Commit and push
3. Monitor new deployment

### Service Not Responding

**Symptom:** `curl` returns connection error or timeout

**Check:**

```bash
# Check service status
railway status

# View logs for errors
railway logs | grep ERROR

# Check if service is running
railway ps
```

**Solution:**

```bash
# Restart service
railway service restart

# Or redeploy
railway up
```

### Environment Variables Not Working

**Symptom:** API returns configuration errors

**Check:**

```bash
# List all variables
railway variables

# Check logs for missing variables
railway logs | grep "not configured"
```

**Solution:**

```bash
# Set missing variables
railway variables set VARIABLE_NAME=value

# Redeploy
railway up
```

### Database Connection Issues

**Symptom:** "Failed to verify session" or database errors

**Check:**

1. Verify Supabase is accessible:
   ```bash
   curl https://your-project.supabase.co/rest/v1/
   ```

2. Check SUPABASE_SERVICE_KEY is correct:
   ```bash
   railway variables | grep SUPABASE
   ```

3. Verify Supabase tables exist:
   - Go to Supabase Dashboard → Table Editor
   - Confirm `conversation_sessions`, `slidev_decks`, `slide_control_commands` exist

**Solution:**

1. Update Supabase credentials if changed
2. Run database migrations if needed
3. Check Supabase project status

### High Memory Usage

**Symptom:** Service restarts frequently or OOM errors

**Check:**

```bash
# View metrics
railway metrics

# Check logs for memory issues
railway logs | grep "memory"
```

**Solution:**

1. Upgrade Railway plan for more memory
2. Optimize code (remove memory leaks)
3. Implement caching to reduce processing

### Slow Performance

**Symptom:** API responses take > 5 seconds

**Check:**

```bash
# Test response time
time curl https://slide-system-production-5813.up.railway.app/demo-sessions

# Check logs for slow operations
railway logs | grep "duration"
```

**Solution:**

1. Optimize database queries
2. Add caching layer
3. Upgrade Railway plan
4. Check Supabase performance

---

## Best Practices

### Development Workflow

1. **Develop Locally:** Test changes before deploying
2. **Use Feature Branches:** Create branch for each feature
3. **Review Before Merge:** Review code before merging to `main`
4. **Monitor Deployments:** Watch logs after each deployment
5. **Rollback if Needed:** Don't hesitate to rollback if issues occur

### Security

1. **Never Commit Secrets:** Use environment variables
2. **Rotate API Keys:** Change SLIDEV_API_KEY periodically
3. **Monitor Logs:** Watch for suspicious activity
4. **Use HTTPS:** Always use HTTPS endpoints (Railway enforces this)

### Monitoring

1. **Set Up Alerts:** Configure Railway alerts for errors
2. **Check Logs Daily:** Review logs for errors or warnings
3. **Monitor Metrics:** Watch CPU, memory, network usage
4. **Test After Deployment:** Run smoke tests after each deployment

---

## Additional Resources

- **Railway Documentation:** https://docs.railway.app
- **Railway CLI Reference:** https://docs.railway.app/develop/cli
- **Motia.dev Documentation:** https://docs.motia.dev
- **API Documentation:** `docs/api/slidev-api.md`
- **Architecture Documentation:** `docs/architecture/slidev-system.md`

---

## Support

**Railway Status:** https://status.railway.app

**Production URL:** https://slide-system-production-5813.up.railway.app

**Internal Documentation:**
- Setup Guide: `.claude/docs/phase0-setup-guide.md`
- Debugging Guide: `.claude/docs/phase0-debugging-guide.md`

---

**Last Updated:** 2025-10-09
