go-sql-driver/mysql · error

invalid connection

Error message

invalid connection

What it means

ErrInvalidConn is a sentinel returned whenever a connection is deemed unusable. It is produced in readPacket (packets.go:59, :88, :101) when a network read fails or a malformed zero-length packet arrives, and in transaction.go/connection.go when operating on a connection that is already bad. The underlying I/O cause is logged via mc.log but NOT wrapped into the sentinel, so callers see only this generic error.

Source

Thrown at errors.go:20

//
// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

package mysql

import (
	"errors"
	"fmt"
	"log"
	"os"
)

// Various errors the driver might return. Can change between driver versions.
var (
	ErrInvalidConn       = errors.New("invalid connection")
	ErrMalformPkt        = errors.New("malformed packet")
	ErrNoTLS             = errors.New("TLS requested but server does not support TLS")
	ErrCleartextPassword = errors.New("this user requires clear text authentication. If you still want to use it, please add 'allowCleartextPasswords=1' to your DSN")
	ErrNativePassword    = errors.New("this user requires mysql native password authentication")
	ErrOldPassword       = errors.New("this user requires old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords")
	ErrUnknownPlugin     = errors.New("this authentication plugin is not supported")
	ErrOldProtocol       = errors.New("MySQL server does not support required protocol 41+")
	ErrPktSync           = errors.New("commands out of sync. You can't run this command now")
	ErrPktSyncMul        = errors.New("commands out of sync. Did you run multiple statements at once?")
	ErrPktTooLarge       = errors.New("packet for query is too large. Try adjusting the `Config.MaxAllowedPacket`")
	ErrBusyBuffer        = errors.New("busy buffer")

	// errBadConnNoWrite is used for connection errors where nothing was sent to the database yet.
	// If this happens first in a function starting a database interaction, it should be replaced by driver.ErrBadConn
	// to trigger a resend. Use mc.markBadConn(err) to do this.
	// See https://github.com/go-sql-driver/mysql/pull/302
	errBadConnNoWrite = errors.New("bad connection")
)

View on GitHub (pinned to c426bd9379)

Solutions

  1. Configure the connection pool to recycle connections before the server/network does: db.SetConnMaxLifetime(...) shorter than the server's wait_timeout, and set db.SetMaxIdleConns / SetMaxOpenConns appropriately.
  2. Retry idempotent operations; database/sql will retry on driver.ErrBadConn, so ensure you are not catching the error and suppressing the retry.
  3. Verify the MySQL server is reachable and not OOM-killed / restarting; check network stability between client and host.

Example fix

// before
db.SetConnMaxLifetime(0) // connections live forever, server kills them
// after
db.SetConnMaxLifetime(5 * time.Minute) // recycle before server wait_timeout
db.SetMaxIdleConns(10)
Defensive patterns

Strategy: retry

Validate before calling

db.SetConnMaxLifetime(min(serverWaitTimeout, 5*time.Minute))
db.SetMaxIdleConns(8)

Type guard

func isBadConn(err error) bool { return errors.Is(err, mysql.ErrInvalidConn) }

Try / catch

var lastErr error
for attempt := 0; attempt < 3; attempt++ {
    err := fn()
    if err == nil { return nil }
    if !errors.Is(err, mysql.ErrInvalidConn) { return err }
    lastErr = err
}
return lastErr

Prevention

When it happens

Trigger: Any read on a connection whose TCP socket is broken: the header read at packets.go:52 fails, or the body read at packets.go:94 fails, or a zero-length packet arrives without prior data (packets.go:83-88). Also returned by Begin/Commit/Rollback on a connection whose mc.bad flag is set (transaction.go:17,33), and by Ping (connection.go:202).

Common situations: MySQL server or a load balancer (e.g. AWS RDS proxy, ProxySQL) closed an idle connection; network partition; server restart; exceeding wait_timeout; firewall dropping long-lived connections.

Related errors


AI-assisted analysis of go-sql-driver/mysql@c426bd9379 (2026-08-04). Data as JSON: /data/errors/971c60aee1b56f67.json. Report an issue: GitHub.