Skip to main content
Engineering
What this does: Tunes PostgreSQL for high-concurrency ML workloads — handling dozens of parallel optimization workers writing results simultaneously without data corruption or slowdowns.

Overview

The Demand Forecasting system uses PostgreSQL as the persistent backend for Optuna studies (hyperparameter optimization history). Given the high concurrency of parallel optimization (multiple workers writing trial results simultaneously), the database configuration is tuned for performance and reliability. This guide details the specific optimizations implemented to handle ML workloads, based on pg-aiguide best practices.

Connection Pooling

To manage concurrent connections from Airflow workers efficiently, we use a tailored connection pooling strategy in src/demand_forecasting/utils/s3_helpers.py and catboost_nodes_enhanced.py.

Configuration Rationale

Database Schema Optimizations

Optuna creates its own tables (trials, trial_params, trial_values), but we apply specific indexes to speed up the complex queries used during the “Best Trial” lookup.

Indexing Strategy

The following custom indexes are applied via app-ml/scripts/init-optuna-db.sql:

Table Maintenance

Optuna tables grow rapidly. We use an aggressive autovacuum schedule to prevent bloat:
  • Autovacuum Scale Factor: 0.05 (Runs when 5% of table changes, default is 20%)
  • Manual Vacuum: Scheduled weekly via maintenance scripts.

Performance Benchmarks

Our internal benchmarks (scripts/validate_postgres_performance.py) ensure the storage backend meets latency requirements:

Troubleshooting

”Too Many Connections”

If you encounter FATAL: sorry, too many clients already, it means the combined pool size of all Airflow workers exceeds the PostgreSQL max_connections limit. Solution:
  1. Check max_connections in postgresql.conf (Recommended: 100+).
  2. Reduce pool_size in catboost_nodes_enhanced.py.
  3. If scaling further, deploy PgBouncer as a connection pooler in front of PostgreSQL.