The technique for handling intricate calls in node.js

My goal is to create a social community where users are rewarded for receiving upvotes or shares on their answers. Additionally, I want to send notifications to users whenever their answers receive some interaction.

The process flow is detailed in the comments within the code snippet below. The post_EVENT function is accessible through the API and serves as the starting point for the flow.

var answerController = function(){
    Emitter.call(this);
    var self = this;
    var continueWith = null;

    var push_event = function(event, answerId, likerId, callback){

        // Checking data and preparing queries batch
        // Implemented this way due to mongoose limitations
        var batch = Answer.collection.initializeOrderedBulkOp();
        batch.find(query).upsert().updateOne(update);
        batch.execute(function(err,result) {
            if(err){
                return callback(err);
            }else{
                return callback(null, result.nModified);
            }
        });
    };


    // Made available as an API call for yo/share/view
    // Invokes push_event
    var post_event = function(req,res, next){

            // Validate incoming request data and pass it along

            push_event(event,answerId, likerId, function(err, num_updated_docs){
                if(err){
                    return errors.api_error({code: 500, message: err, res: res, next: next});
                }else{
                    if(num_updated_docs){
                        // Creating calculateScore_args variable
                        self.emit('calculateScore',calculateScore_args);
                        res.status(200).send({message : 'success'}).end();
                    }else{
                        return errors.api_error({code: 401, message: 'event already exists for user', res: res, next: next});
                    }
                }
            });

    };


    var score = function(args){

        var asyncTasks = [];
        asyncTasks.push(function(cb){
            // Update user's score
            // Intensive CPU function (small matrix multiplication)
        })

        asyncTasks.push(function(cb){
            // Update answer's score  (user's score depends on various answers)
            // Another CPU intensive task, calculates confidence interval -->  score
        })

        async.parallel(asyncTasks, function(err, results){
            self.emit('notify', notifyData);
          })

    };

    function notify(args){
        // Invoking another controller that notifies the user(GCM) and inserts notification into DB
        notification.AnswerEvent(args);

    }

    self.on('calculateScore', score);
    self.on('notify',notify);

    return {
        post_event : post_event
    }
};

Question : I am curious whether this pattern is suitable for handling around 100-200 requests per second. Any advice on alternative patterns (like message queues) would be appreciated. Also, what is the most effective method for debugging event emitter code?

Thanks

Answer №1

One effective way to avoid server blocking is by relocating CPU intensive code away from the web server.

Using a task queue can help in accomplishing this goal easily. In my experience with Ruby, I have found success using https://github.com/resque/resque.

If you are looking for a node port solution, consider checking out https://github.com/taskrabbit/node-resque. This allows you to create and enqueue jobs, while also running workers to efficiently handle the workload.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for the selection box in my form not changing the items when togg

I'm having an issue with my form selection box code that used to work but is now not functioning properly. Could someone please help me identify where the error lies? Essentially, I have a form with the ID #main and a select box named #chart-type. Th ...

Having trouble with selecting checkboxes in a div using jQuery? While it may work in IE and Firefox, Chrome seems to be causing issues

In my div, I have several checkboxes placed under labels for formatting purposes. There is a list of checkbox names that need to be checked upon certain actions. Here is the list: var columns= ['2','5','4'] This is the curren ...

Encountered a Gulp error: unable to spawn process due to E

gulpfile.js 'use strict'; var gulp = require('gulp'); gulp.paths = { src: 'src', dist: 'dist', tmp: '.tmp', e2e: 'e2e' }; require('require-dir')('./gulp'); gulp.ta ...

React Native: Once a user has successfully logged in, I would like the app to automatically direct them to the "Home" screen

After a user signs in, I would like my app to navigate home. However, it seems this is not working because the roots have not been updated. You can view the App code here to get a better understanding of what I am trying to communicate. What is the most e ...

Unable to submit form with Jquery

Having some trouble with my form submission using Jquery. The submit part of my code seems to be malfunctioning, and I can't pinpoint the issue. <?php if(!isset($_SESSION["useridentity"])){ die(header("Location:index.php")); } ...

The function window.close() does not close the pop-up window when called within the pop-up

I am facing an issue with a Customer Info form that contains an anchor tag "close" meant to close the current window. This customer form is displayed as a pop-up. Within this form, there is also a search button that triggers a pop-up for the search form co ...

Issue with deploying NEXT.JS due to a failure in the build process caused by next lint

Issue I have been encountering deployment failures on Vercel due to lint errors in test files within my git repository. Despite following the recommendations from the Vercel documentation for ESLint settings, the issue persists. According to Vercel' ...

Using Regular Expressions in Javascript

I have gone through numerous posts with this title, but so far, none of them have addressed my specific query... My requirement is to utilize regex in the following format: "/^ user provided input $/i". The user can include the special regex character * e ...

Tips for creating a mobile-responsive React + MUI component

A React component utilizing Material-UI (MUI) has been created and I am working on making it mobile responsive. The current appearance is as follows: https://i.stack.imgur.com/8z0T8.png My goal is to have it look like this: https://i.stack.imgur.com/L8g ...

What is the memory allocation for null values in arrays by node.js?

Continuing the discussion from this thread: Do lots of null values in an array pose any harm? I experimented with node.js by doing this: arr=[] arr[1000]=1 arr[1000000000]=2 arr.sort() However, I encountered the following error: FATAL ERROR: JS Alloca ...

Is there a way to retrieve the line number of an error within a dynamically inserted <script> element?

When I dynamically create a script element and add it to the page, the errors do not give me the line numbers of the script itself, but instead provide the line number where I append the script. The following code in a .js file will result in an error mes ...

The shadow effects and color overlays do not seem to be functioning properly in Mozilla Firefox

I have designed a popup registration form using the Bootstrap modal class. To ensure form validation, I have integrated some jQuery validation engine functionality. Additionally, I customized the appearance by adding a box shadow, adjusting the background ...

Travis is experiencing issues with retrieving the API key after logging in with npm

Referencing the information found at , it is stated that an API key should be visible after executing npm login. However, upon performing npm login (or npm adduser) and checking with cat .npmrc, I am unable to locate any indication of an API key. I would ...

Struggling to link an external JavaScript file to your HTML document?

While attempting to run a firebase app locally, I encountered an error in the chrome console: GET http://localhost:5000/behaviors/signup.js net::ERR_ABORTED 404 (Not Found) Do I need to set firebase.json source and destination under rewrites or add a rout ...

Guide to referencing the same schema as a type in Mongoose

I have created a list of objects called Comments Objects in which comments are stored, and whenever someone replies to a comment, it gets stored in the children section. { "_id": "5dbc479babc1c22683b73cf3", "comment": "wow .. this is awesome", ...

Developing entities in Express.js

My express app is currently fetching data from an external API through the following endpoints: api.com/companies (GET, POST) api.com/companies/id (GET, PUT) To improve maintainability and avoid code repetition, I am looking to create a model for handlin ...

What is the method for configuring Vue to utilize a value other than the value property in form fields?

I am facing a unique challenge. Consider this: <select name="screw[type]" v-model="form.screw.type"> <option value="My value" ><?php _e('My value', 'fiam'); ?></option> //[...] Now, in another part of my ...

Querying an API for JSON data repeatedly until a particular key is located

I am currently in the process of working on a submission-based project where tasks are performed using the submitted content. While a details/results page is generated immediately after submission (the job being queued), the results may not be readily avai ...

The functionality of the submit form is encountering issues upon integration of Ajax requests

Hello everybody! I am currently creating a dynamic form for editing specific classes, but I am facing an issue with the ajax call not working. Below is the HTML code for the form: <form id="userDataForm" name="userDataForm" th:acti ...

Converting Byte strings to Byte arrays in Node.js using JavaScript

Currently facing a challenge while trying to complete the pythonchallenge using JS and Node. Stuck on challenge 8 where I need to decompress a string using bzip2: BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x ...