Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NATS Request Reply - How it works?

I am new NATS. Not sure how NATS request reply works.

As per my understanding, this pattern can be use for bi-directional communication but questions is, Does it works between same message id/thread ? If not, can't we use two different queue for the same purpose? How it is different from pub-sub or queue pattern of NATS?

Can someone provide more use case on this?

Thanks.

like image 685
DSA Avatar asked Mar 07 '23 11:03

DSA


1 Answers

You added nats-streaming-server tag, so I would first want to clarify that there is no request/reply API in NATS Streaming, because it does not really make sense.

In NATS, you would use request/reply when your publishing application wants to know that the subscribing application did receive and process the message. It is an end-to-end confirmation that the published message was received and processed.

It can also be simply because the subscribing application processes a job and send the result of that job back to the requestor.

A simple example would be:

// Request will create an internal subscription on
// a private inbox and set it to the message's Reply
// field.
msg, err := nc.Request("job", payload, time.Second)
if err != nil {
    ...
} else {
    // msg is the reply sent by the subscribing application.
}

In the other side, you would have registered a subscription to handle the job requests.

nc.Subscribe("job", func(req *nats.Msg) {
    // req is the request received by the publisher above.
    // Send back a reply to the request reply subject.
    nc.Publish(req.Reply, []byte(reply))
})

Not sure what language you use, but here is a link to the Go client

like image 154
I. Kozlovic Avatar answered Mar 16 '23 11:03

I. Kozlovic