liveBook · Manning

Connection pooling

As explained in 100 Go Mistakes and How to Avoid Them

A database connection pool is a managed collection of reusable database connections that are allocated to operations and returned for later use.

A common mistake is treating sql.Open as a single database connection. It returns an *sql.DB that manages reusable connections, which may be in use by another goroutine or idle for later operations. section 10.4.2

Tune the pool according to database capacity and request behavior:

  • SetMaxOpenConns limits simultaneous database connections; leaving it unlimited can exceed what the database handles. section 10.4.2
  • SetMaxIdleConns controls reusable idle connections; increasing it can reduce reconnects during concurrent requests. section 10.4.2
  • SetConnMaxIdleTime and SetConnMaxLifetime close connections after configured idle or total lifetimes. section 10.4.2

When the pool is full

With five maximum connections, four ongoing connections leave one slot. A new query reuses an idle connection; without an idle connection, it creates one if a slot remains or waits until one becomes available. section 10.4.2

The same tradeoff appears in Go's HTTP client. Connections are reused, but MaxIdleConnsPerHost defaults to two; repeated parallel requests to one host can therefore cause reconnects and higher latency. section 10.7.1

Figure 10.1 A connection pool with five connections

Use the five-connection diagram to trace idle connections, active connections, available capacity, reuse, creation, and waiting. section 10.4.2

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains pool states, allocation, waiting, and four database limits, then contrasts HTTP idle and per-host limits.
Examples
Uses a five-connection database pool and 100 requests to one HTTP host to expose reuse and reconnection behavior.
What you can do after
Operate and configure database or HTTP pools by matching connection limits and idle policies to workload and backend capacity.
How it connects
Connects connection pooling with database capacity, goroutines, concurrent requests, HTTP clients, transports, timeouts, and latency.

Also explained in

Compare how 9 books explain connection pooling →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.