nats.ionats-streaming-server

Nats which pattern to use


I asked a question in: Microservice Architecture dependency which pattern to use when using a clustered Microservice architecure.

I recieved answer that point to point should work but when reading: https://nats.io/documentation/concepts/nats-req-rep/ It feels like all subscribers recieves event (and because of that handles it) but there will just be one subscriber that responses. This will not work when putting an order event that will trigger an update-inventory-event that Inventory microservices subscribes to (as in example in link) i.e it wont work in a clustered env due to inventory will be updated the same amount of times as the amount of microservice instances.

How can I solve this scenario using Nats?

Thanks in advance!


Solution

  • NATS.io supports this feature using queue groups:

    All subscriptions with the same queue name will form a queue group. Each message will be delivered to only one subscriber per queue group, using queuing semantics. You can have as many queue groups as you wish. Normal subscribers will continue to work as expected.

    Connect your services using the queue group (sample is node.js):

    https://github.com/nats-io/node-nats#queue-groups

    nats.subscribe('foo', {'queue':'job.workers'}, function() {
        received += 1;
    });
    

    then the client would use the library provided request methods:

    https://github.com/nats-io/node-nats#basic-usage

    // Request for single response with timeout.
    nats.requestOne('help', null, {}, 1000, function(response) {
      // `NATS` is the library.
      if(response.code && response.code === NATS.REQ_TIMEOUT) {
        console.log('Request for help timed out.');
        return;
      }
      console.log('Got a response for help: ' + response);
    });