cshah
cshah

Reputation: 23

Postgres connection frequently closed/reopened

I am seeing frequently connection close and open messages for every request on the file upload process.

One of the articles I found was asking to set open/idle connections but it not working error message still coming.

What will be case I am not able to find what's going on so attaching data database.go code and dog log screen.

func InitDatabase(ctx context.Context, opts infrastructure.DBOptions) (Database, error) {
    dsn := fmt.Sprintf("host=%s dbname=%s user=%s sslmode=disable",
        opts.Host,
        opts.Database,
        opts.User,
    )

    if opts.Pass != "" {
        dsn = fmt.Sprintf("%s password=%s", dsn, opts.Pass)
    }

    sqltrace.Register("postgres", &pq.Driver{})
    db, err := sqltrace.Open("postgres", dsn)
    if err != nil {
        return nil, err
    }

    // Retrieve the value of "MaxOpenConns" and "MaxIdleConns" from opts
    defaultMaxIdleConns := 100
    defaultMaxOpenConns := 100

    // Convert the string to an integer
    maxIdleConns, err := strconv.Atoi(opts.MaxIdleConns)

    if err != nil {
        // Handle the error if conversion fails
        db.SetMaxIdleConns(defaultMaxIdleConns)
    } else {
        // Set maximum number of connections in idle connection pool.
        db.SetMaxIdleConns(maxIdleConns)
    }

    // Convert the string to an integer
    maxOpenConns, err := strconv.Atoi(opts.MaxOpenConns)

    if err != nil {
        // Handle the error if conversion fails
        db.SetMaxOpenConns(defaultMaxOpenConns)
    } else {
        // Set the maximum number of open connections to the database.
        db.SetMaxOpenConns(maxOpenConns)
    }

    db.SetConnMaxLifetime(time.Hour)

    database := &DocumentDatabase{
        DB: db,
    }

    log.Info().Caller().Msgf("initialized db host: %v | database: %v", opts.Host, opts.Database)
    return database, nil
}    

datadog log

Upvotes: 1

Views: 130

Answers (0)

Related Questions