Skip to content

Commit edaacad

Browse files
authored
fix: add backoff also to postgresql (kubeflow#1263)
Signed-off-by: Alessio Pragliola <[email protected]>
1 parent 04ba579 commit edaacad

File tree

1 file changed

+30
-4
lines changed

1 file changed

+30
-4
lines changed

internal/datastore/embedmd/postgres/connect.go

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,18 @@
11
package postgres
22

33
import (
4+
"fmt"
5+
"time"
6+
47
"github.com/golang/glog"
58
"gorm.io/driver/postgres"
69
"gorm.io/gorm"
10+
"gorm.io/gorm/logger"
11+
)
12+
13+
const (
14+
// postgresMaxRetries is the maximum number of attempts to retry PostgreSQL connection.
15+
postgresMaxRetries = 25 // 25 attempts with incremental backoff (1s, 2s, 3s, ..., 25s) it's ~5 minutes
716
)
817

918
type PostgresDBConnector struct {
@@ -18,17 +27,34 @@ func NewPostgresDBConnector(dsn string) *PostgresDBConnector {
1827
}
1928

2029
func (c *PostgresDBConnector) Connect() (*gorm.DB, error) {
30+
var db *gorm.DB
31+
var err error
32+
2133
glog.V(2).Infof("Attempting to connect with DSN: %q", c.DSN)
22-
db, err := gorm.Open(postgres.Open(c.DSN), &gorm.Config{})
34+
35+
for i := range postgresMaxRetries {
36+
db, err = gorm.Open(postgres.Open(c.DSN), &gorm.Config{
37+
Logger: logger.Default.LogMode(logger.Silent),
38+
TranslateError: true,
39+
})
40+
if err == nil {
41+
break
42+
}
43+
44+
glog.Warningf("Retrying connection to PostgreSQL (attempt %d/%d): %v", i+1, postgresMaxRetries, err)
45+
46+
time.Sleep(time.Duration(i+1) * time.Second)
47+
}
48+
2349
if err != nil {
24-
return nil, err
50+
return nil, fmt.Errorf("failed to connect to PostgreSQL: %w", err)
2551
}
2652

2753
c.db = db
2854
glog.Info("Successfully connected to PostgreSQL database")
2955
return db, nil
30-
}
56+
}
3157

3258
func (c *PostgresDBConnector) DB() *gorm.DB {
3359
return c.db
34-
}
60+
}

0 commit comments

Comments
 (0)