Stage 3 · Build
Databases & Persistence
Connection Pooling
Tune database/sql pools, pgxpool, max open connections, idle timeouts, and PostgreSQL saturation.
Why Connection Pools
Opening a database connection is expensive. It involves a TCP handshake, SSL negotiation, and authentication. Connection pools reuse established connections across requests, eliminating this overhead. Every production Go application needs a connection pool.
database/sql Pool
pgxpool
pgxpool is the native connection pool for pgx, the most popular pure Go PostgreSQL driver. It avoids the database/sql abstraction overhead and provides better performance for PostgreSQL-specific features.
Pool Sizing
Pool size depends on your workload. Too few connections and queries wait. Too many and PostgreSQL saturates. A good starting point is 2x CPU cores for MaxOpenConns.
| Workload | MaxOpenConns | MaxIdleConns |
|---|---|---|
| Low traffic API | 10 | 5 |
| Medium traffic API | 25 | 10 |
| High traffic API | 50 | 25 |
| Background worker | 10 | 5 |
| Mixed (API + worker) | 30 | 15 |
Start with MaxOpenConns=25 and MaxIdleConns=5. Monitor PostgreSQL connections with pg_stat_activity. If queries wait for connections, increase MaxOpenConns. If connections sit idle, decrease.
Monitoring Pools
Common Pitfalls
- Not closing rows: Rows not closed hold connections indefinitely. Always defer rows.Close().
- Unbounded queries: Large result sets hold connections longer. Use LIMIT and pagination.
- Transaction timeouts: Long transactions hold connections and locks. Keep them short.
- MaxOpenConns too high: More connections than PostgreSQL can handle causes context deadline exceeded errors.
- Not monitoring: Without pool metrics, you cannot diagnose connection exhaustion.
If your application connects to multiple databases, each connection pool is independent. MaxOpenConns=25 on each pool means up to 50 total connections. Account for this when sizing PostgreSQL max_connections.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.