Skip to content

Connecting Go services to NATS and JetStream

Connect a Go service to NATS with reconnect handling, JetStream pull consumers, durable subscriptions, ack/nak semantics, and graceful shutdown.

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

  1. 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. Name shows up in nats server report connz — invaluable for debugging which client is misbehaving.

  2. 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 of Close().

  3. 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 }

    WorkQueuePolicy deletes messages once a single consumer group acks them — the queue semantics you want for jobs. Use LimitsPolicy instead for fan-out streams.

  4. 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()

    Consume returns a ConsumeContext — calling Stop() finishes pending acks and stops fetching. This is the right plumbing for graceful shutdown.

  5. 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)

    WithMsgID lets the broker dedupe on the message-ID within a configurable window (Duplicates field on the stream). The same publish twice produces one stored message.

  6. 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 close

    Drain blocks until everything is flushed. Set nats.DrainTimeout(15 * time.Second) for an upper bound.

  7. 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()))

    NumPending is the lag of your consumer group — alert on it growing without bound.

Common pitfalls

  • Forgetting Ack() or Nak() leaks redelivery. Unacknowledged messages re-deliver after AckWait, leading to “double processing” complaints. Always either ack or nak.
  • Close() instead of Drain() drops in-flight publishes. Drain is asynchronous-but-complete; Close is immediate.
  • MaxDeliver defaults 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’s MaxDeliver config.
  • Multiple consumers with the same Durable share work. That is the intended fan-out behavior; remove Durable or use a unique name if you want per-instance subscriptions.
  • nats.Connect with no creds against a server that requires them fails silently with authorization 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.