How to Handle Database Connection Timeouts in Go

Configure database connection timeouts in Go by setting DialTimeout and connection pool limits on your client, not via GODEBUG.

Database connection timeouts in Go are handled by configuring the net/http transport or your database driver's connection pool settings, not via GODEBUG. Set the DialTimeout, ReadTimeout, and WriteTimeout fields on your http.Transport or use the SetConnMaxLifetime and SetMaxIdleConns methods on your *sql.DB instance to control connection behavior. For example, to configure an HTTP client with timeouts:

client := &http.Client{
	Transport: &http.Transport{
		DialContext: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
		}).DialContext,
		ForceAttemptHTTP2:     true,
		MaxIdleConns:          100,
		IdleConnTimeout:       90 * time.Second,
		TLSHandshakeTimeout:   10 * time.Second,
		ExpectContinueTimeout: 1 * time.Second,
	},
	Timeout: 30 * time.Second,
}

For SQL databases, configure the connection pool after opening the database:

db, err := sql.Open("postgres", "your-connection-string")
if err != nil {
	log.Fatal(err)
}
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(25)
db.SetConnMaxLifetime(5 * time.Minute)

The GODEBUG environment variable is used for controlling internal Go runtime behaviors like HTTP/2 usage (http2client=0) or tar path security (tarinsecurepath=0), but it does not directly manage database connection timeouts.