Skip to content

Commit

Permalink
fix(db): sets max open and idle connections for postgres
Browse files Browse the repository at this point in the history
When postgres is used as backing database for headscale, it does not set
a limit on maximum open and idle connections which leads to hundreds of
open connections to the postgres server. This commit fixes that by
setting up a connection pool while creating the gorm DB instance.
  • Loading branch information
pallabpain committed Jan 12, 2024
1 parent 3b10328 commit 9274087
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions hscontrol/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,14 @@ import (

"github.com/glebarez/sqlite"
"github.com/go-gormigrate/gormigrate/v2"
"github.com/juanfont/headscale/hscontrol/notifier"
"github.com/juanfont/headscale/hscontrol/types"
"github.com/juanfont/headscale/hscontrol/util"
"github.com/rs/zerolog/log"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"

"github.com/juanfont/headscale/hscontrol/notifier"
"github.com/juanfont/headscale/hscontrol/types"
"github.com/juanfont/headscale/hscontrol/util"
)

const (
Expand Down Expand Up @@ -360,10 +361,17 @@ func openDB(dbType, connectionAddr string, debug bool) (*gorm.DB, error) {
return db, err

case Postgres:
return gorm.Open(postgres.Open(connectionAddr), &gorm.Config{
db, err := gorm.Open(postgres.Open(connectionAddr), &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
Logger: dbLogger,
})

sqlDB, _ := db.DB()
sqlDB.SetMaxOpenConns(10)
sqlDB.SetMaxIdleConns(10)
sqlDB.SetConnMaxIdleTime(time.Hour)

return db, err
}

return nil, fmt.Errorf(
Expand Down

0 comments on commit 9274087

Please sign in to comment.