48 lines
1.8 KiB
Go
48 lines
1.8 KiB
Go
|
|
package config
|
||
|
|
|
||
|
|
import (
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"go.uber.org/zap"
|
||
|
|
|
||
|
|
"veza-backend-api/internal/database"
|
||
|
|
)
|
||
|
|
|
||
|
|
// initDatabaseWithRetry initialise la connexion à la base de données avec des tentatives de retry
|
||
|
|
func initDatabaseWithRetry(databaseURL, databaseReadURL string, maxRetries int, retryInterval time.Duration, logger *zap.Logger) (*database.Database, error) {
|
||
|
|
dbConfig := &database.Config{
|
||
|
|
URL: databaseURL,
|
||
|
|
// BE-DB-015: Optimized connection pool settings for production
|
||
|
|
// MaxOpenConns: Recommended formula: (2 * CPU cores) + effective_spindle_count
|
||
|
|
// Default: 25 for small-medium apps, 50-100 for high-traffic apps
|
||
|
|
MaxOpenConns: getEnvAsInt("DB_MAX_OPEN_CONNS", 50),
|
||
|
|
// MaxIdleConns: Should be ~25% of MaxOpenConns to maintain warm connections
|
||
|
|
MaxIdleConns: getEnvAsInt("DB_MAX_IDLE_CONNS", 12),
|
||
|
|
// MaxLifetime: 5-15 minutes recommended to avoid connection timeouts
|
||
|
|
// PostgreSQL default idle_in_transaction_session_timeout is 0 (unlimited)
|
||
|
|
MaxLifetime: getEnvAsDuration("DB_MAX_LIFETIME", 10*time.Minute),
|
||
|
|
// MaxIdleTime: 5-10 minutes to close idle connections and free resources
|
||
|
|
MaxIdleTime: getEnvAsDuration("DB_MAX_IDLE_TIME", 5*time.Minute),
|
||
|
|
MaxRetries: maxRetries,
|
||
|
|
RetryInterval: retryInterval,
|
||
|
|
}
|
||
|
|
|
||
|
|
db, err := database.NewDatabaseWithRetry(dbConfig, logger)
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
if databaseReadURL != "" {
|
||
|
|
readConfig := &database.Config{
|
||
|
|
URL: databaseReadURL,
|
||
|
|
MaxOpenConns: getEnvAsInt("DB_READ_MAX_OPEN_CONNS", 25),
|
||
|
|
MaxIdleConns: getEnvAsInt("DB_READ_MAX_IDLE_CONNS", 6),
|
||
|
|
MaxLifetime: getEnvAsDuration("DB_MAX_LIFETIME", 10*time.Minute),
|
||
|
|
MaxIdleTime: getEnvAsDuration("DB_MAX_IDLE_TIME", 5*time.Minute),
|
||
|
|
}
|
||
|
|
if err := db.InitReadReplica(readConfig); err != nil {
|
||
|
|
logger.Warn("Failed to init read replica, using primary for reads", zap.Error(err))
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return db, nil
|
||
|
|
}
|