Skip to content

Database connection pooling w/ timeout and retries #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
struckchure opened this issue Feb 15, 2025 · 0 comments
Open

Database connection pooling w/ timeout and retries #13

struckchure opened this issue Feb 15, 2025 · 0 comments
Labels
enhancement New feature or request good first issue Good for newcomers

Comments

@struckchure
Copy link
Contributor

          _:hammer_and_wrench: Refactor suggestion_

Enhance database connection configuration for production readiness.

Consider adding the following improvements:

  1. Add connection pooling configuration
  2. Add context with timeout for connection
  3. Add validation for DATABASE_URL
  4. Add retry mechanism for initial connection

Here's a suggested implementation:

-func NewDatabaseConnection(env *Env) (*gorm.DB, error) {
-	return gorm.Open(postgres.Open(env.DATABASE_URL), &gorm.Config{})
-}
+func NewDatabaseConnection(env *Env) (*gorm.DB, error) {
+	if env.DATABASE_URL == "" {
+		return nil, fmt.Errorf("DATABASE_URL is required")
+	}
+
+	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+	defer cancel()
+
+	config := &gorm.Config{
+		PrepareStmt: true,
+		NowFunc: func() time.Time {
+			return time.Now().UTC()
+		},
+	}
+
+	var db *gorm.DB
+	var err error
+	
+	for retries := 3; retries > 0; retries-- {
+		db, err = gorm.Open(postgres.Open(env.DATABASE_URL), config)
+		if err == nil {
+			break
+		}
+		time.Sleep(time.Second)
+	}
+	if err != nil {
+		return nil, fmt.Errorf("failed to connect to database: %w", err)
+	}
+
+	sqlDB, err := db.DB()
+	if err != nil {
+		return nil, fmt.Errorf("failed to get underlying *sql.DB: %w", err)
+	}
+
+	// Set connection pool settings
+	sqlDB.SetMaxIdleConns(10)
+	sqlDB.SetMaxOpenConns(100)
+	sqlDB.SetConnMaxLifetime(time.Hour)
+
+	return db, nil
+}

Don't forget to add the required imports:

import (
	"context"
	"fmt"
	"time"
)

Originally posted by @coderabbitai[bot] in #12 (comment)

@struckchure struckchure added enhancement New feature or request good first issue Good for newcomers labels Feb 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request good first issue Good for newcomers
Projects
None yet
Development

No branches or pull requests

1 participant