# Railway Deployment Steps for Screenshare Bot

**Purpose**: Step-by-step instructions for deploying the screenshare bot to Railway platform.

**Audience**: Operations team, deployment engineers, on-call personnel

**Prerequisites**: Complete PRE-DEPLOYMENT-CHECKLIST.md before proceeding

---

## Table of Contents

1. [Overview](#overview)
2. [Environment Variable Setup](#environment-variable-setup)
3. [Deployment Process](#deployment-process)
4. [Monitoring the Build](#monitoring-the-build)
5. [Verifying Deployment](#verifying-deployment)
6. [Common Build Errors](#common-build-errors)
7. [Troubleshooting](#troubleshooting)

---

## Overview

### Deployment Architecture

```
┌─────────────────────────────────────────────────┐
│           Railway Platform (PaaS)               │
│                                                 │
│  ┌───────────────────────────────────────────┐ │
│  │  Build Process                            │ │
│  │  1. Git push triggers build               │ │
│  │  2. Railway clones repository             │ │
│  │  3. Detects Dockerfile                    │ │
│  │  4. Builds Docker image                   │ │
│  │  5. Runs RUN commands                     │ │
│  │  6. Installs dependencies                 │ │
│  │  7. Installs Playwright + Chromium        │ │
│  │  8. Creates container                     │ │
│  │  9. Starts service (CMD)                  │ │
│  └───────────────────────────────────────────┘ │
│                                                 │
│  ┌───────────────────────────────────────────┐ │
│  │  Running Service                          │ │
│  │  • Node.js API (port 3000)                │ │
│  │  • Bot Manager (spawns Python bots)       │ │
│  │  • Python bots (Playwright + Daily.co)    │ │
│  └───────────────────────────────────────────┘ │
└─────────────────────────────────────────────────┘
                      │
                      ↓
              ┌───────────────┐
              │  Daily.co     │
              │  Video Rooms  │
              └───────────────┘
```

### Deployment Methods

Railway supports three deployment methods:

1. **Auto-Deploy** (Recommended for production)
   - Automatically deploys on git push to main branch
   - Consistent, reproducible deployments
   - Best for CI/CD workflows

2. **Manual Deploy via CLI**
   - Explicit control over deployment timing
   - Useful for testing or off-hours deployments
   - Requires Railway CLI

3. **Manual Deploy via Dashboard**
   - Web-based deployment trigger
   - Good for non-technical deployers
   - Visual deployment monitoring

**This guide covers Method #1 (Auto-Deploy) as primary, with CLI fallback.**

---

## Environment Variable Setup

### Step 1: Access Railway Dashboard

1. Open browser and navigate to: https://railway.app
2. Log in with your Railway account
3. Select project: `slide-system` (or your project name)
4. Click on the `slide-system` service

### Step 2: Navigate to Variables Tab

1. In the service dashboard, click on **"Variables"** tab
2. You'll see a list of existing environment variables
3. Click **"New Variable"** to add each required variable

### Step 3: Set Required Environment Variables

Add each of the following variables one at a time:

#### PIPECAT_API_KEY

```
Variable Name: PIPECAT_API_KEY
Value: [Your Pipecat API key - starts with pk_live_... or similar]
```

**Where to get**:
- Log in to Pipecat Dashboard (https://dashboard.pipecat.ai or provider URL)
- Navigate to API Keys section
- Copy your API key
- Paste into Railway variable value field

**Click "Add" to save**

---

#### DAILY_PIPECAT_API_KEY

```
Variable Name: DAILY_PIPECAT_API_KEY
Value: [Your Daily.co API key for Pipecat integration]
```

**Where to get**:
- Log in to Daily.co Dashboard: https://dashboard.daily.co
- Go to Developers > API Keys
- Copy the API key (starts with `d_api_key_...`)
- Paste into Railway variable value field

**Click "Add" to save**

---

#### DAILY_API_KEY

```
Variable Name: DAILY_API_KEY
Value: [Your Daily.co API key for room management]
```

**Where to get**:
- Same location as DAILY_PIPECAT_API_KEY
- May be the same key or a separate one depending on your setup
- Copy from Daily.co Dashboard > Developers > API Keys
- Paste into Railway variable value field

**Click "Add" to save**

---

#### SUPABASE_URL

```
Variable Name: SUPABASE_URL
Value: https://[your-project-id].supabase.co
```

**Where to get**:
- Log in to Supabase: https://app.supabase.com
- Select your project
- Go to Settings > API
- Copy "Project URL"
- Paste into Railway variable value field

**Click "Add" to save**

---

#### SUPABASE_SERVICE_KEY

```
Variable Name: SUPABASE_SERVICE_KEY
Value: [Your Supabase service role key - starts with eyJ...]
```

**Where to get**:
- Same location: Supabase Settings > API
- Scroll to "Project API keys" section
- Copy the **`service_role`** key (NOT the `anon` key)
- This key bypasses Row Level Security - keep it secret!
- Paste into Railway variable value field

**Click "Add" to save**

---

### Step 4: Set Optional Environment Variables

These have defaults but can be customized:

#### BOT_TIMEOUT_MINUTES (Optional)

```
Variable Name: BOT_TIMEOUT_MINUTES
Value: 30
Default: 30 minutes
```

Maximum duration for a bot session before auto-termination.

**Click "Add" to save** (if customizing)

---

#### MAX_CONCURRENT_BOTS (Optional but Recommended)

```
Variable Name: MAX_CONCURRENT_BOTS
Value: 1   # Start with 1, increase gradually
Default: 5
```

**IMPORTANT for Gradual Rollout**:
- Phase 1: Set to `1`
- Phase 2: Set to `3`
- Phase 3: Set to `5`

Start with 1 bot for initial deployment!

**Click "Add" to save**

---

#### FRAME_RATE (Optional)

```
Variable Name: FRAME_RATE
Value: 10
Default: 10 FPS
```

Frames per second for video streaming.

**Click "Add" to save** (if customizing)

---

#### LOG_LEVEL (Optional)

```
Variable Name: LOG_LEVEL
Value: INFO
Default: INFO
Options: DEBUG, INFO, WARNING, ERROR
```

For production, use `INFO` or `WARNING`.
For debugging, use `DEBUG`.

**Click "Add" to save** (if customizing)

---

#### DEBUG_MODE (Optional)

```
Variable Name: DEBUG_MODE
Value: false
Default: false
```

Enable debug mode for verbose logging.

**Click "Add" to save** (if customizing)

---

### Step 5: Verify Variables Are Set

1. Stay on the Variables tab
2. Scroll through the list of variables
3. Confirm you see all 5 required variables:
   - ✅ PIPECAT_API_KEY
   - ✅ DAILY_PIPECAT_API_KEY
   - ✅ DAILY_API_KEY
   - ✅ SUPABASE_URL
   - ✅ SUPABASE_SERVICE_KEY

4. Verify optional variables if set:
   - ✅ MAX_CONCURRENT_BOTS (should be `1` for first deployment)
   - ✅ LOG_LEVEL (recommended: `INFO`)

**CLI Verification** (alternative):
```bash
railway vars --service slide-system | grep -E "PIPECAT|DAILY|SUPABASE|MAX_CONCURRENT"
```

---

## Deployment Process

### Method 1: Auto-Deploy (Recommended)

This is the simplest and most reliable method.

#### Step 1: Ensure Auto-Deploy is Enabled

1. In Railway dashboard, go to service `slide-system`
2. Click on **"Settings"** tab
3. Scroll to **"Deploy"** section
4. Ensure **"Auto Deploy"** is enabled
5. Verify **Branch** is set to `main` (or your deployment branch)

#### Step 2: Push Code to Main Branch

```bash
# Ensure you're on the main branch
git checkout main

# Ensure you have latest changes
git pull origin main

# Verify no uncommitted changes
git status
# Expected: nothing to commit, working tree clean

# Push to main (triggers auto-deploy)
git push origin main
```

**What happens next**:
- Railway detects the push
- Triggers a new deployment automatically
- Build process starts (see "Monitoring the Build" section)

---

### Method 2: Manual Deploy via CLI

If auto-deploy is disabled or you want manual control:

#### Step 1: Ensure Railway CLI is Set Up

```bash
# Check Railway CLI is installed
railway --version

# Should show: railway version x.x.x

# If not installed:
npm install -g @railway/cli
```

#### Step 2: Link to Project

```bash
# Navigate to project directory
cd /Users/lars/mycode/buzztrail/epic-pipecat-based-screenshare-bot/apps/slide-system

# Link to Railway project
railway link

# Select your project and service when prompted
# Project: slide-system
# Service: slide-system (or your service name)
```

#### Step 3: Deploy

```bash
# Deploy current directory to Railway
railway up --service slide-system

# Output:
# ✓ Building...
# ✓ Deploying...
# ✓ Deployment successful
```

---

### Method 3: Manual Deploy via Dashboard

If you prefer web-based deployment:

#### Step 1: Navigate to Deployments

1. Open Railway dashboard
2. Select `slide-system` service
3. Click on **"Deployments"** tab

#### Step 2: Trigger Deploy

1. Click **"Deploy Now"** button (top-right)
2. Confirm the deployment
3. Build process starts automatically

---

## Monitoring the Build

### Step 1: Access Build Logs

**Via Dashboard**:
1. Railway dashboard > `slide-system` service
2. Click on **"Deployments"** tab
3. Click on the latest deployment (top of list)
4. Build logs appear in real-time

**Via CLI**:
```bash
railway logs --service slide-system --tail
```

### Step 2: Watch Build Progress

You'll see output similar to this:

```
[Build] Starting build...
[Build] Cloning repository...
[Build] ✓ Repository cloned
[Build] Detecting build configuration...
[Build] ✓ Dockerfile detected at /Dockerfile
[Build] Building Docker image...

[Build] Step 1/10 : FROM motiadev/motia:latest
[Build] ✓ Base image pulled

[Build] Step 2/10 : COPY . .
[Build] ✓ Files copied

[Build] Step 3/10 : RUN npm install -g motia@latest
[Build] ✓ Motia CLI installed

[Build] Step 4/10 : RUN echo '{"compilerOptions": ...
[Build] ✓ tsconfig created

[Build] Step 5/10 : RUN npx motia@latest install
[Build] ✓ Motia dependencies installed

[Build] Step 6/10 : RUN pip install --no-cache-dir uv && cd bots/tavus-tool-forwarder && ...
[Build] ✓ Tavus bot dependencies installed

[Build] Step 7/10 : RUN cd bots/screenshare-bot && python3 -m venv .venv && uv pip install ...
[Build] Installing pipecat-ai>=0.0.50...
[Build] Installing daily-python>=0.19.9...
[Build] Installing playwright>=1.40.0...
[Build] Installing Pillow>=10.0.0...
[Build] Installing supabase>=2.0.0...
[Build] ✓ Screenshare bot dependencies installed

[Build] Step 8/10 : RUN cd bots/screenshare-bot && .venv/bin/playwright install --with-deps chromium
[Build] Downloading Chromium browser...
[Build] Installing browser dependencies (libnss3, libglib2.0-0, etc.)...
[Build] ✓ Playwright Chromium installed

[Build] Step 9/10 : EXPOSE 3000
[Build] ✓ Port exposed

[Build] Step 10/10 : CMD sh -c "npx motia dev --port ${PORT:-3000} --host 0.0.0.0"
[Build] ✓ Start command configured

[Build] ✓ Build successful (4m 32s)
[Build] Image ID: sha256:abc123...

[Deploy] Starting deployment...
[Deploy] Pulling image...
[Deploy] Creating container...
[Deploy] Starting container...
[Deploy] Container started on port 3000
[Deploy] Health check passed ✓
[Deploy] ✓ Deployment successful

[Status] Service is now RUNNING
[Status] Public URL: https://slide-system-production-5813.up.railway.app
```

### Step 3: Build Duration

**Expected Build Time**: 4-6 minutes

**Breakdown**:
- Base image pull: 30-60 seconds
- File copy: 10 seconds
- Motia install: 30 seconds
- Tavus bot deps: 30 seconds
- Screenshare bot deps: 60 seconds
- **Playwright + Chromium**: 90-120 seconds (largest component)
- Container creation: 30 seconds

**If build takes > 10 minutes**: Something may be wrong, check logs for errors.

---

## Verifying Deployment

### Step 1: Check Service Status

**Via Dashboard**:
1. Railway dashboard > `slide-system` service
2. Top of page should show: **Status: RUNNING** (green indicator)

**Via CLI**:
```bash
railway status --service slide-system

# Expected output:
# Service: slide-system
# Status: RUNNING
# Health: Healthy
# Uptime: 2m 15s
# CPU: 5%
# Memory: 280 MB
# Public URL: https://slide-system-production-5813.up.railway.app
```

### Step 2: Check Recent Logs

```bash
railway logs --service slide-system --tail -n 50

# Look for:
# ✓ "Service listening on port 3000"
# ✓ "Motia started successfully"
# ✓ "BotManager initialized"
# ✗ No ERROR logs
```

### Step 3: Test API Endpoint

**Get your Railway URL**:
```bash
railway status --service slide-system | grep "Public URL"
# Copy the URL
```

**Test bot status endpoint**:
```bash
export API_URL="https://slide-system-production-5813.up.railway.app"

curl -s "$API_URL/api/tavus/bot/status" | jq

# Expected response:
# {
#   "activeCount": 0,
#   "bots": []
# }
```

If you get a JSON response, deployment is successful! ✅

---

## Common Build Errors

### Error 1: ModuleNotFoundError: No module named 'pipecat'

**Cause**: Screenshare bot dependencies not installed in Dockerfile

**Log Pattern**:
```
[Deploy] Starting bot...
[Deploy] Traceback (most recent call last):
[Deploy]   File "bot.py", line 3, in <module>
[Deploy]     from pipecat.transports.daily.transport import DailyTransport
[Deploy] ModuleNotFoundError: No module named 'pipecat'
```

**Solution**:
1. Verify Dockerfile includes screenshare bot installation:
   ```dockerfile
   RUN cd bots/screenshare-bot && \
       python3 -m venv .venv && \
       uv pip install --python .venv/bin/python .
   ```
2. Re-deploy after fixing Dockerfile
3. See DOCKERFILE-VALIDATION.md for details

---

### Error 2: Browser executable not found

**Cause**: Playwright Chromium not installed

**Log Pattern**:
```
[Deploy] playwright._impl._api_types.Error:
[Deploy] Executable doesn't exist at /root/.cache/ms-playwright/chromium-1091/chrome-linux/chrome
```

**Solution**:
1. Verify Dockerfile includes Playwright installation:
   ```dockerfile
   RUN cd bots/screenshare-bot && \
       .venv/bin/playwright install --with-deps chromium
   ```
2. Re-deploy after fixing Dockerfile
3. Ensure `--with-deps` flag is present (installs system libraries)

---

### Error 3: Build timeout

**Cause**: Build taking > 10 minutes

**Log Pattern**:
```
[Build] ERROR: Build timed out after 10m 0s
```

**Solution**:
1. Check Railway status page: https://railway.app/status
2. Retry deployment: `railway up --service slide-system`
3. If persistent, contact Railway support
4. Consider optimizing Dockerfile (cache layers, parallel installs)

---

### Error 4: ENOENT: no such file or directory, open '.venv/bin/python'

**Cause**: Virtual environment not created

**Log Pattern**:
```
[Deploy] Error: ENOENT: no such file or directory, open 'bots/screenshare-bot/.venv/bin/python'
[Deploy] BotManager failed to spawn bot
```

**Solution**:
1. Verify Dockerfile creates venv:
   ```dockerfile
   RUN cd bots/screenshare-bot && python3 -m venv .venv && ...
   ```
2. Check Python is installed in base image
3. Re-deploy after fixing

---

### Error 5: Environment variable not set

**Cause**: Missing required environment variable

**Log Pattern**:
```
[Deploy] Error: DAILY_API_KEY is required but not set
[Deploy] Bot failed to initialize
```

**Solution**:
1. Go to Railway dashboard > Variables tab
2. Add the missing variable (see "Environment Variable Setup" section)
3. Redeploy automatically triggers after adding variable
4. Verify all 5 required variables are set

---

### Error 6: Port binding error

**Cause**: Service not binding to PORT environment variable

**Log Pattern**:
```
[Deploy] Error: listen EADDRINUSE: address already in use :::3000
[Deploy] Service failed to start
```

**Solution**:
1. Verify CMD in Dockerfile uses `${PORT:-3000}`:
   ```dockerfile
   CMD sh -c "npx motia dev --port ${PORT:-3000} --host 0.0.0.0"
   ```
2. Railway automatically sets PORT - service must use it
3. Re-deploy after fixing

---

## Troubleshooting

### Build Fails After Dockerfile Change

**Steps**:
1. Review build logs for specific error
2. Test Dockerfile locally:
   ```bash
   cd /Users/lars/mycode/buzztrail/epic-pipecat-based-screenshare-bot/apps/slide-system
   docker build -t screenshare-bot-test .
   ```
3. Fix errors in Dockerfile
4. Commit and push changes
5. Railway will auto-rebuild

---

### Deployment Succeeds But Bot Won't Spawn

**Steps**:
1. Check if all environment variables are set:
   ```bash
   railway vars --service slide-system
   ```
2. Check Railway logs for spawn errors:
   ```bash
   railway logs --service slide-system | grep "spawn\|ERROR"
   ```
3. Test environment validation:
   ```bash
   python scripts/validate_railway_config.py
   ```
4. Review RUNBOOK.md for spawn troubleshooting

---

### Service Crashes Immediately After Deploy

**Steps**:
1. Check for OOM (Out of Memory) kills:
   ```bash
   railway logs --service slide-system | grep "OOM\|137"
   ```
2. Check for application errors:
   ```bash
   railway logs --service slide-system | grep "ERROR\|Exception"
   ```
3. Increase Railway memory limit if OOM:
   - Dashboard > Settings > Memory Limit > 2GB (or higher)
4. Review RUNBOOK.md for crash troubleshooting

---

### Cannot Access Public URL
**Steps**:
1. Verify service is RUNNING:
   ```bash
   railway status --service slide-system
   ```
2. Check if public domain is enabled:
   - Dashboard > Settings > Domains
   - Should have a `*.up.railway.app` domain
3. Test with curl:
   ```bash
   curl -v https://slide-system-production-5813.up.railway.app/api/tavus/bot/status
   ```
4. Check for firewall/network issues locally

---

### Rollback Needed

If deployment has critical issues:

**Immediate Rollback**:
```bash
# List recent deployments
railway deployments --service slide-system | head -5

# Rollback to previous deployment
railway rollback --service slide-system dep-PREVIOUS_ID

# Monitor rollback
railway logs --service slide-system --tail
```

See DEPLOYMENT.md for full rollback procedures.

---

## Deployment Checklist Summary

Use this quick checklist during deployment:

```
□ Pre-deployment checklist complete (PRE-DEPLOYMENT-CHECKLIST.md)
□ All environment variables set in Railway
□ MAX_CONCURRENT_BOTS set to 1 (for initial deployment)
□ Code pushed to main branch
□ Build started successfully
□ Build logs show no errors
□ All Dockerfile RUN steps complete
□ Playwright + Chromium installed successfully
□ Build completes in 4-6 minutes
□ Deployment status: RUNNING
□ Service health check: Healthy
□ API endpoint responds: /api/tavus/bot/status
□ No errors in recent logs
□ Ready for smoke testing (see PRODUCTION-VALIDATION.md)
```

---

## Next Steps

After successful deployment:

1. **Verify deployment** using PRODUCTION-VALIDATION.md
2. **Monitor service** for 30 minutes
3. **Run smoke tests** to validate functionality
4. **Begin gradual rollout** per GRADUAL-ROLLOUT-PLAN.md
5. **Update deployment log** in DEPLOYMENT-SIGN-OFF.md

---

## Quick Reference Commands

```bash
# Set environment variables
railway vars --service slide-system set KEY=value

# Deploy to Railway
git push origin main  # Auto-deploy
# OR
railway up --service slide-system  # Manual deploy

# Monitor deployment
railway logs --service slide-system --tail

# Check status
railway status --service slide-system
# Test API
curl https://slide-system-production-5813.up.railway.app/api/tavus/bot/status

# Rollback
railway rollback --service slide-system dep-PREVIOUS_ID
```

---

**Document Version**: 1.0
**Last Updated**: 2025-10-12
**Owner**: Stream C - Production Validation & Rollout
**Related Documents**: PRE-DEPLOYMENT-CHECKLIST.md, RAILWAY-CONFIG.md, DOCKERFILE-VALIDATION.md, PRODUCTION-VALIDATION.md
