Overview
JOIP Web Application uses PostgreSQL as its primary database, with Neon as the recommended serverless PostgreSQL provider for production deployments. This guide covers database provisioning, schema setup, connection configuration, and optimization.Why Neon?
Neon is the recommended PostgreSQL provider for JOIP because:- Serverless Architecture: Automatic scaling and sleep when idle
- Instant Provisioning: Create databases in seconds
- Branching: Database branches for development/staging
- Connection Pooling: Built-in PgBouncer for connection management
- Replit Integration: Seamless deployment with Replit
- Generous Free Tier: 3 GiB storage, 100 hours compute per month
- PostgreSQL 16: Latest features and performance improvements
Database Provisioning
Create Neon Project
Sign Up for Neon
- Visit neon.tech
- Click “Sign Up” and authenticate with GitHub/Google/email
- Verify your email address
Create New Project
- Click “Create Project” in the Neon dashboard
- Configure your project:
- Project Name:
joip-production(or your preferred name) - Region: Choose closest to your Replit region (e.g., US East)
- PostgreSQL Version: 16 (latest)
- Compute Size: Start with 0.25 vCPU (free tier)
- Project Name:
- Click “Create Project”
Retrieve Connection String
After creation, Neon displays your connection string:
Copy this string immediately - you’ll need it for the
DATABASE_URL environment variable.Alternative Providers
While Neon is recommended, JOIP supports any PostgreSQL provider:- Supabase Database: Free tier with 500 MB, includes real-time features
- Railway: PostgreSQL with automatic backups
- Render: Free PostgreSQL with 90-day retention
- Self-Hosted: Your own PostgreSQL server (ensure SSL/TLS)
Database Schema Setup
JOIP uses Drizzle ORM for type-safe database operations with schema defined inshared/schema.ts.
Apply Schema Migrations
Verify Database Connection
Ensure Should output your connection string (may be redacted in Replit).
DATABASE_URL is set in environment variables:Run Migration Command
Apply all schema changes to your database:This command:
- Reads schema from
shared/schema.ts - Compares with current database state
- Creates/modifies tables, indexes, and constraints
- Outputs migration summary
Database Schema Overview
JOIP’s schema includes 36 constraints across multiple tables:Core Tables
users (shared/schema.ts)
- User profiles and authentication data
- Fields:
id(varchar),email,name,avatar,createdAt - Primary key:
id - Unique constraint:
email
- Slideshow sessions with configuration
- Fields:
id(serial),userId,title,subreddits,intervalMin/Max,transition,aiPrompt,captionTheme - Foreign key:
userId→users.id(on delete cascade) - 13 user reference constraints prevent orphaned records
- Media items associated with sessions
- Fields:
id,sessionId,mediaUrl,caption,type,order - Foreign key:
sessionId→content_sessions.id(on delete cascade) - Indexed on:
sessionId,order
- Personal media vault uploads
- Fields:
id,userId,storagePath,filename,filesize,contentType - Foreign key:
userId→users.id(on delete cascade) - Supports Supabase Storage integration
Analytics Tables
user_usage_stats- Comprehensive usage metrics per user
- Tracks sessions created, media uploaded, API calls, etc.
- Updated in real-time via
server/usageTracking.ts
- Detailed activity logging for analytics
- Fields:
id,userId,action,metadata,timestamp - Indexed on:
userId,timestamp
Community & Sharing
shared_sessions- Public session sharing with unique codes
- Fields:
id,sessionId,shareCode(UUID),createdAt - Unique constraint:
shareCode
- Snapshots of public sessions for Community feed
- Preserves original content even if source is deleted
- Community copies of shared media items
- Stored in Supabase
generalbucket for durability
System Tables
app_settings- Dynamic application configuration
- Administrative access management
- Personalized subreddit collections
Connection String Format
PostgreSQL connection strings follow this format:Components
- user: Database username (e.g.,
joip_user) - password: Database password (URL-encoded if contains special characters)
- host: Server hostname (e.g.,
ep-cool-name.us-east-2.aws.neon.tech) - port: PostgreSQL port (default:
5432) - database: Database name (e.g.,
neondb) - parameters: Query parameters (e.g.,
sslmode=require)
Example Connection Strings
URL Encoding: Passwords containing special characters (
@, !, #, etc.) must be URL-encoded in connection strings.Connection Pooling
JOIP implements connection pooling for optimal database performance (server/db.ts).
Default Pool Settings
Custom Pool Configuration
Override defaults with environment variables:Pool Tuning Recommendations
Small Apps (< 100 concurrent users):Performance Optimization
Indexes
JOIP’s schema includes performance indexes on frequently queried columns:npm run db:push.
Query Optimization
Drizzle ORM generates efficient queries, but follow these best practices:-
Use Select Projections: Only fetch needed columns
-
Batch Operations: Use transactions for multiple inserts
-
Limit Results: Always paginate large result sets
Database Monitoring
Neon provides built-in monitoring:- Open your project in Neon dashboard
- Navigate to Monitoring tab
- View:
- Connection count
- Query performance
- Storage usage
- Compute time
- Connection pool exhaustion
- Slow query detection
- Storage capacity warnings
Backup and Recovery
Neon Automatic Backups
Neon automatically backs up your database:- Frequency: Continuous (Write-Ahead Log streaming)
- Retention: 7 days (free tier), 30 days (paid plans)
- Point-in-Time Recovery: Restore to any second within retention period
Manual Backups
Create manual backups usingpg_dump:
Restore from Backup
Database Branching (Neon)
Neon’s branching feature allows safe testing of schema changes:Create Branch
- Open Neon dashboard
- Navigate to your project
- Click “Branches” → “Create Branch”
- Name:
stagingormigration-test - Select parent branch:
main
Troubleshooting
Connection Refused
Symptom:ECONNREFUSED or Connection refused errors
Solutions:
- Verify
DATABASE_URLis correct and includes port (:5432) - Check database is not paused (Neon free tier auto-pauses)
- Verify SSL is required:
?sslmode=require - Test connection with
psql $DATABASE_URL
SSL/TLS Errors
Symptom:SSL connection required or certificate errors
Solutions:
- Ensure connection string includes
?sslmode=require - For self-signed certs, use
?sslmode=disable(dev only) - Update
pgpackage:npm update pg
Pool Exhaustion
Symptom:sorry, too many clients already errors
Solutions:
- Check for connection leaks in code
- Reduce
DB_POOL_MAXto match database limits - Enable Neon’s connection pooling (PgBouncer)
- Upgrade Neon plan for more connections
Migration Failures
Symptom:npm run db:push fails with schema errors
Solutions:
- Verify database is empty for initial setup
- Check for existing tables with conflicts
- Review
shared/schema.tsfor syntax errors - Drop all tables and retry (dev only):
psql $DATABASE_URL -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"
Slow Queries
Symptom: Application timeouts or slow responses Solutions:- Check Neon monitoring for slow queries
- Add indexes to frequently queried columns
- Optimize queries (use projections, limits)
- Upgrade Neon compute size
- Enable query logging:
DB_LOG_QUERIES=true
Security Best Practices
Credential Rotation
Rotate database credentials periodically:Next Steps
Storage Configuration
Setup Supabase Storage for file uploads
Environment Variables
Complete environment variable reference
Deploy on Replit
Deploy your configured database to Replit