jackc/pgx · error

SyncConn: Ping failed while syncing conn

Error message

SyncConn: Ping failed while syncing conn: %w

What it means

SyncConn needed to drain the connection's state before handing the raw net.Conn to the caller, which required a Ping, and that Ping failed. The connection's readiness for direct use could not be confirmed.

Solutions

  1. Check the wrapped Ping error for the underlying cause
  2. Verify the connection is still alive before calling SyncConn
  3. Retry SyncConn if the failure was transient
  4. Ensure no concurrent operations are using the connection
Defensive patterns

Strategy: try-catch

When it happens

Trigger: Thrown at pgconn/pgconn.go:2163 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of jackc/pgx@ec1a0befd2 (2026-08-04). Data as JSON: /api/errors/5334259253c7961a. Report an issue: GitHub.

Appendix: source

Thrown at pgconn/pgconn.go:2163

	return err
}

// SyncConn prepares the underlying net.Conn for direct use. PgConn may internally buffer reads or use goroutines for
// background IO. This means that any direct use of the underlying net.Conn may be corrupted if a read is already
// buffered or a read is in progress. SyncConn drains read buffers and stops background IO. In some cases this may
// require sending a ping to the server. ctx can be used to cancel this operation. This should be called before any
// operation that will use the underlying net.Conn directly. e.g. Before Conn() or Hijack().
//
// This should not be confused with the PostgreSQL protocol Sync message.
func (pgConn *PgConn) SyncConn(ctx context.Context) error {
	for range 10 {
		if pgConn.bgReader.Status() == bgreader.StatusStopped && pgConn.frontend.ReadBufferLen() == 0 {
			return nil
		}

		err := pgConn.Ping(ctx)
		if err != nil {
			return fmt.Errorf("SyncConn: Ping failed while syncing conn: %w", err)
		}
	}

	// This should never happen. Only way I can imagine this occurring is if the server is constantly sending data such as
	// LISTEN/NOTIFY or log notifications such that we never can get an empty buffer.
	return errors.New("SyncConn: conn never synchronized")
}

// CustomData returns a map that can be used to associate custom data with the connection.
func (pgConn *PgConn) CustomData() map[string]any {
	return pgConn.customData
}

// HijackedConn is the result of hijacking a connection.
//
// Due to the necessary exposure of internal implementation details, it is not covered by the semantic versioning
// compatibility.
type HijackedConn struct {

View on GitHub (pinned to ec1a0befd2)