In the previous article, I wrote an overview of NATS and NATS JetStream. Before we go deeper into advanced topics like scalability and reliability, it’s important to understand the most common messaging pattern in NATS: Publish–Subscribe.
What is Publish–Subscribe?
Publish–Subscribe (or pub/sub) is a way of sending messages where:
- Publishers send messages to a subject.
- Subscribers listen to that subject.
- Publishers don’t know who the subscribers are.
- Subscribers don’t know where the messages come from.
It’s a decoupled system: the publisher just fires a message, and anyone who is interested can subscribe and receive it.
Pub/Sub in NATS
In NATS, everything revolves around subjects. A subject is like a channel or a topic.
- A publisher publishes a message to a subject.
- A subscriber subscribes to that subject and receives the message in real time.
Example:
// Publisher nc.Publish("updates", []byte("Hello subscribers!")) // Subscriber nc.Subscribe("updates", func(msg *nats.Msg) { fmt.Printf("Received: %s\n", string(msg.Data)) })
When the publisher sends "Hello subscribers!"
, all subscribers of updates
will get that message instantly.
Using Wildcards
NATS subjects support wildcards, which makes pub/sub flexible.
*
matches one token.>
matches one or more tokens.
Example:
orders.*
→ matchesorders.created
,orders.paid
, but notorders.created.new
.orders.>
→ matches everything that starts withorders.
This is useful when you want to organize your events with patterns.
Real-World Examples
1. Order Processing
- Subjects:
orders.created
orders.shipped
- Services can subscribe only to the events they care about. For example, the shipping service subscribes to
orders.created
.
2. Chat Application
- Subject:
chat.room1
- Every user in room1 subscribes to
chat.room1
. - Messages are instantly broadcast to everyone in that room.
3. System Monitoring
- Subject:
metrics.cpu.usage
- Monitoring tools subscribe to all metrics using
metrics.>
. - This way, they receive all metrics without needing separate subscriptions for each one.