micro/go-micro · critical

Failed to connect to NATS Server

Error message

Failed to connect to NATS Server

What it means

natsStore.Init connects to the NATS servers via n.nopts.Connect() before obtaining a JetStream context; if the NATS connection cannot be established the store fails initialization with this message. The wrapped cause contains the NATS-specific reason (no servers, auth, TLS).

Source

Thrown at store/nats-js-kv/nats.go:79

		buckets:     hashmap.New[string, nats.KeyValue](),
		storageType: nats.FileStorage,
	}

	n.setOption(opts...)

	return n
}

// Init initializes the store. It must perform any required setup on the
// backing storage implementation and check that it is ready for use,
// returning any errors.
func (n *natsStore) Init(opts ...store.Option) error {
	n.setOption(opts...)

	// Connect to NATS servers
	conn, err := n.nopts.Connect()
	if err != nil {
		return errors.Wrap(err, "Failed to connect to NATS Server")
	}

	// Create JetStream context
	js, err := conn.JetStream(n.jsopts...)
	if err != nil {
		return errors.Wrap(err, "Failed to create JetStream context")
	}

	n.conn = conn
	n.js = js

	// Create default config if no configs present
	if len(n.kvConfigs) == 0 {
		if _, err := n.mustGetBucketByName(n.opts.Database); err != nil {
			return err
		}
	}

View on GitHub (pinned to 24529f1404)

Solutions

  1. Verify NATS server is running and reachable (nats -s <url> server check or nc to 4222)
  2. Fix the NATS connection options: URLs, credentials, TLS settings passed via store/nats options
  3. Confirm credentials/token are valid and not expired
  4. If connect fails intermittently, enable/rely on NATS reconnect and retry Init

Example fix

// before
s := natsjs.NewStore(store.Nodes("nats://wrong:4222"))
// after
s := natsjs.NewStore(store.Nodes("nats://nats:4222"))
s.Init(store.Namespace("micro"))
Defensive patterns

Strategy: try-catch

Validate before calling

// check NATS reachability before Init
conn, err := nats.Connect("nats://nats:4222", nats.Timeout(2*time.Second))
if err != nil {
    return fmt.Errorf("nats unreachable: %w", err)
}
conn.Close()

Try / catch

if err := st.Init(opts...); err != nil {
    if strings.Contains(err.Error(), "Failed to connect to NATS Server") {
        log.Printf("nats connect failed: %+v", err)
        time.Sleep(backoff)
        return st.Init(opts...)
    }
    return err
}

Prevention

When it happens

Trigger: store.Init(...) on the NATS JetStream KV store when no NATS server is reachable at the configured URLs, credentials are rejected, TLS handshake fails, or connection timeouts are hit.

Common situations: NATS server not running or wrong URL in NATS_URL; credentials/token expired; TLS certificate mismatch; network policy blocking port 4222; JetStream not enabled on the server (affects the next step).

Related errors


AI-assisted analysis of micro/go-micro@24529f1404 (2026-09-01). Data as JSON: /api/errors/0e145e32630ea550. Report an issue: GitHub.