Skip to content
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

Expose Postgres database connection configuration properties including max connection lifetime #321

Open
kentbull opened this issue Oct 23, 2022 · 1 comment

Comments

@kentbull
Copy link

Configuring the max lifetime for the Postgres database connection type, and likely all others, like maxLifetime in HikariCP would allow for regular connection cycling on a configured lifetime duration. I believe the default is "0" in the database/sql library, or infinite lifetimes.

PQ says it "Handles bad connections for database/sql" and line 727 func TestCloseBadConn seems to indicate PQ will recover from bad connections, that seem to last for an infinite timeframe, though I have seen in production stale connection pools not recycle stale connections. If we have access to the underlying configuration properties then we can manually configure the connection lifecycle.

The configuration properties I have in mind are as indicated in this article:

db.SetMaxOpenConns(25)
db.SetMaxIdleConns(25)
db.SetConnMaxLifetime(5*time.Minute)
@kentbull
Copy link
Author

Here's the relevant code from database/sql showing that If d <= 0, connections are not closed due to a connection's age.

// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
//
// Expired connections may be closed lazily before reuse.
//
// If d <= 0, connections are not closed due to a connection's age.
func (db *DB) SetConnMaxLifetime(d time.Duration) {
	if d < 0 {
		d = 0
	}
	db.mu.Lock()
	// Wake cleaner up when lifetime is shortened.
	if d > 0 && d < db.maxLifetime && db.cleanerCh != nil {
		select {
		case db.cleanerCh <- struct{}{}:
		default:
		}
	}
	db.maxLifetime = d
	db.startCleanerLocked()
	db.mu.Unlock()
}

Looks like all we need to do is expose that API. PR incoming...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant