Go NATS Messaging: Publish, Subscribe and Request

Updated 8 min read
Go NATS featured image: cards for publish, queue groups and request reply

Go NATS gives your services a fast, simple way to send messages to each other without calling each other directly. In this post, you will learn the three core NATS patterns: publish and subscribe, queue groups, and request and reply. Then we will build an order system where one event reaches several services at once.

In the last two lessons, our chat hub and SSE broker lived inside one Go process. So they could not share messages across servers. That is exactly the gap a message system fills. For a refresher on goroutines, see Go goroutines explained for beginners. Also, for clean exits, see Go graceful shutdown.

What Is Go NATS?

NATS is an open source messaging server, and nats.go is its official Go client. A service publishes a message to a named topic, called a subject. Then every service that subscribed to that subject receives a copy.

For example, think of a group announcement on a school notice board. The teacher pins one notice, and every student who checks the board sees it. Also, the teacher does not need to know who is reading. Similarly, a publisher in Go NATS never needs to know who the subscribers are.

The NATS server is a single small binary. As a result, you can run it on your laptop in seconds and in production on a few small machines.

Why Go NATS Matters

When services call each other directly over HTTP, they become tightly linked. If the email service is down, the order service fails too. However, with a message system in the middle, each service only talks to NATS.

Here are common reasons teams add Go NATS to a backend.

  • Fan-out events: one “order created” event goes to the email, invoice and analytics services together.
  • Load sharing: three copies of a worker split the jobs between them automatically.
  • Fast internal calls: request and reply over NATS replaces many small HTTP calls.
  • Scaling real-time apps: chat or SSE servers share live messages through one subject.
  • Loose coupling: you can add a new subscriber later without changing the publisher.

In short, Go NATS lets services react to events instead of waiting on each other.

How Go NATS Works

First, every service opens one long-lived TCP connection to the NATS server. Next, subscribers tell the server which subjects they care about. Then, when a publisher sends a message, the server forwards it to every matching subscriber. Finally, each client library calls your handler function in its own goroutine.

Go NATS diagram showing one published order event delivered to three subscribed services
An order service publishes one message on orders.created, and the NATS server delivers a copy to every subscribed service.

By default, core NATS is “fire and forget”. So if no one is listening at that moment, the message is simply dropped. For messages you must never lose, NATS adds a storage layer called JetStream. We look at it later in this post.

Key Parts of Go NATS

In practice, a few building blocks cover almost everything you will do with Go NATS. So once you know them, most NATS code reads easily.

Subjects and Wildcards

A subject is a string made of tokens separated by dots, such as orders.created. Also, subscribers can use two wildcards. This table shows how they match.

Subject patternMatchesDoes not match
orders.createdorders.created onlyorders.paid
orders.*orders.created, orders.paidorders.eu.created
orders.>orders.created, orders.eu.createdpayments.created

In other words, * matches exactly one token, while > matches one or more tokens at the end.

Publish and Subscribe

nc.Publish(subject, data) sends bytes to a subject. Meanwhile, nc.Subscribe(subject, handler) registers a function that runs for every message on that subject.

Queue Groups

When several subscribers join the same queue group, NATS delivers each message to only one of them. So you get automatic load balancing without a separate load balancer.

Request and Reply

nc.Request publishes a message and waits for one answer. On the other side, the responder calls m.Respond. In fact, this works like an HTTP call, but through NATS.

Core NATS vs JetStream

NATS comes in two layers. The table below compares them so you can pick the right one.

FeatureCore NATSJetStream
StorageNone, memory onlyMessages saved to disk
Missed messagesLost if no one listensKept until read
DeliveryAt most onceAt least once, with acks
SpeedFastestSlightly slower
SetupNothing extraCreate a stream first
Good forLive updates, requestsOrders, payments, jobs
Go NATS diagram showing a queue group sharing six orders between three workers
With a queue group, NATS gives each message to only one worker, so three workers share the load.

So when should you use which? Use core NATS for live data where a missed message does not hurt. On the other hand, use JetStream when every message must be processed, such as an order or a payment.

Hands-On: An Order System with Go NATS

Let’s build a small Go NATS system. First, an order service publishes events. Then an email service and an analytics service both receive them. Finally, an inventory service answers stock questions.

Step 1: Run the NATS Server

The quickest way is Docker. Alternatively, download the nats-server binary for your system and run it directly.

docker run -d --name nats -p 4222:4222 nats:latest -js

The -js flag turns on JetStream. Then add the Go client to your module.

go get github.com/nats-io/nats.go

Step 2: Publish and Subscribe

This program starts two subscribers on the same subject and then publishes one order event.

func main() {
	nc, err := nats.Connect(nats.DefaultURL)
	if err != nil {
		log.Fatal(err)
	}
	defer nc.Drain()

	// Two different services listen to the same subject.
	nc.Subscribe("orders.created", func(m *nats.Msg) {
		fmt.Printf("email service got: %s\n", m.Data)
	})
	nc.Subscribe("orders.*", func(m *nats.Msg) {
		fmt.Printf("analytics got %s: %s\n", m.Subject, m.Data)
	})

	// The order service publishes one event.
	order := []byte(`{"id":1042,"total":499}`)
	if err := nc.Publish("orders.created", order); err != nil {
		log.Fatal(err)
	}
	nc.Flush()
	time.Sleep(100 * time.Millisecond) // give handlers time to print
}

Here, nats.DefaultURL is nats://127.0.0.1:4222. Also, Flush waits until the server has received everything we sent. Finally, Drain lets pending messages finish before the connection closes, which is the clean way to shut down.

Both subscribers receive the same event, so the output looks like this. The two lines may appear in either order, because each handler runs separately.

email service got: {"id":1042,"total":499}
analytics got orders.created: {"id":1042,"total":499}

Step 3: Share Work with a Queue Group

Now imagine three copies of the email service. We want each email sent only once.

for i := 1; i <= 3; i++ {
	worker := i
	nc.QueueSubscribe("orders.created", "emailers", func(m *nats.Msg) {
		fmt.Printf("worker %d sends email for %s\n", worker, m.Data)
	})
}
for id := 1; id <= 6; id++ {
	nc.Publish("orders.created", []byte(fmt.Sprintf("order-%d", id)))
}
nc.Flush()

All three workers join the queue group emailers. As a result, each of the six orders goes to exactly one worker. The split is random, so you might see worker 2 handle three orders while worker 3 handles one.

Step 4: Request and Reply

Finally, the inventory service answers questions. The order service asks and waits up to two seconds.

// Inventory service: answers stock questions.
nc.Subscribe("inventory.check", func(m *nats.Msg) {
	m.Respond([]byte("in stock: " + string(m.Data)))
})

// Order service: asks and waits for the answer.
reply, err := nc.Request("inventory.check", []byte("book-7"), 2*time.Second)
if err != nil {
	log.Fatal(err)
}
fmt.Println("reply:", string(reply.Data))

With the responder running, the program prints one line.

reply: in stock: book-7

However, if no service listens on inventory.check, the request fails at once with nats: no responders available for request. And if a responder exists but is too slow, you get nats: timeout instead.

Step 5: Keep Go NATS Messages with JetStream

For orders, losing a message is not acceptable. So we store them in a JetStream stream. The newer jetstream package inside nats.go makes this short.

js, err := jetstream.New(nc)
if err != nil {
	log.Fatal(err)
}
ctx := context.Background()

// A stream stores every message on orders.> subjects.
_, err = js.CreateStream(ctx, jetstream.StreamConfig{
	Name:     "ORDERS",
	Subjects: []string{"orders.>"},
})
if err != nil {
	log.Fatal(err)
}

ack, err := js.Publish(ctx, "orders.created", []byte(`{"id":1042}`))
if err != nil {
	log.Fatal(err)
}
fmt.Println("stored in", ack.Stream, "at sequence", ack.Sequence)

Unlike core Publish, this call waits for the server to confirm that the message is saved. So ack.Sequence tells you its position in the stream. On a fresh stream, the first message gets sequence 1, and the program prints stored in ORDERS at sequence 1.

To read from the stream, a service creates a durable consumer and acknowledges each message after it finishes the work. As a result, if the service crashes halfway, Go NATS JetStream delivers the message again later.

Common Mistakes with Go NATS

  • Exiting before messages arrive: main returns and handlers never run. So call Flush and keep the program alive, or use Drain on shutdown.
  • Expecting core NATS to store messages: messages sent while a service is down are lost. Use JetStream for anything important.
  • Forgetting queue groups: three worker copies each send the same email three times. Use QueueSubscribe with a shared group name.
  • Slow handlers: a long handler delays later messages on that subscription. Instead, hand heavy work to a worker pool.
  • No timeout on requests: a missing responder can block your flow. Always pass a sensible timeout to Request.

Best Practices for Go NATS

  • Name subjects like paths, such as orders.eu.created, because wildcards then work nicely.
  • Send JSON or protobuf payloads, so every language can read them.
  • Use one connection per process, since a single NATS connection handles many subscriptions.
  • Drain on shutdown, as it finishes in-flight messages before closing.
  • Pick JetStream for business events, because acks and storage protect against lost messages.

Practice Task

Connect this to the SSE tracker from the previous post. Subscribe to orders.* in the SSE server and pass every NATS message to broker.publish. Then run two SSE servers and check that both browsers receive every update.

Hint: subscribe once at startup, outside the HTTP handlers.

Official Resources

These pages cover the client API and the server features in detail.

Quick Recap

  • Go NATS sends messages between services through a NATS server.
  • Subjects use dots, and * and > act as wildcards.
  • Plain subscribers each get a copy, while a queue group shares the work.
  • Request and Respond give you request and reply with a timeout.
  • Core NATS is fire and forget, and JetStream adds storage and acks.
  • Call Drain on shutdown so pending messages are not lost.

What’s Next?

Messages move data between services. However, most services also need to store it, so we will add a database next. Next, we will connect Go to PostgreSQL using the pgx driver.

Next lesson: Go PostgreSQL with pgx: A Practical Guide