Skip to main content

STEMblock Platform - Cost-Optimized Deployment Guide

For Development/Internal Trial Use

Target: Minimal cost deployment for internal testing and trials Platform: Digital Ocean App Platform (maximized usage) Monthly Budget: Under $20/month


Table of Contents

  1. Cost-Optimized Architecture
  2. Prerequisites
  3. Database Setup (Dev Tier)
  4. Backend Deployment
  5. Frontend Deployment
  6. Environment Configuration
  7. Cost Breakdown
  8. Scaling Path

Cost-Optimized Architecture

┌─────────────────┐
│ Test Users │
└────────┬────────┘

│ HTTPS (Free SSL)

┌────────▼──────────────────────────────┐
│ Digital Ocean App Platform │
│ (Includes Load Balancer + SSL) │
└──────┬──────────────────────┬─────────┘
│ │
│ │
┌──────▼──────────┐ ┌────────▼──────────┐
│ Frontend │ │ Backend API │
│ Static Site │ │ Basic Tier │
│ $5/month │ │ $5/month │
└─────────────────┘ └─────────┬─────────┘


┌─────────▼──────────┐
│ Managed PostgreSQL │
│ Dev Database │
│ $7/month (with promo)│
└────────────────────┘

Total Monthly Cost: ~$17/month


Prerequisites

Required Accounts

  • Digital Ocean account
  • GitHub account (for code deployment)
  • Mistral AI API key (Free tier available)

Cost-Saving Tips

  1. Use Digital Ocean Promo: New accounts get $200 credit for 60 days
  2. Mistral AI Free Tier:
    • Use "open-mistral-7b" model
    • Free tier: 1M tokens/month
    • Sufficient for 100-200 evaluations/month

Database Setup

Cost: $7/month (with promo) or FREE for first 60 days

  1. Create Database Cluster

    • Navigate to: Databases → Create Database Cluster
    • Select: PostgreSQL 15
    • Choose plan: Dev Database
      • 1 GB RAM
      • 10 GB Disk
      • 1 vCPU
      • $7/month (but FREE with $200 credit)
    • Choose datacenter region: New York 3 (cheapest)
    • Name: stemblock-db-dev
  2. Security Settings

    • Enable "Trusted Sources"
    • Add App Platform as trusted source
    • Enable connection pooling (free, improves performance)
  3. Connection Details

    Host: stemblock-db-dev-do-user-XXXXX-0.b.db.ondigitalocean.com
    Port: 25060
    User: doadmin
    Password: [provided by DO]
    Database: defaultdb
    SSL: required
  4. Create Application Database

    # Connect via psql
    psql "postgresql://doadmin:PASSWORD@HOST:25060/defaultdb?sslmode=require"

    # Create database
    CREATE DATABASE stemblock_dev;
    \q
  5. Connection String

    postgresql://doadmin:PASSWORD@HOST:25060/stemblock_dev?sslmode=require&schema=public

Option 2: Free PostgreSQL (Alternative)

If you want $0 cost during trial:

  1. Use ElephantSQL Free Tier

  2. Use Supabase Free Tier

For serious testing, we recommend Option 1 (Digital Ocean managed DB with promo credit)


Backend Deployment

1. Prepare Repository

Ensure your code is on GitHub:

cd ~/stemblock
git add .
git commit -m "Prepare for deployment"
git push origin main

2. Create App Platform App - Backend

  1. Navigate to App Platform

    • Go to: App Platform → Create App
    • Source: GitHub
    • Repository: stemblock
    • Branch: main
  2. Configure Backend Component

    Name: stemblock-backend
    Type: Web Service
    Source Directory: /backend

    Build Command: npm ci && npm run build
    Run Command: npm run start:prod

    HTTP Port: 8080
    HTTP Routes: /

    Instance Size: Basic (512MB RAM, 1 vCPU) - $5/month
    Instance Count: 1

    Health Check:
    HTTP Path: /health
    Port: 8080
    Initial Delay: 30s
    Period: 60s
  3. Add Environment Variables

    # Database
    DATABASE_URL=postgresql://doadmin:PASSWORD@HOST:25060/stemblock_dev?sslmode=require&schema=public

    # JWT (Generate random 32+ char string)
    JWT_SECRET=your-secure-random-string-min-32-characters
    JWT_EXPIRATION=7d

    # App
    PORT=8080
    NODE_ENV=development
    FRONTEND_URL=https://your-app-name.ondigitalocean.app

    # File Upload
    UPLOAD_DIR=/tmp/uploads
    MAX_FILE_SIZE=10485760

    # AI Evaluation (Free tier)
    LLM_PROVIDER=mistral
    MISTRAL_API_KEY=your-mistral-api-key
    MISTRAL_MODEL=open-mistral-7b
    MISTRAL_MIN_REQUEST_INTERVAL=2000
    MISTRAL_MAX_RETRIES=5
    LLM_FALLBACK_TO_MOCK=true

    # Google OAuth (Optional - leave empty if not using)
    GOOGLE_CLIENT_ID=
    GOOGLE_CLIENT_SECRET=
    GOOGLE_CALLBACK_URL=https://your-api-url/auth/google/callback
  4. Database Migrations Setup

    You have TWO options for running database migrations:

    Option A: Using Job Component (Recommended)

    1. In your app, click CreateCreate Resources From Source Code
    2. Select your repository and branch
    3. In the resource configuration screen, click Edit in the Info section
    4. Change resource type to Job (not "Web Service")
    5. Configure the Job:
      Name: db-migration
      Type: Job
      Source Directory: /backend
      Build Command: npm ci
      Run Command: npx prisma migrate deploy
      Instance Size: Basic (512MB RAM)
    6. In the When to Run dropdown, select Pre-deploy
    7. This ensures migrations run before each deployment

    Option B: Run Migrations in Start Command (Simpler Alternative)

    If you can't find the Job component option, modify your backend Run Command to:

    Run Command: npm run start:migrate

    This runs npx prisma migrate deploy && npm run start:prod automatically.

    Note: npx prisma migrate deploy is idempotent (safe to run multiple times).

  5. Create Resources

    • Click "Create Resources"
    • Wait 5-10 minutes for deployment
    • Note the backend URL: https://stemblock-backend-xxxxx.ondigitalocean.app

Frontend Deployment

1. Update Frontend Configuration

File: /frontend/.env.production

NEXT_PUBLIC_API_URL=https://your-backend-url.ondigitalocean.app

Update next.config.js:

/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
output: 'standalone',
env: {
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
},
}

module.exports = nextConfig

2. Add Frontend Component

  1. In App Platform

    • Go to your app
    • Click "Create Component"
    • Type: Static Site (cheaper than Web Service)
  2. Configure Frontend Component

    Name: stemblock-frontend
    Type: Static Site
    Source Directory: /frontend

    Build Command: npm ci && npm run build
    Output Directory: .next

    HTTP Routes: /

    Instance Size: Basic (Static Site) - $5/month
  3. Add Environment Variable

    NEXT_PUBLIC_API_URL=https://your-backend-url.ondigitalocean.app
  4. Deploy

    • Click "Save"
    • Wait 5-10 minutes
    • Note the frontend URL: https://your-app-name.ondigitalocean.app

Environment Configuration

Update Backend CORS

After deployment, update FRONTEND_URL in backend environment variables to match your actual frontend URL.

Also update CORS in backend code if needed:

File: /backend/src/main.ts

app.enableCors({
origin: [
process.env.FRONTEND_URL,
'https://your-app-name.ondigitalocean.app',
],
credentials: true,
});

Cost Breakdown

Monthly Costs (Development/Trial)

ServiceTierSpecsCost
DatabaseDev Database1GB RAM, 10GB disk, 1 vCPU$7/month
BackendBasic Web Service512MB RAM, 1 vCPU$5/month
FrontendStatic SiteBasic tier$5/month
BandwidthIncluded1TB/month$0
SSL CertificatesIncludedAuto-renewed$0
Load BalancerIncludedWith App Platform$0
BackupsNot enabled(Can enable for +$1/month)$0
Mistral AIFree tier1M tokens/month$0
Total$17/month

With Promo Credit ($200 for 60 days)

  • Effective Cost: $0/month for first ~11 months
  • After Promo: $17/month ongoing

Cost Comparison

DeploymentMonthly CostUse Case
Development (This guide)$17/monthInternal testing, <50 users
Staging$35/monthUser testing, <100 users
Production$89/monthLive product, 500+ users

Optimization Strategies

1. Minimize Database Costs

  • Use Dev Database tier ($7/month vs $15+ for Basic)
  • Only 1 node (no replicas during dev)
  • No point-in-time recovery (enable in production)
  • Manual backups when needed

2. Minimize Compute Costs

  • Backend: Basic tier 512MB RAM ($5/month vs $12+ for Professional)
  • Frontend: Static Site ($5/month vs $12+ for Web Service)
  • Single instance each (no auto-scaling)

3. Leverage Free Services

  • SSL certificates: Included with App Platform
  • Load balancer: Included with App Platform
  • Bandwidth: 1TB included (enough for 10,000+ pageviews)
  • Logs: 7 days retention included
  • Metrics: Basic monitoring included

4. AI Costs

  • Use Mistral "open-mistral-7b" (free tier)
  • Enable response caching (already implemented)
  • Fallback to mock provider for testing

5. Storage Costs

  • File uploads to /tmp (ephemeral, free)
  • For permanent storage, add Spaces later ($5/month for 250GB)

Limitations of Dev Tier

Acceptable for Internal Trial:

  • ✅ Up to 50 concurrent users
  • ✅ Up to 10GB database storage
  • ✅ Up to 1TB bandwidth/month
  • ✅ Basic monitoring and logs
  • ✅ SSL and custom domains

Not Suitable For:

  • ❌ Production workloads
  • ❌ 100+ concurrent users
  • ❌ High-availability requirements
  • ❌ Advanced backups and recovery
  • ❌ Dedicated resources

Scaling Path

When to Upgrade

From Dev to Staging ($17 → $35/month)

  • Database: Dev → Basic ($7 → $15)
  • Backend: 512MB → 1GB RAM ($5 → $12)
  • User Load: 10-50 → 50-100 concurrent users

From Staging to Production ($35 → $89/month)

  • Database: Basic → Professional ($15 → $60)
  • Backend: 1GB → 2GB RAM ($12 → $24)
  • Add Redis cache: $7/month
  • Add Spaces storage: $5/month
  • Enable backups: +$7/month
  • User Load: 100 → 500+ concurrent users

Monitoring & Alerts

Free Monitoring Included

Built-in Metrics:

  • CPU usage
  • Memory usage
  • Bandwidth usage
  • Request count
  • Response times
  • Error rates

Set Up Free Alerts:

  1. Go to App Platform → Monitoring
  2. Create alerts for:
    • CPU > 80% for 5 minutes
    • Memory > 90% for 5 minutes
    • Error rate > 5% for 5 minutes

External Monitoring (Free):

  • UptimeRobot: Free tier monitors 50 URLs
  • Healthchecks.io: Free tier for basic checks

Deployment Checklist

Initial Setup

  • Create Digital Ocean account
  • Apply promo code ($200 credit)
  • Push code to GitHub
  • Create Dev Database
  • Note database connection string

Backend Deployment

  • Create App Platform app
  • Configure backend component (Basic $5/month)
  • Add all environment variables
  • Setup database migrations (Job component OR start:migrate command)
  • Deploy and test /health endpoint

Frontend Deployment

  • Update frontend API URL
  • Add frontend component (Static $5/month)
  • Configure build settings
  • Deploy and test homepage

Post-Deployment

  • Update CORS in backend
  • Test login flow
  • Create test accounts
  • Test AI evaluation (within free tier)
  • Set up monitoring alerts
  • Document URLs and credentials

Cost-Saving Tips

During Development (Months 1-2)

  1. Use Promo Credit - Covers everything for free
  2. Mock AI Provider - Use LLM_PROVIDER=mock for testing
  3. Pause Database - Not available for managed DB, but minimal cost
  4. Single Region - Choose closest region only

During Trial (Months 3-6)

  1. Monitor Usage - Check App Platform metrics weekly
  2. Optimize Database - Delete old test data
  3. Cache Aggressively - Already implemented for AI
  4. Limit File Uploads - Keep max file size at 10MB

Before Production (Month 6+)

  1. Plan Upgrade - Review user growth projections
  2. Budget for Scale - $89/month for production tier
  3. Enable Backups - Critical for production
  4. Add CDN - Included with App Platform, no extra cost

Frequently Asked Questions

Q: Can I use a free database?

A: Yes! ElephantSQL (20MB free) or Supabase (500MB free) work for initial testing. However, Digital Ocean Dev Database is recommended because:

  • Better performance
  • Managed backups available
  • Easier scaling path
  • Free with promo credit for 11 months

Q: What happens after the $200 credit runs out?

A: You'll start paying $17/month. You can:

  • Continue at this tier for internal use
  • Upgrade to staging/production tiers
  • Move to free database options to reduce cost
  • Pause the app if not actively testing

Q: How many users can this handle?

A: Comfortably supports:

  • 10-20 concurrent users
  • 100-200 total registered users
  • 500-1000 API requests/hour
  • Sufficient for internal trials and demos

Q: Can I add more features without increasing cost?

A: Yes! The cost is based on compute and database size, not features. All current features work within the $17/month budget.

Q: How do I monitor costs?

A:

  • Check "Billing" in Digital Ocean dashboard
  • View "Usage" tab in App Platform
  • Set up spending alerts in Billing settings
  • Track AI usage in Mistral dashboard

Support & Resources


Quick Start Commands

# 1. Prepare code
cd ~/stemblock
git add .
git commit -m "Deploy to Digital Ocean"
git push origin main

# 2. Create database (via DO dashboard)
# Note connection string

# 3. Deploy via App Platform dashboard
# Connect GitHub → Configure → Deploy

# 4. Test deployment
curl https://your-backend-url.ondigitalocean.app/health
# Should return: {"status":"ok","database":"connected"}

# 5. Test frontend
open https://your-frontend-url.ondigitalocean.app

Summary

Total Setup Time: ~30-45 minutes Monthly Cost: $17/month ($0 with promo for 11 months) Suitable For: Internal testing, demos, trials with <50 users Upgrade Path: Clear path to production when ready

This deployment strategy maximizes use of App Platform's included features (SSL, load balancing, CI/CD) while minimizing costs through:

  • Dev-tier database
  • Basic-tier compute
  • Static site frontend
  • Free AI tier
  • Included bandwidth and SSL

Perfect for internal trials and early-stage testing! 🚀


Last Updated: November 2025 Version: 2.0 - Cost-Optimized Target Audience: Internal trial deployment