Pub/Sub vs Request–Reply
Feature | Publish–Subscribe | Request–Reply |
---|---|---|
Communication style | One-to-many | One-to-one |
Response expected | No | Yes |
Persistence | Only with JetStream | Optional JetStream, but usually real-time |
Typical use cases | Events, notifications | Queries, RPC, commands |
Request–Reply vs HTTP Call
At first glance, Request–Reply in NATS looks very similar to making an HTTP request. Both involve a client sending a message and waiting for a response. But there are some clear differences:
Aspect | NATS Request–Reply | HTTP Call |
---|---|---|
Transport | Uses NATS protocol over TCP (lightweight) | Uses HTTP/HTTPS over TCP (heavier) |
Latency | Very low, designed for microseconds | Higher, includes HTTP headers and parsing |
Connection | Multiplexed over a single NATS connection | Often opens/closes TCP connections |
Routing | Based on subjects (flexible patterns) | Based on URLs and endpoints |
Discovery | Implicit — services just subscribe to a subject | Explicit — clients must know exact URL |
Scaling | Easy, multiple subscribers can share the load | Usually needs a load balancer or service mesh |
Persistence | Works with JetStream if needed | Usually requires external database or logs |
Use cases | Fast RPC between microservices, health checks, IoT commands | Web APIs, browser-to-server communication |
Example Scenario
- HTTP Call:
- A mobile app calls
GET https://api.example.com/user/123
to fetch user info. - The app must know the server’s exact URL and handle authentication, TLS, etc.
- A mobile app calls
- NATS Request–Reply:
- A service sends a request to subject
user.get
with payload{id:123}
. - Any service subscribed to
user.get
can reply. The client doesn’t care where the service is running. - If multiple services are subscribed, NATS will load-balance the request automatically.
- A service sends a request to subject
Final Thoughts
Request–Reply is a powerful complement to pub/sub in NATS. Use it when you need direct responses from a service, like fetching data, running commands, or performing checks. Together, pub/sub and request–reply give you flexible patterns to design distributed systems that fit your needs.
Pages: 1 2
Category: NATS