middleware in mongoose vs replica set for things like sending emails/sms

Viewed 208

Which one is better approach for things this sending Emails ,Sms (for account verification) , notifications bla bla via nodejs application

As per my knowledge there can be two approaches.

  1. Execute a function after save which will do this... one can use mongoose middleware like after save..

  2. Simulate triggers with the help of replica set in mongodb and run it through background jobs

I think second approach is better because it will be executed by some other process in background, But on the other hand node.js is asynchronous may be node.js handles these kind of stuffs in a smart way .. any idea !!!

In short: Sending Sms emails notification after user regestration should be send by nodjs middleware or by background process and as per my knowledge background process can be executed by binding a listener to oplog

2 Answers

The best approach for triggering an sms/email service request after saving the document in mongoDB would be through some messaging queue.

I would recommend using RabbitMQ. It will segregate the process of sending sms/email from your req/res loop. Invoke it after the success of save function and it will get added in the queue with a completely different process. You can simply return the success result of save function without waiting for the response of message worker.

The messaging queue comes with many more features like delivery acknowledgement, scalability options, apis and guis for managing and monitoring the status of actions performed.

You can either set it up on the same server or deploy on a separate server according to the traffic.

As of MongoDB 3.6, you can do exactly this via Change Streams. They are a new feature API that let you trigger all sorts of actions based on events happening in the database.

Related