package database import ( "database/sql" "time" "github.com/rs/zerolog" "base/pkg/metrics" ) // monitorConnectionPool periodically monitors and records connection pool metrics func monitorConnectionPool(sqlDB *sql.DB, metric *metrics.Metrics, logger zerolog.Logger) { ticker := time.NewTicker(30 * time.Second) // Monitor every 30 seconds defer ticker.Stop() for range ticker.C { stats := sqlDB.Stats() // Record connection pool metrics using available methods // Note: Connection pool size metrics are not available in current metrics package // Consider adding them if needed for monitoring // Record wait time if there are any waits if stats.WaitCount > 0 { avgWaitTime := time.Duration(stats.WaitDuration.Nanoseconds() / stats.WaitCount) metric.RecordDatabaseQuery("WaitTime", "database", avgWaitTime, nil) } // Log connection pool stats at info level for better visibility logger.Info(). Int("open_connections", stats.OpenConnections). Int("in_use", stats.InUse). Int("idle", stats.Idle). Int("max_open", stats.MaxOpenConnections). Int64("wait_count", stats.WaitCount). Int64("wait_duration_ms", stats.WaitDuration.Milliseconds()). Msg("Database connection pool stats") // Alert if we're approaching connection limits if stats.OpenConnections >= 7 { // 7 out of 8 max connections logger.Warn(). Int("open_connections", stats.OpenConnections). Int("max_open", stats.MaxOpenConnections). Msg("Database connection pool approaching limit - consider reducing concurrent operations") } // Alert if there are connection waits if stats.WaitCount > 0 { logger.Warn(). Int64("wait_count", stats.WaitCount). Int64("wait_duration_ms", stats.WaitDuration.Milliseconds()). Msg("Database connections are being waited for - possible connection pool exhaustion") } } }