sqlgo

Set minimum idle connections in SQL pool


Background: I want to reduce the response time when working with SQL databases in my Go applications.

Golang provides an SQL package with a connection pool. It includes the following configuration options:

However, there is nothing like SetMinIdleConns to ensure that there are always some open connections that can be used when a request comes in. As a result, my application has good response times under load, but the first request after some idle time always has some delay because it needs to open a new connection to the database.

Question: Is there a way to fix this with the Go standard library or is there some alternative connection pooling library for Go with this feature?

Workarounds and already tried:

  1. I tried setting ConnMaxIdleTime and ConnMaxLifetime to very high values, but then the SQL server closes them and I get even higher delays or even errors on the first call after a long idle time.
  2. Obviously, I could create a background task that periodically uses the database. However, this does not seem like a clean solution.
  3. I am considering porting a connection pool library from another language to Go.

Solution

  • The pgx/pgxpool library provides a connection pool for Postgres, which allows to configure the minimum number of connections:

        connConf, err := pgxpool.ParseConfig(connStr)
        // ... (error handling)
        connConf.MaxConns = 50
        // Set minimum number of connections:
        connConf.MinConns = 10
        pool, err := pgxpool.ConnectConfig(context.TODO(), connConf)