benbjohnson/litestream · error

failed to connect to NATS server: %w

Error message

failed to connect to NATS server: %w

What it means

The internal connect() method calls nats.Connect with the configured URL and client options; this error wraps any connection failure. Unlike error 362, this is the innermost cause — it surfaces the NATS client library's own reason (refused, timeout, auth, TLS).

Source

Thrown at nats/replica_client.go:159

	}

	if err := c.initObjectStore(ctx); err != nil {
		return fmt.Errorf("nats: failed to initialize object store: %w", err)
	}

	return nil
}

// connect establishes a connection to NATS server with proper configuration.
func (c *ReplicaClient) connect(_ context.Context) error {
	url := c.URL
	if url == "" {
		url = nats.DefaultURL
	}

	nc, err := nats.Connect(url, c.options()...)
	if err != nil {
		return fmt.Errorf("failed to connect to NATS server: %w", err)
	}

	js, err := jetstream.New(nc)
	if err != nil {
		nc.Close()
		return fmt.Errorf("failed to create JetStream context: %w", err)
	}

	c.nc = nc
	c.js = js
	return nil
}

func (c *ReplicaClient) options() []nats.Option {
	opts := []nats.Option{
		nats.MaxReconnects(c.MaxReconnects),
		nats.ReconnectWait(c.ReconnectWait),
		nats.ReconnectJitter(c.ReconnectJitter, c.ReconnectJitter*2),

View on GitHub (pinned to 4ed7a308f6)

Solutions

  1. Test connectivity first: `nc -zv host 4222` or `nats -s <url> server info`
  2. Confirm the URL scheme/port (nats:// vs tls://, default port 4222)
  3. Supply required credentials in the URL or client options
  4. Inspect the inner %w error for auth/TLS specifics and fix accordingly

Example fix

# before (monitoring port instead of client port)
url: "nats://host:8222/backups"
# after
url: "nats://host:4222/backups"
Defensive patterns

Strategy: try-catch

Validate before calling

u, _ := url.Parse(strings.TrimPrefix(replicaURL, "nats://"))
hp := net.JoinHostPort(u.Hostname(), u.Port() or "4222")
if c, err := net.DialTimeout("tcp", hp, 3*time.Second); err != nil {
	return fmt.Errorf("cannot reach NATS at %s: %w", hp, err)
} else { c.Close() }

Try / catch

if err := client.Init(ctx); err != nil {
	if strings.Contains(err.Error(), "failed to connect to NATS server") {
		// inspect wrapped cause: timeouts, auth violations, TLS errors
		return retry.WithBackoff(ctx, client.Init) // transient outages
	}
	return err
}

Prevention

When it happens

Trigger: nats.Connect(url, c.options()...) returns an error during connect() (reached via Init): no listener at the URL, connection timeout, auth violation, or TLS handshake failure.

Common situations: NATS not running on the configured host/port; wrong port (4222 vs 8222 monitoring port); credentials missing/rotated; TLS required by server but client options lack certs; DNS failure in containers.

Understand the failure class

Background: ECONNREFUSED and "connection refused" / "could not connect to server" errors: what they mean and how to fix them — this error's family across 44 libraries.

Related errors


AI-assisted analysis of benbjohnson/litestream@4ed7a308f6 (2026-09-06). Data as JSON: /api/errors/3309c9e1659d5054. Report an issue: GitHub.