Fix SQLConnectionPoolExhausted: sql: database/sql: connection pool exhausted, all connections are in use in Go
This error occurs when all connections in Go's database/sql connection pool are in use and a new query cannot acquire one before the timeout. Common causes include leaked connections from unclosed rows, too-low MaxOpenConns, or long-running transactions. Fix it by ensuring all rows and statements are closed, tuning pool settings, and adding connection timeout context.
Reading the Stack Trace
Here's what each line means:
- database/sql.(*DB).conn(0x14000118300, {0x1029f0ea0, 0x14000196040}, 0x1): The connection pool's conn method is blocked waiting for a free connection. All MaxOpenConns connections are currently in use.
- main.ListOrders(0x14000226000) /app/handlers/order.go:18 +0x1c4: The ListOrders handler at line 18 triggers a query that cannot acquire a connection from the exhausted pool.
- database/sql.(*DB).QueryContext(0x14000118300, {0x1029f0ea0, 0x14000196040}, {0x1028f1e60, 0x15}, {0x0, 0x0, 0x0}): QueryContext blocks waiting for a connection, eventually timing out via the context deadline.
Common Causes
1. Rows not closed after query
Forgetting to close sql.Rows after a query leaks the connection, preventing it from returning to the pool.
func ListOrders(c *gin.Context) {
rows, err := db.Query("SELECT * FROM orders")
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
// Missing: defer rows.Close()
var orders []Order
for rows.Next() {
var o Order
rows.Scan(&o.ID, &o.Total)
orders = append(orders, o)
}
c.JSON(200, orders)
}
2. MaxOpenConns too low for traffic
The pool has fewer connections than concurrent requests, causing requests to queue and eventually timeout.
db.SetMaxOpenConns(2) // only 2 connections for high-traffic app
3. Long-running transactions hold connections
A transaction that takes minutes to complete holds a connection for its entire lifetime, starving other queries.
tx, _ := db.Begin()
// ... complex operations taking minutes ...
tx.Commit() // connection held for entire duration
The Fix
Always defer rows.Close() immediately after the query. Configure pool settings with SetMaxOpenConns, SetMaxIdleConns, and SetConnMaxLifetime. Use QueryContext with a timeout. Check rows.Err() after the loop for errors that occurred during iteration.
func ListOrders(c *gin.Context) {
rows, err := db.Query("SELECT * FROM orders")
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
var orders []Order
for rows.Next() {
var o Order
rows.Scan(&o.ID, &o.Total)
orders = append(orders, o)
}
c.JSON(200, orders)
}
func init() {
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(5 * time.Minute)
db.SetConnMaxIdleTime(1 * time.Minute)
}
func ListOrders(c *gin.Context) {
ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)
defer cancel()
rows, err := db.QueryContext(ctx, "SELECT id, total FROM orders LIMIT 100")
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
c.JSON(http.StatusGatewayTimeout, gin.H{"error": "query timed out"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "database error"})
return
}
defer rows.Close()
var orders []Order
for rows.Next() {
var o Order
if err := rows.Scan(&o.ID, &o.Total); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "scan error"})
return
}
orders = append(orders, o)
}
if err := rows.Err(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "query error"})
return
}
c.JSON(http.StatusOK, orders)
}
Testing the Fix
package handlers_test
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func TestListOrders_ClosesRows(t *testing.T) {
db, mock, _ := sqlmock.New()
defer db.Close()
rows := sqlmock.NewRows([]string{"id", "total"}).AddRow(1, 99.99)
mock.ExpectQuery("SELECT").WillReturnRows(rows)
gin.SetMode(gin.TestMode)
r := gin.New()
r.GET("/api/orders", NewListOrders(db))
req := httptest.NewRequest(http.MethodGet, "/api/orders", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.NoError(t, mock.ExpectationsWereMet())
}
func TestListOrders_DBTimeout(t *testing.T) {
db, mock, _ := sqlmock.New()
defer db.Close()
mock.ExpectQuery("SELECT").WillReturnError(context.DeadlineExceeded)
gin.SetMode(gin.TestMode)
r := gin.New()
r.GET("/api/orders", NewListOrders(db))
req := httptest.NewRequest(http.MethodGet, "/api/orders", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusGatewayTimeout, w.Code)
}
Run your tests:
go test ./handlers/... -v
Pushing Through CI/CD
git checkout -b fix/go-sql-connection-pool,git add handlers/order.go handlers/order_test.go main.go,git commit -m "fix: close rows, tune pool settings, and add query timeouts",git push origin fix/go-sql-connection-pool
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.22'
- run: go mod download
- run: go vet ./...
- run: go test ./... -race -coverprofile=coverage.out
- run: go build ./...
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
go get github.com/bugstack/sdk
Step 2: Initialize
import "github.com/bugstack/sdk"
func init() {
bugstack.Init(os.Getenv("BUGSTACK_API_KEY"))
}
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run go test ./... locally to confirm queries work with pool limits.
- Open a pull request with the connection pool changes.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and monitor connection pool metrics in staging.
Frequently Asked Questions
BugStack validates that all queries close their rows, tests with mock databases under simulated pool exhaustion, and checks pool configuration values before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
Use db.Stats() to expose pool metrics (OpenConnections, InUse, Idle, WaitCount) via a /debug/db endpoint or Prometheus exporter.
The most common cause is forgetting defer rows.Close() after db.Query. Also check that transactions are always committed or rolled back, even on error paths.