Your Question

When connecting to a database using a domain name, DNS resolution is triggered every time a connection is established, which can cause DNS resolution storms. The Go HTTP framework provides the ability to customize net.Resolver, which can be used to implement DNS caching. Does GORM have similar functionality?

Comment From: ivila

I don't see why it will cause DNS resolution storms, as there are connection pool with MaxIdleConnection and MaxOpenConnection settings, most of the time, gorm do not create new connection.

Comment From: yzcwf

d, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { return err } sqlDB, err := d.DB() sqlDB.SetMaxOpenConns(60) sqlDB.SetMaxIdleConns(0) db = d I set it up this way, and I observed that a large number of new connections were being created.

Comment From: ivila

d, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { return err } sqlDB, err := d.DB() sqlDB.SetMaxOpenConns(60) sqlDB.SetMaxIdleConns(0) db = d I set it up this way, and I observed that a large number of new connections were being created.

@yzcwf I wonder why you set SetMaxIdleConns to zero? You want to create a new connection for every query? I suggest changing MaxIdleConns to the same as MaxOpenConns(or half as MaxOpenConns), just like the following.

    d, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) 
    if err != nil { 
        return err
    } 
    sqlDB, err := d.DB() 
    sqlDB.SetMaxOpenConns(60)
    // set MaxIdleConns to 30 or 60 
    sqlDB.SetMaxIdleConns(60)
    //sqlDB.SetMaxIdleConns(30)

    // also, don't forget to set setMaxIdleTime in case that 
    // your server will close long time inactive connections
    // for mysql server, the default value is 8 hours, aka 8 * 60 * 60 seconds
    sqlDB.SetConnMaxIdleTime(5 * 60)  // for client side, close idle connections after 5 minutes inactive is enough
    sqlDB.SetConnMaxLifetime(24 * 60 * 60) // prevent a bug of golang: https://github.com/golang/go/issues/45993

    db = d

you may check https://pkg.go.dev/database/sql#DB.SetConnMaxIdleTime and https://pkg.go.dev/database/sql#DB.SetMaxIdleConns as well.

Comment From: abhi-112

I am facing a issue where i have configured the pooling but still multiple connections are being created and held on pgsql server. Every time I send a hit it create more and more entries in pg_stat_activity Screenshot 2024-04-03 at 12 55 02 PM Screenshot 2024-04-03 at 12 55 27 PM