nats-io/nats-server · error

failed to write CONNECT request: %v

Error message

failed to write CONNECT request: %v

What it means

Writing the HTTP CONNECT request to the proxy connection failed. req.Write(conn) returned an error, meaning the socket was broken before/at the time the request was sent — the proxy accepted the TCP connection but the write could not complete.

Source

Thrown at server/leafnode.go:655

		conn.Close()
		return nil, fmt.Errorf("failed to set deadline: %v", err)
	}

	req := &http.Request{
		Method: http.MethodConnect,
		URL:    &url.URL{Opaque: targetHost}, // Opaque is required for CONNECT
		Host:   targetHost,
		Header: make(http.Header),
	}

	// Add proxy authentication if provided
	if username != "" && password != "" {
		req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":"+password)))
	}

	if err := req.Write(conn); err != nil {
		conn.Close()
		return nil, fmt.Errorf("failed to write CONNECT request: %v", err)
	}

	resp, err := http.ReadResponse(bufio.NewReader(conn), req)
	if err != nil {
		conn.Close()
		return nil, fmt.Errorf("failed to read proxy response: %v", err)
	}

	if resp.StatusCode != http.StatusOK {
		resp.Body.Close()
		conn.Close()
		return nil, fmt.Errorf("proxy CONNECT failed: %s", resp.Status)
	}

	// Close the response body
	resp.Body.Close()

	// Clear the deadline now that we've finished the proxy handshake

View on GitHub (pinned to 3a66a489d2)

Solutions

  1. Increase the proxy timeout so the deadline does not expire before the write
  2. Verify nothing between client and proxy strips or blocks HTTP CONNECT traffic
  3. Retry — transient resets often succeed on a second attempt
  4. Confirm the proxy actually speaks HTTP CONNECT on that port

Example fix

// before
proxy {
  url: "http://proxy:3128"
  timeout: 1s
}
// after
proxy {
  url: "http://proxy:3128"
  timeout: 15s
}
Defensive patterns

Strategy: retry

Try / catch

_, err := establishHTTPProxyTunnel(purl, target, timeout, user, pass)
if err != nil && strings.Contains(err.Error(), "failed to write CONNECT request") {
    log.Warnf("CONNECT write failed, retrying: %v", err)
    time.Sleep(backoff)
    // retry tunnel establishment
}

Prevention

When it happens

Trigger: conn write error during establishHTTPProxyTunnel after successful dial: peer reset the connection, buffer full because proxy is unresponsive, network dropped mid-write, or deadline already expired before write.

Common situations: Proxy with very small read timeouts closing early; middleboxes (IPS/load balancers) rejecting CONNECT; network flaps in container environments; handshake deadline too tight for slow links.

Related errors


AI-assisted analysis of nats-io/nats-server@3a66a489d2 (2026-09-02). Data as JSON: /api/errors/1b365db35807c461. Report an issue: GitHub.