Skip to content

Backend Deployment Guide

Comprehensive guide for deploying the Archety backend orchestrator to production.

Last Updated: November 4, 2025 Status: Production Ready


Quick Start

Prerequisites

  • GitHub account with repository
  • Render.com account (free tier works)
  • Environment variables ready (API keys)

Fastest Path to Production

  1. Push to GitHub

    git push origin master
    

  2. Deploy on Render (choose one method below)

  3. Blueprint deploy (recommended)
  4. Manual web service creation

  5. Configure environment variables

  6. Verify deployment


Deployment Methods

Fastest and most automated approach

  1. Push to GitHub

    git init
    git add .
    git commit -m "Initial commit"
    git branch -M main
    git remote add origin <your-repo-url>
    git push -u origin main
    

  2. Create Blueprint on Render

  3. Visit: https://render.com
  4. Sign up / Log in with GitHub
  5. Click "New +" → "Blueprint"
  6. Connect your GitHub repository
  7. Render detects render.yaml automatically
  8. Click "Apply"

  9. Set Environment Variables After blueprint creation, add to your web service:

    MEM0_API_KEY=<your-mem0-key>
    OPENAI_API_KEY=<your-openai-key>
    GOOGLE_CLIENT_ID=<your-google-client-id>
    GOOGLE_CLIENT_SECRET=<your-google-client-secret>
    FERNET_KEY=<your-fernet-key>
    TELEGRAM_BOT_TOKEN=<your-telegram-bot-token>
    TELEGRAM_API_ID=<your-telegram-api-id>
    TELEGRAM_API_HASH=<your-telegram-api-hash>
    SENTRY_DSN=<your-sentry-dsn>
    ENVIRONMENT=production
    LOG_LEVEL=INFO
    

  10. Wait for Deploy

  11. Build + deploy takes 5-10 minutes
  12. Your URL: https://archety-backend-prod.up.railway.app

Method 2: Manual Web Service Creation

For more control over configuration

Step 1: Create PostgreSQL Database

  1. Dashboard → "New +" → "PostgreSQL"
  2. Configuration:
  3. Name: archety-postgres
  4. Database: archety
  5. Region: Oregon (or closest to users)
  6. Plan: Free (256 MB storage)
  7. Click "Create Database"
  8. Copy Internal Database URL (format: `

Step 2: Create Web Service

  1. Dashboard → "New +" → "Web Service"
  2. Connect your GitHub repository
  3. Configuration:
  4. Name: archety-backend
  5. Region: Oregon (same as database)
  6. Branch: main
  7. Root Directory: (leave blank)
  8. Runtime: Python 3
  9. Build Command: pip install -r requirements.txt
  10. Start Command: uvicorn app.main:app --host 0.0.0.0 --port $PORT
  11. Plan: Free (or Starter for always-on)

Step 3: Environment Variables

Add all environment variables from Method 1, plus:

DATABASE_URL=<paste-internal-database-url-from-step-1>
PYTHON_VERSION=3.11.0

Step 4: Deploy

Click "Create Web Service" and monitor build logs.


Post-Deployment Setup

1. Verify Deployment

# Health check
curl https://archety-backend-prod.up.railway.app/

# Expected: {"status":"healthy","version":"3.5.0"}

2. Test API Endpoints

# Test message endpoint
curl -X POST https://archety-backend-prod.up.railway.app/orchestrator/message \
  -H "Content-Type: application/json" \
  -d '{
    "chat_guid": "test",
    "mode": "direct",
    "sender": "+15551234567",
    "text": "Hello Sage!",
    "timestamp": 1699123456,
    "participants": ["+15551234567"]
  }'

3. Sync Persona Memories (First Time)

Choose one method:

Option A: Via Render Shell 1. Render Dashboard → Your Service → "Shell" tab 2. Run: python scripts/sync_persona_memories.py

Option B: Via SSH

render ssh archety-backend
python scripts/sync_persona_memories.py
exit

Option C: Auto-sync on Startup (Recommended)

Update start command in render.yaml or Render Dashboard:

python scripts/sync_persona_memories.py && uvicorn app.main:app --host 0.0.0.0 --port $PORT

4. Access Admin Panel

Navigate to: https://archety-backend-prod.up.railway.app/admin

Features: - View and manage persona memories - Browse conversation history - Monitor system stats - Sync memories from JSON


Environment Variables Reference

Required Variables

Variable Description Example
MEM0_API_KEY mem0 cloud API key m0-xxxxx...
OPENAI_API_KEY OpenAI API key for LLM sk-proj-xxxxx...
DATABASE_URL PostgreSQL connection string `

OAuth & Integrations

Variable Description Required For
GOOGLE_CLIENT_ID Google OAuth client ID Calendar/Gmail
GOOGLE_CLIENT_SECRET Google OAuth secret Calendar/Gmail
FERNET_KEY Token encryption key OAuth tokens

Telegram Integration

Variable Description Required For
TELEGRAM_BOT_TOKEN Bot token from @BotFather Telegram interface
TELEGRAM_API_ID API ID from my.telegram.org Telegram client
TELEGRAM_API_HASH API hash from my.telegram.org Telegram client

Monitoring & Debugging

Variable Description Default
SENTRY_DSN Sentry error tracking DSN (optional)
ENVIRONMENT Deployment environment production
LOG_LEVEL Logging verbosity INFO

Generating Secrets

Fernet Key:

from cryptography.fernet import Fernet
print(Fernet.generate_key().decode())


Render Free Tier Limitations

What's Included (Free)

  • ✅ 750 hours/month compute
  • ✅ 256 MB RAM (sufficient for MVP)
  • ✅ PostgreSQL: 256 MB storage
  • ✅ Automatic HTTPS
  • ✅ Auto-deploy from GitHub

Limitations

  • ⚠️ Spins down after 15 minutes inactivity
  • ⚠️ Cold start: 30-60 seconds
  • ⚠️ No always-on guarantee

Workarounds

Keep-Alive Service (Prevents Spin-Down): 1. Sign up for UptimeRobot (free) 2. Create HTTP monitor 3. URL: https://archety-backend-prod.up.railway.app/ 4. Interval: 14 minutes 5. Render stays warm!

Upgrade Path: - Starter Plan: $7/month - Always-on, faster - Standard Plan: $25/month - More resources


Database Migrations

Initial Setup

Database tables are created automatically on first run via SQLAlchemy.

Running Migrations

If using Alembic:

# Via Render shell
render ssh archety-backend
alembic upgrade head
exit

Backup Database

# Get database credentials from Render dashboard
pg_dump $DATABASE_URL > backup_$(date +%Y%m%d).sql

Monitoring & Debugging

View Logs

Real-time logs: - Render Dashboard → Your Service → "Logs" tab

Recent errors: - If Sentry is configured, check Sentry dashboard

Metrics

Render Dashboard → Your Service → "Metrics" - CPU usage - Memory usage - Request count - Response time

Common Issues

502 Bad Gateway - Cause: App starting but timing out - Fix: Check logs for startup errors, increase timeout

Memory Exceeded - Cause: Too many concurrent requests on free tier - Fix: Upgrade to Starter plan or optimize memory usage

Database Connection Errors - Cause: DATABASE_URL incorrect or DB offline - Fix: Verify DATABASE_URL, check PostgreSQL service status


Security Considerations

Admin Panel Authentication

Current State: Open access (development)

Recommended: Add HTTP Basic Auth

  1. Set ADMIN_PASSWORD environment variable in Render
  2. Code already implements basic auth (see app/api/admin_routes.py)
  3. Access with: https://admin:YOUR_PASSWORD@archety-backend.onrender.com/admin

API Authentication

Current State: Open endpoints (development)

Production TODO: - Add API key authentication for /orchestrator/message - Implement request signing from edge agent - Rate limiting per user/endpoint

Token Storage

OAuth tokens are encrypted with Fernet before storage in database.

Ensure: - FERNET_KEY is set and never committed to git - Rotate FERNET_KEY periodically (requires token re-auth)


Performance Optimization

Caching Strategy

Currently Implemented: - Persona passport caching (in-memory) - OAuth token caching (database)

Future Enhancements: - Redis for LLM response caching - mem0 search result caching (short TTL) - Session-level context caching

Database Connection Pooling

Current: SQLAlchemy default pooling

Production Recommendation:

# In app/models/database.py
engine = create_engine(
    DATABASE_URL,
    pool_size=10,
    max_overflow=20,
    pool_pre_ping=True
)


Continuous Deployment

Auto-Deploy from GitHub

  1. Render Dashboard → Your Service → Settings
  2. Enable "Auto-Deploy" for main branch
  3. Every push to main triggers deploy automatically

Deploy Webhooks

Receive notifications:

# Add webhook URL in Render settings
# POST request on deploy start/complete


Scaling Considerations

Horizontal Scaling

  • Upgrade to Standard+ plan for multiple instances
  • Add Redis for shared session state
  • Configure load balancer

Database Scaling

  • Monitor PostgreSQL storage (256 MB free tier)
  • Upgrade to larger PostgreSQL plan as needed
  • Consider PostgreSQL read replicas for heavy read workloads

Rollback Procedure

Via Render Dashboard

  1. Go to Deploys tab
  2. Find previous successful deploy
  3. Click "Redeploy" on that version

Via Git

# Revert to previous commit
git revert HEAD
git push origin main

# Render will auto-deploy reverted version

Health Checks

Render automatically checks: GET /

Custom Health Endpoint:

GET https://archety-backend-prod.up.railway.app/health

Returns:

{
  "status": "healthy",
  "database": "connected",
  "mem0": "connected",
  "version": "3.5.0",
  "uptime": 3600
}


Cost Estimation

Free Tier (Current)

  • Cost: $0/month
  • Suitable for: Development, testing, low-traffic MVP
  • Limitations: Spin-down, cold starts

Backend: - Starter Plan: $7/month (always-on) - Database: $7/month (1 GB storage)

External Services: - mem0: Free tier (100K vectors) - OpenAI: Pay-per-token (~$10-50/month depending on usage) - Sentry: Free tier (5K events/month)

Total Estimated: $15-30/month for production MVP


Backup & Disaster Recovery

Database Backups

Render Automatic Backups (Paid plans): - Daily snapshots - 7-day retention

Manual Backup:

# Backup to local file
pg_dump $DATABASE_URL > backup.sql

# Restore from backup
psql $DATABASE_URL < backup.sql

Configuration Backup

Keep render.yaml and environment variables documented in: - This file (sanitized) - Password manager - Team documentation


Next Steps After Deployment

  1. ✅ Verify health endpoint
  2. ✅ Test message flow end-to-end
  3. ✅ Access admin panel
  4. ✅ Sync persona memories
  5. ✅ Set up UptimeRobot keep-alive
  6. ✅ Configure Sentry error tracking
  7. ✅ Set up monitoring alerts
  8. 🚀 Connect edge agent (Mac mini)
  9. 🚀 Test with real users!

  • Backend Setup: SETUP.md
  • Database Migrations: DATABASE_MIGRATION.md (removed)
  • Edge Agent Integration: See docs/edge/ for current edge agent docs

Support & Troubleshooting

Common Resources: - Render Docs: https://render.com/docs - FastAPI Docs: https://fastapi.tiangolo.com - mem0 Docs: https://docs.mem0.ai

Need Help? - Check Render logs first - Review this deployment guide - Consult team documentation