mirror of
https://github.com/kjanat/livedash-node.git
synced 2026-01-16 11:32:13 +01:00
- Set up pre-commit hooks with husky and lint-staged for automated code quality - Improved TypeScript type safety by replacing 'any' types with proper generics - Fixed markdown linting violations (MD030 spacing) across all documentation - Fixed compound adjective hyphenation in technical documentation - Fixed invalid JSON union syntax in API documentation examples - Automated code formatting and linting on commit - Enhanced error handling with better type constraints - Configured biome and markdownlint for consistent code style - All changes verified with successful production build
4.9 KiB
4.9 KiB
Database Connection Pooling Guide
This document explains how to optimize database connection pooling for better performance and resource management in the LiveDash application.
Overview
The application now supports two connection pooling modes:
- Standard Pooling: Default Prisma client connection pooling
- Enhanced Pooling: Advanced PostgreSQL connection pooling with custom configuration
Configuration
Environment Variables
Add these variables to your .env.local file:
# Database Connection Pooling Configuration
DATABASE_CONNECTION_LIMIT=20 # Maximum connections in pool
DATABASE_POOL_TIMEOUT=10 # Idle timeout in seconds
USE_ENHANCED_POOLING=true # Enable advanced pooling (production recommended)
# Optional: Add pool parameters to DATABASE_URL for additional control
DATABASE_URL="postgresql://user:pass@host:5432/db?connection_limit=20&pool_timeout=10"
Pooling Modes
Standard Pooling (Default)
- Uses Prisma's built-in connection pooling
- Simpler configuration
- Good for development and small-scale deployments
Enhanced Pooling (Recommended for Production)
- Uses PostgreSQL native connection pooling with
@prisma/adapter-pg - Advanced monitoring and health checks
- Better resource management
- Detailed connection metrics
Implementation Details
Fixed Issues
- Multiple PrismaClient Instances:
- ❌ Before: Each scheduler created its own PrismaClient
- ✅ After: All modules use singleton pattern from
lib/prisma.ts
- No Connection Management:
- ❌ Before: No graceful shutdown or connection cleanup
- ✅ After: Proper cleanup on process termination
- No Monitoring:
- ❌ Before: No visibility into connection usage
- ✅ After: Health check endpoint and connection metrics
Key Files Modified
lib/prisma.ts- Enhanced singleton with pooling optionslib/database-pool.ts- Advanced pooling configurationlib/processingScheduler.ts- Fixed to use singletonlib/importProcessor.ts- Fixed to use singletonlib/processingStatusManager.ts- Fixed to use singletonlib/schedulers.ts- Added graceful shutdownapp/api/admin/database-health/route.ts- Monitoring endpoint
Monitoring
Health Check Endpoint
Check database connection health:
curl -H "Authorization: Bearer your-token" \
http://localhost:3000/api/admin/database-health
Response includes:
- Connection status
- Pool statistics (if enhanced pooling enabled)
- Basic metrics (session counts, etc.)
- Configuration details
Connection Metrics
With enhanced pooling enabled, you'll see console logs for:
- Connection acquisitions/releases
- Pool size changes
- Error events
- Health check results
Performance Benefits
Before Optimization
- Multiple connection pools (one per scheduler)
- Potential connection exhaustion under load
- No connection monitoring
- Resource waste from idle connections
After Optimization
- Single shared connection pool
- Configurable pool size and timeouts
- Connection health monitoring
- Graceful shutdown and cleanup
- Better resource utilization
Recommended Settings
Development
DATABASE_CONNECTION_LIMIT=10
DATABASE_POOL_TIMEOUT=30
USE_ENHANCED_POOLING=false
Production
DATABASE_CONNECTION_LIMIT=20
DATABASE_POOL_TIMEOUT=10
USE_ENHANCED_POOLING=true
High-Load Production
DATABASE_CONNECTION_LIMIT=50
DATABASE_POOL_TIMEOUT=5
USE_ENHANCED_POOLING=true
Troubleshooting
Connection Pool Exhaustion
If you see "too many connections" errors:
- Increase
DATABASE_CONNECTION_LIMIT - Check for connection leaks in application code
- Monitor the health endpoint for pool statistics
Slow Database Queries
If queries are timing out:
- Decrease
DATABASE_POOL_TIMEOUT - Check database query performance
- Consider connection pooling at the infrastructure level (PgBouncer)
Memory Usage
If memory usage is high:
- Decrease
DATABASE_CONNECTION_LIMIT - Enable enhanced pooling for better resource management
- Monitor idle connection cleanup
Best Practices
- Always use the singleton: Import
prismafromlib/prisma.ts - Monitor connection usage: Use the health endpoint regularly
- Set appropriate limits: Don't over-provision connections
- Enable enhanced pooling in production: Better resource management
- Implement graceful shutdown: Ensure connections are properly closed
- Log connection events: Monitor for issues and optimize accordingly
Next Steps
Consider implementing:
- Connection pooling middleware: PgBouncer or similar
- Read replicas: For read-heavy workloads
- Connection retry logic: For handling temporary failures
- Metrics collection: Prometheus/Grafana for detailed monitoring