jackc/pgx · error

Bad startup message last byte. Expected 0, got

Error message

Bad startup message last byte. Expected 0, got %d

What it means

While parsing the startup message's null-terminated parameter list, the final remaining byte was expected to be the terminating NUL but was not. The %d shows the actual byte value, indicating a malformed parameter block.

Solutions

  1. Ensure all parameter strings are NUL-terminated
  2. Add the final NUL terminator byte after the last key/value pair
  3. Use pgproto3's StartupMessage.Encode which handles termination
  4. Check for off-by-one errors in manual packet construction
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at pgproto3/startup_message.go:62 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/45c1a1ef6a2a122f. Report an issue: GitHub.

Appendix: source

Thrown at pgproto3/startup_message.go:62

		idx := bytes.IndexByte(src[rp:], 0)
		if idx < 0 {
			return &invalidMessageFormatErr{messageType: "StartupMessage"}
		}
		key := string(src[rp : rp+idx])
		rp += idx + 1

		idx = bytes.IndexByte(src[rp:], 0)
		if idx < 0 {
			return &invalidMessageFormatErr{messageType: "StartupMessage"}
		}
		value := string(src[rp : rp+idx])
		rp += idx + 1

		dst.Parameters[key] = value

		if len(src[rp:]) == 1 {
			if src[rp] != 0 {
				return fmt.Errorf("Bad startup message last byte. Expected 0, got %d", src[rp])
			}
			break
		}
	}

	return nil
}

// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length.
func (src *StartupMessage) Encode(dst []byte) ([]byte, error) {
	sp := len(dst)
	dst = pgio.AppendInt32(dst, -1)

	dst = pgio.AppendUint32(dst, src.ProtocolVersion)
	for k, v := range src.Parameters {
		dst = append(dst, k...)
		dst = append(dst, 0)
		dst = append(dst, v...)

View on GitHub (pinned to ec1a0befd2)