In the previous articles, we looked at Publish–Subscribe and Request–Reply patterns in NATS. Pub/Sub is great for broadcasting messages to many subscribers, while Request–Reply is perfect for one-to-one communication. But what if you want to distribute messages across a group of workers so that only one of them processes each message?
This is where Queue Groups come in.
What are Queue Groups?
A Queue Group is a way to make multiple subscribers share the work for the same subject. Instead of all subscribers getting every message, each message is delivered to only one member of the group.
- Publishers don’t need to know about the group.
- Subscribers just join the same queue group by giving it a name.
- NATS automatically balances the messages among them.
Example in Go
Publisher:
nc.Publish("jobs", []byte("process this task"))
Subscribers in a Queue Group:
// Worker A nc.QueueSubscribe("jobs", "workers", func(msg *nats.Msg) { fmt.Println("Worker A got:", string(msg.Data)) }) // Worker B nc.QueueSubscribe("jobs", "workers", func(msg *nats.Msg) { fmt.Println("Worker B got:", string(msg.Data)) })
If the publisher sends 10 messages to jobs
, NATS will spread them between Worker A and Worker B. Each message will only be delivered once to one worker.
Why Use Queue Groups?
- Load Balancing
- Multiple workers can share the load of incoming tasks.
- Example: background jobs, image processing, or notification sending.
- High Availability
- If one worker goes down, the others in the group continue processing.
- This reduces downtime and increases reliability.
- Horizontal Scaling
- You can add more subscribers to the queue group to handle higher traffic.
- No need to change publishers — they keep sending to the same subject.