liveBook · Manning

Connection pooling

As explained in Go by Example

A connection pool is a managed collection of reusable network connections maintained to avoid repeatedly establishing new connections.

Connection pooling keeps reusable network connections under a long-lived manager instead of establishing a new connection for every operation. Reuse avoids the network latency and handshakes of reconnecting, while the manager selects, opens, and closes connections as needed. section 10.1 section 10.1.2

In Go’s database/sql API, sql.Open verifies a registered driver and returns a *sql.DB whose pool may initially be empty. Calling PingContext verifies connectivity and, on success, adds the first connection; retain the resulting *DB for the program lifetime rather than reopening it per query. section 10.1.2

Open and verify a SQLite pool

Use sql.Open("sqlite", dsn) to create the *sql.DB handle, then call db.PingContext(ctx). Wrap either failure with context such as "opening" or "pinging" before returning the handle for later queries. section 10.1.2

A pool tracks idle and in-use connections. For a database task, it uses an idle connection when available; otherwise it establishes one. Tune capacity with SetMaxOpenConns and SetMaxIdleConns, and bound reuse with SetConnMaxLifetime and SetConnMaxIdleTime. section 10.1.2

The same reuse principle applies to HTTP: http.Transport is a RoundTripper with a TCP connection pool. Reuse one Transport while sending requests, whether it is the default transport or a selected implementation behind http.Client. section 7.4.1

Figure 10.2 Connecting to the SQLite database using Open and PingContext
A screenshot of a computer

AI-generated content may be incorrect.

Trace the transition from an empty *sql.DB pool after Open to its first reusable connection after PingContext succeeds. section 10.1.2

How Go by Example covers it

How deep it goes
Explains pool initialization, selection, lifecycle retention, and four database tuning controls without detailing their numeric trade-offs.
Examples
Demonstrates a SQLite Dial function using sql.Open and PingContext, plus HTTP requests sharing an http.Transport.
What it assumes
Assumes familiarity with Go database and HTTP APIs while introducing driver verification and connection establishment steps.
What you can do after
Apply it via *sql.DB and http.Transport by retaining shared handles and optionally configuring database pool limits.
How it connects
Connects connection pooling to database/sql, drivers, PingContext, HTTP clients, RoundTripper, and http.Transport.

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 Go by Example. The section links point to the parts of the book it draws on.