Running in production

Reconnects, errors that have no caller, ordering and broker limits.

Configure for a long-running service

client := mqtt.NewClient(
	mqtt.WithBroker(broker),
	mqtt.WithClientID("my-service"),
	// Without these, connection and subscription failures are not visible.
	mqtt.WithLogger(logger),
	mqtt.WithOnError(func(err error) { logger.Error("mqtt", "error", err) }),
	// Runs on the first connection and after every reconnect: republish state
	// here, in case the broker forgot its retained messages.
	mqtt.WithOnConnectionUp(republish),
	// The broker publishes this if the process dies without disconnecting.
	mqtt.WithWill(mqtt.Will{Topic: "my-service/availability", Payload: []byte("offline"), QoS: 1, Retain: true}),
)
err := client.Connect(ctx, nil)

WithOnConnectionUp runs on its own goroutine, so it may publish. It runs more than once, so make it safe to repeat.

The context given to Connect bounds only the dial. The connection then lasts until Close, so a cancelled context does not stop a device from reporting itself offline.

Errors with no caller

The library writes nothing to standard output. Without WithLogger its diagnostics are discarded.

  • A subscription the broker refuses is a *mqtt.SubscribeError. Subscribe returns it.
  • A failed re-subscribe after a reconnect goes to WithOnError, and client.Err() reports it until a later attempt succeeds. While it is set, the connection is up but some callbacks will not fire. Filters the broker refuses for good are dropped from the retry loop.
  • An error from a device's command callback, and a state change that does not decode, go to the same path.

Ordering and slow callbacks

Each MQTT subscription has one worker and a queue of 256 messages. A callback never races itself, and a slow one stalls only its own subscription. When the queue is full the oldest message is dropped and logged. Discovery has no queue and drops nothing: it runs on the receive path.

HTTP subscriptions and a dropped connection

Over HTTP, Subscribe uses one WebSocket shared by the client. If that connection drops, existing subscriptions stop and are not restored, and the callback is not told. The client opens a new connection only for the next Subscribe. Where that matters, use ConnectWebSocket directly, wait on conn.Done(), then reconnect, subscribe again and re-read the state. This is on the roadmap.

Last Will

A killed process cannot report itself offline. mqtt.WithWill asks the broker to publish for it. Retain the will, so Home Assistant sees it after a restart too. A client has one will, so if your program serves several devices, list a shared availability topic in each one's discovery config.

A device that sets ExpireAfter should report with mqtt.StateRetained(false). Otherwise the broker replays a state after it expired.

NATS as the MQTT broker

NATS's MQTT gateway speaks MQTT 3.1.1, so use mqtt.WithProtocolVersion(mqtt.V311). With its default max_ack_pending, one session holds about 63 plain QoS 1 subscriptions. NATS refuses the next one without an error that Home Assistant shows: the entity appears and never receives state. Client.WatchSubscriptionBudget warns before you get there. See NATS on how many messages can be in flight.