jackc/pgx · error

invalid message length

Error message

invalid message length: %d

What it means

The frontend received a backend message whose declared length is less than 4 bytes, which is impossible for a valid message. The %d shows the malformed length; the stream cannot be trusted beyond this point.

Solutions

  1. Verify server compatibility — is this actually PostgreSQL?
  2. Check for connection corruption or a proxy mangling the stream
  3. Reconnect and retry the query
  4. Capture traffic with tcpdump or a tracing proxy to inspect the bytes
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at pgproto3/frontend.go:322 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/bb0b5b0b61f12c6e. Report an issue: GitHub.

Appendix: source

Thrown at pgproto3/frontend.go:322

	if err == io.EOF {
		return io.ErrUnexpectedEOF
	}
	return err
}

// Receive receives a message from the backend. The returned message is only valid until the next call to Receive.
func (f *Frontend) Receive() (BackendMessage, error) {
	if !f.partialMsg {
		header, err := f.cr.Next(5)
		if err != nil {
			return nil, translateEOFtoErrUnexpectedEOF(err)
		}

		f.msgType = header[0]

		msgLength := int(int32(binary.BigEndian.Uint32(header[1:])))
		if msgLength < 4 {
			return nil, fmt.Errorf("invalid message length: %d", msgLength)
		}

		f.bodyLen = msgLength - 4
		if f.maxBodyLen > 0 && f.bodyLen > f.maxBodyLen {
			return nil, &ExceededMaxBodyLenErr{f.maxBodyLen, f.bodyLen}
		}
		f.partialMsg = true
	}

	msgBody, err := f.cr.Next(f.bodyLen)
	if err != nil {
		return nil, translateEOFtoErrUnexpectedEOF(err)
	}

	f.partialMsg = false

	var msg BackendMessage
	switch f.msgType {

View on GitHub (pinned to ec1a0befd2)