跪拜 Guibai
← Back to the summary

Go's 'sql: waiting for connection' Pitfall: Why Raising MaxOpenConns Only Makes It Worse

🔥🔥sql: waiting for connection 踩坑:不要一味调大 MaxOpenConns

Recently, a very confusing failure occurred in production. The on-call engineer's alerts kept flooding with sql: waiting for connection, and a large number of interfaces timed out. But when we checked the slow query log and MySQL monitoring, the DB CPU was very low, and the average single SQL execution time was only about 20ms. There were no slow SQL statements at all.

My first reaction was that the connection pool was too small, so I directly changed SetMaxOpenConns from 40 to 200. After the change, it improved briefly, but not long after, the pool was exhausted again and the failure recurred.

This is a classic pitfall many Go backend developers will step into: a full connection pool ≠ insufficient connections. Blindly increasing MaxOpenConns only masks the problem, not solves it, and may even crush the database. Today I'll share this complete troubleshooting experience.

Environment: Go1.21 + database/sql + GORM + MySQL

First, understand: what does sql: waiting for connection actually mean?

In the Go standard library database/sql, when you call QueryContext / ExecContext, it first tries to get an idle connection from the pool. If all current connections are occupied and the MaxOpenConns limit has been reached, the request blocks and queues, waiting for other requests to return connections. After the queue times out, this error is thrown.

Many people mistakenly think that slow SQL execution causes connections to be held.

Key point: connection hold time ≠ SQL execution time! After a connection is checked out of the pool, it remains occupied until it is returned. Even if the SQL has finished, as long as rows is not closed or the transaction is not committed, the connection is still held.

The chain is like this:

Check out a connection from the pool → Execute SQL (fast, 20ms) → Business code loops to call downstream HTTP, assemble data → rows.Close() is not called / transaction not committed → connection not returned

SQL is fast, but the connection is occupied for a long time. New requests can't grab a connection, queue and time out.

The 3 most common error patterns in production that cause connections to be held and not returned

Pitfall 1: rows not closed in time, early return misses defer

Many beginners write queries with defer rows.Close(), but when code branches are complex, or they do IO inside the loop, the connection is occupied for a long time. Error code:

func (s *ConversationService) List(ctx context.Context, userID string) ([]Item, error) {
    // Execute query, get rows result set, connection is now occupied
    rows, err := s.db.QueryContext(ctx, `SELECT id, title FROM conversations WHERE user_id=?`, userID)
    if err != nil {
        return nil, err
    }
    // defer closes later, only executed when function exits
    defer rows.Close()

    var out []Item
    for rows.Next() { // Loop over result set, connection is held by rows
        var it Item
        if err := rows.Scan(&it.ID, &it.Title); err != nil {
            return nil, err
        }
        // Fatal mistake: calling external HTTP downstream while iterating rows
        // During downstream processing, the database connection is held and not released
        user, _ := s.users.Verify(ctx, userID)
        it.UserName = user.Name
        out = append(out, it)
    }
    return out, rows.Err()
}

Problem: calling downstream service inside the rows loop, the connection is bound to rows. If downstream is slow, the connection is held for a long time.

Correct approach: query all data first, read all rows, close the connection, then do downstream calls and data assembly.

Pitfall 2: External HTTP and cache operations inside transactions (long transactions)

Error code:

func (s *ConversationService) UpdateStatus(ctx context.Context, id uint64, userID string) error {
    // Start transaction, connection is bound to this transaction until Commit/Rollback
    tx, err := s.db.BeginTx(ctx, nil)
    if err != nil {
        return err
    }
    // defer rollback as a safety net, in case exception causes transaction to hang
    defer tx.Rollback()

    // Execute DB update inside transaction, this step is fast
    _, err = tx.ExecContext(ctx, `UPDATE conversations SET status=1 WHERE id=?`, id)
    if err != nil {
        return err
    }
    // Big taboo: calling HTTP notification inside transaction, the connection is locked by the transaction
    // If external service jitters or times out, it directly extends transaction hold time
    _, err = s.users.Notify(ctx, userID)
    _, err = tx.ExecContext(ctx, `INSERT INTO conversation_logs ...`)
    // Commit transaction, only then connection returns to pool
    err = tx.Commit()
    return err
}

Once a transaction starts, the connection is handed to it, and it won't return until Commit or Rollback. Mixing external IO inside a transaction turns it into a long transaction, and the connection is stuck.

Correct approach: transactions should only contain DB operations. Notifications and cache clearing should be placed after the transaction commits.

Pitfall 3: Not using Context, cancellation signal cannot propagate

Many old code uses db.Query() directly instead of QueryContext(ctx). When the client times out and disconnects, or gin request is canceled, the server doesn't sense it, SQL continues to run, and the connection is not released.

// Wrong: no ctx, after client cancels, query continues, connection not released
rows, err := db.Query("SELECT * FROM conversations WHERE user_id=?", userID)

Correct fix: shorten connection hold window

Repository layer (only DB queries, return connections as soon as possible)

// ListByUser queries conversation list by user ID
// repo layer responsibility: only database IO, release connection immediately after reading data, no downstream calls
func (r *ConversationRepo) ListByUser(ctx context.Context, userID string) ([]Conversation, error) {
    // QueryContext binds context, supports timeout and cancellation
    rows, err := r.db.QueryContext(ctx, `
        SELECT id, title, unread_count, pinned, last_message_at
        FROM conversations
        WHERE user_id = ? AND deleted_at IS NULL
        ORDER BY last_message_at DESC
        LIMIT 50`, userID)
    if err != nil {
        return nil, fmt.Errorf("list conversations: %w", err)
    }
    // Key: defer closes result set, as long as function exits, connection is released
    defer rows.Close()

    // Pre-allocate slice capacity to reduce memory growth
    out := make([]Conversation, 0, 50)
    // Loop to read all rows, load data into memory at once
    for rows.Next() {
        var c Conversation
        // Scan fields into struct
        if err := rows.Scan(&c.ID, &c.Title, &c.UnreadCount, &c.Pinned, &c.LastMessageAt); err != nil {
            return nil, fmt.Errorf("scan conversation: %w", err)
        }
        out = append(out, c)
    }
    // Check if any error occurred during iteration
    if err := rows.Err(); err != nil {
        return nil, fmt.Errorf("iterate conversations: %w", err)
    }
    return out, nil
}

Service layer: after getting data, do downstream orchestration

// List handles conversation list business logic
// service layer: after DB query completes and connection returns, do downstream calls and data assembly
func (s *ConversationService) List(ctx context.Context, userID string) ([]Item, error) {
    // Step 1: call repo to query DB, after reading data, connection has already returned to pool
    list, err := s.repo.ListByUser(ctx, userID)
    if err != nil {
        return nil, err
    }

    // Step 2: connection already released, now call downstream and assemble data
    // This IO does not occupy a DB connection
    user, err := s.users.Verify(ctx, userID)
    if err != nil {
        return nil, fmt.Errorf("verify user: %w", err)
    }

    items := make([]Item, 0, len(list))
    for _, c := range list {
        items = append(items, Item{
            ID:       c.ID,
            Title:    c.Title,
            UserName: user.Name,
        })
    }
    return items, nil
}

MySQL connection pool initialization (recommended config template)

// OpenMySQL initializes MySQL connection pool
func OpenMySQL(dsn string) (*sql.DB, error) {
    // Create db object, note: sql.Open doesn't establish connections, just initializes the pool structure
    db, err := sql.Open("mysql", dsn)
    if err != nil {
        return nil, err
    }
    // MaxOpenConns: maximum number of concurrent open connections, don't blindly increase
    // Cannot exceed MySQL instance's total connection quota, reserve connections for other services and background tasks
    db.SetMaxOpenConns(40)
    // MaxIdleConns: idle connections kept in the pool, reuse to reduce frequent connection creation overhead
    db.SetMaxIdleConns(10)
    // ConnMaxLifetime: maximum connection lifetime, auto-destroy after timeout, avoid database-side recycling old connection exceptions
    db.SetConnMaxLifetime(5 * time.Minute)
    // ConnMaxIdleTime: maximum idle time for idle connections, proactively close long-idle connections
    db.SetConnMaxIdleTime(2 * time.Minute)

    // Ping with timeout to verify connection availability, prevent invalid DSN
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()
    if err := db.PingContext(ctx); err != nil {
        _ = db.Close()
        return nil, fmt.Errorf("ping mysql failed: %w", err)
    }
    return db, nil
}

Parameter explanation:

How to monitor and locate? Key look at db.Stats()

Go's sql.DB has built-in statistics. In production, you can send these metrics to monitoring platforms (Prometheus).

// DBStats is the built-in statistics struct of database/sql
type Stats struct {
    OpenConnections int         // total connections currently in the pool
    InUse           int         // connections in use (checked out, not returned)
    Idle            int         // idle available connections
    WaitCount       int64       // cumulative number of times waiting for a connection, this metric is the core! Continuous growth means queuing
    WaitDuration    time.Duration // cumulative total time spent waiting for connections
}

Troubleshooting rules:

  1. WaitCount keeps growing, SQL is fast → connection return is slow, long transactions, rows leak
  2. Connection still occupied after client cancels → QueryContext not used to pass ctx
  3. Increasing MaxOpenConns brings temporary relief, but it blows up again after a while → there is a leak, capacity only masks the problem

Summary

  1. When sql: waiting for connection appears, first check connection hold time, not directly increase MaxOpenConns;
  2. Connections should only be held during SQL execution; rows must be closed, and external IO inside transactions is forbidden;
  3. All queries should use QueryContext / ExecContext to make the ctx cancellation chain work;
  4. Connection pool parameters are rate limiting protection, not performance accelerators; the bigger they are, the easier it is to crash MySQL;
  5. Report WaitCount in production; this metric is the core signal for discovering connection pool queuing ahead of time.

Regression test case (simple version)

// TestListByUserRespectsCancel tests that query fails quickly after context cancellation
func TestListByUserRespectsCancel(t *testing.T) {
    // Create an already canceled ctx to simulate client disconnecting early
    ctx, cancel := context.WithCancel(context.Background())
    cancel()
    // Execute query
    _, err := repo.ListByUser(ctx, "u1")
    // A canceled request should fail quickly, not block and occupy the connection
    if err == nil {
        t.Fatal("a canceled request should fail fast")
    }
}
Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

badhope

This article clearly separates the idea of a full connection pool from an insufficient number of connections. I fell into the same pit before, calling downstream services inside a rows loop, and later added two hard constraints: the Repository layer may only read from the database, no HTTP calls allowed; transactions contain only SQL, with all notifications and caching moved to after Commit. Also, rows.Err() and defer rows.Close() need to be handled together — only calling Close without checking iterator errors will still miss something. I'd like to ask: do you encode these constraints in static analysis now, or rely only on code review?