Pub/Sub Messaging with NATS CLI
Beginnerv1.0.0
Implement publish/subscribe messaging with the NATS CLI — subject hierarchies, wildcards, queue groups, request/reply patterns, and building event-driven communication between services.
Content
Overview
NATS pub/sub is the foundation of event-driven architectures. Publishers send messages to subjects, subscribers receive them — with wildcards for flexible routing and queue groups for load balancing.
Why This Matters
- -Decoupling — services communicate without knowing each other
- -Scalability — add subscribers without changing publishers
- -Routing — wildcard subjects enable flexible message routing
- -Load balancing — queue groups distribute work across consumers
How It Works
Step 1: Basic Publish & Subscribe
Step 2: Subject Hierarchies & Wildcards
Step 3: Queue Groups
Step 4: Request/Reply
Best Practices
- -Use dot-separated subject hierarchies: service.entity.action
- -Use wildcards in subscribers, never in publishers
- -Use queue groups for work distribution (not fan-out)
- -Set --timeout on requests to avoid indefinite blocking
- -Monitor subject usage with nats sub for debugging
Common Mistakes
- -Publishing to wildcard subjects (wildcards are for subscribing only)
- -Not using queue groups when multiple instances handle the same work
- -Overly broad subscriptions (processing irrelevant messages)
- -No timeout on request/reply (blocks forever if no responder)
- -Flat subject names instead of hierarchies (no wildcard flexibility)
FAQ
Discussion
Loading comments...