Your Question

Why did I configure the gorm with sqlDB.SetMaxIdleConns(25) and sqlDB.SetMaxOpenConns(50), but the number of idle connections exceeds the specified limit?

The document you expected this should be explained

https://gorm.io/docs/connecting_to_the_database.html#Connection-Pool

package dbConfig

import (
    "fmt"
    "log"
    "os"
    "time"

    "gorm.io/gorm/logger"

    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

var PostgresSql *gorm.DB

func ConnectDBPostgresSQL() {
    var err error
    dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s application_name=%s sslmode=disable", os.Getenv("POSTGRES_DB_HOST"), os.Getenv("POSTGRES_DB_PORT"), os.Getenv("POSTGRES_DB_USERNAME"), os.Getenv("POSTGRES_DB_PASSWORD"), os.Getenv("POSTGRES_DB_NAME"), os.Getenv("APPLICATION_NAME"))
    PostgresSql, err = gorm.Open(postgres.Open(dsn), &gorm.Config{
        Logger: logger.Default.LogMode(logger.Silent),
    })
    if err != nil {
        log.Printf("gorm can't open postgres cause: %s", err.Error())
        return
    }

    if PostgresSql == nil {
        return
    }

    sqlDB, err := PostgresSql.DB()

    if err != nil {
        log.Println(err.Error())
        return
    }

    sqlDB.SetMaxIdleConns(20)
    sqlDB.SetMaxOpenConns(50)
    sqlDB.SetConnMaxIdleTime(time.Minute * 10)
    sqlDB.SetConnMaxLifetime(time.Minute * 10)
}

Screenshot 2023-09-19 164822

Expected answer

When I execute the command SELECT * FROM pg_stat_activity;, I can see that the Idle status exceeds the configured limit. For example, in this screenshot, there are up to 29 Idle connections, and they keep increasing. What could be the reason for this?

Comment From: C-puqing

Hi, @puphan I encountered the same problem. Do you have any solution?