NATS is the fastest message bus we run for clients who want a thin, fast, in-process or sidecar broker. The Go client (nats.go) is the reference implementation and supports both core NATS (fire-and-forget pub/sub) and JetStream (persistent streams with replay). This article shows the NATS Go client pattern Stack Harbor uses on production services.
How to verify
After connecting, publish a message and consume it with a pull consumer:
go get github.com/nats-io/nats.go
nats-server -js # or via the official nats Docker image
go run ./cmd/producer &
go run ./cmd/consumer
nats stream ls
nats consumer info ORDERS workers
nats stream ls and nats consumer info come from the nats CLI — they give you durable view of what your Go client created.
What’s happening
NATS has two layers. Core NATS is fire-and-forget pub/sub on subjects (hierarchical strings like orders.created, users.42.events). No persistence — a subscriber that is not running when a message is published does not see it. JetStream layers persistence on top: a stream subscribes to subjects, stores messages on disk, and lets consumers pull them with acknowledgement semantics (Ack, Nak, Term, InProgress).
The Go client maintains a single TCP connection that does all pub/sub. Reconnect, backoff, and disconnect events fire as configurable callbacks. JetStream operations go through the same connection via the jetstream.JetStream interface — a js.Stream, js.Consumer, and js.Publish API that wraps the request/reply RPC under the hood.
Consumers come in two shapes. Push consumers stream messages to a callback as they arrive — easy but you cannot pause cleanly. Pull consumers are the production default: Fetch(N) requests up to N messages, you process them, ack each, and loop. Pull consumers play nicely with worker pools and graceful shutdown.
The procedure
-
Connect with reconnect handling.
package main import ( "log/slog" "time" "github.com/nats-io/nats.go" ) func connect(log *slog.Logger) (*nats.Conn, error) { nc, err := nats.Connect("nats://nats.internal:4222", nats.Name("billing-worker"), nats.UserInfo("worker", "CHANGEME"), nats.MaxReconnects(-1), nats.ReconnectWait(2*time.Second), nats.ReconnectJitter(500*time.Millisecond, time.Second), nats.PingInterval(20*time.Second), nats.MaxPingsOutstanding(2), nats.DisconnectErrHandler(func(_ *nats.Conn, err error) { log.Warn("nats disconnected", "err", err) }), nats.ReconnectHandler(func(c *nats.Conn) { log.Info("nats reconnected", "url", c.ConnectedUrl()) }), nats.ClosedHandler(func(c *nats.Conn) { log.Info("nats closed", "err", c.LastError()) }), ) return nc, err }MaxReconnects(-1)retries forever.Nameshows up innats server report connz— invaluable for debugging which client is misbehaving. -
Core NATS publish/subscribe.
nc, _ := connect(log) defer nc.Drain() sub, _ := nc.Subscribe("orders.created", func(m *nats.Msg) { handleOrderCreated(m.Data) }) defer sub.Unsubscribe() nc.Publish("orders.created", payload)nc.Drain()is the graceful-shutdown call — it flushes pending publishes, unsubscribes, then closes the connection. Use it instead ofClose(). -
Create a JetStream and a consumer.
import "github.com/nats-io/nats.go/jetstream" js, _ := jetstream.New(nc) stream, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{ Name: "ORDERS", Subjects: []string{"orders.>"}, Storage: jetstream.FileStorage, Retention: jetstream.WorkQueuePolicy, Replicas: 3, }) if err != nil { return err } cons, err := stream.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{ Name: "workers", Durable: "workers", AckPolicy: jetstream.AckExplicitPolicy, AckWait: 30 * time.Second, MaxDeliver: 5, FilterSubject: "orders.created", }) if err != nil { return err }WorkQueuePolicydeletes messages once a single consumer group acks them — the queue semantics you want for jobs. UseLimitsPolicyinstead for fan-out streams. -
Pull consumer loop with backpressure.
cc, err := cons.Consume(func(msg jetstream.Msg) { ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second) defer cancel() if err := process(ctx, msg.Data()); err != nil { log.Error("process failed", "err", err) msg.Nak() return } msg.Ack() }) if err != nil { return err } defer cc.Stop()Consumereturns aConsumeContext— callingStop()finishes pending acks and stops fetching. This is the right plumbing for graceful shutdown. -
Publish with confirmation.
ack, err := js.Publish(ctx, "orders.created", payload, jetstream.WithExpectStream("ORDERS"), jetstream.WithMsgID(orderID), // idempotent publish dedup ) if err != nil { return err } log.Info("published", "stream", ack.Stream, "seq", ack.Sequence)WithMsgIDlets the broker dedupe on the message-ID within a configurable window (Duplicatesfield on the stream). The same publish twice produces one stored message. -
Graceful shutdown. Wire NATS into your signal-context plumbing:
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() <-ctx.Done() cc.Stop() // stop fetching new messages _ = nc.Drain() // flush pending publishes, then closeDrainblocks until everything is flushed. Setnats.DrainTimeout(15 * time.Second)for an upper bound. -
Observability. Export consumer lag and connection state as Prometheus gauges:
ci, _ := cons.Info(ctx) pending.Set(float64(ci.NumPending)) ackPending.Set(float64(ci.NumAckPending)) connRTT.Set(float64(nc.RTT().Milliseconds()))NumPendingis the lag of your consumer group — alert on it growing without bound.
Common pitfalls
- Forgetting
Ack()orNak()leaks redelivery. Unacknowledged messages re-deliver afterAckWait, leading to “double processing” complaints. Always either ack or nak. Close()instead ofDrain()drops in-flight publishes. Drain is asynchronous-but-complete; Close is immediate.MaxDeliverdefaults to unlimited. A bad payload that always fails will redeliver forever — set a finite value (typically 5-10) and route exhausted messages to a dead-letter subject via the consumer’sMaxDeliverconfig.- Multiple consumers with the same
Durableshare work. That is the intended fan-out behavior; removeDurableor use a unique name if you want per-instance subscriptions. nats.Connectwith no creds against a server that requires them fails silently withauthorization violation. Read the connection error before assuming the network is broken.
Stack Harbor runs NATS/JetStream as the lightweight bus alternative to Kafka for clients with throughput needs measured in thousands-per-second instead of millions-per-second. See how that fits into our managed operations practice for messaging-heavy Go services.