The server gets blocked by numerous AJAX GET requests happening at the same time until the data gets returned

In my Rails application, I am using the gridList library to display charts. The chart data is fetched asynchronously from a controller method in JSON format via AJAX. Upon initial page load, each gridlist item displays a loading icon while simultaneously making an AJAX call to retrieve the data. Each grid item triggers a separate AJAX request. While the charts are rendering correctly, an issue arises where the server becomes unresponsive to other requests such as page refresh or route changes until all the charts have finished loading.

The problem appears to be on the server side, as the front-end JavaScript functions properly during AJAX calls.

The grid items are generated using the following partial:

%li.grid_item{ data: { id: chart.id } }
 .chart-loading
   // loading icon
 .chart-content.hide
   // hidden chart content

:javascript
 var chart_id = "#{chart.id}"
 $.ajax({
   url: "#{get_data_charts_path(chart.id)}",
   success: function (res) {
     var data = JSON.parse(res)
     hideLoadingChart(chart_id) // hides loading and shows chart-content
     renderChart(data) // plots chart for the data
   }
 })

The partial is invoked using this command:

.grid-container
 %ul#grid.grid
  = render partial: 'chart', collection: @current_user.get_charts

What might be causing this issue? Is there a way to cancel ongoing AJAX calls when a new request is made to the server? Also, is the approach of making multiple AJAX calls for each chart the right design choice? I aim to have the charts load dynamically as data becomes available, rather than all at once towards the end.

Answer №1

While a multi-threaded server does not always handle requests in parallel, it can still offer benefits in certain scenarios.

Employing multiple AJAX requests to retrieve data may introduce some overhead, especially if there is a need to load overlapping resources for each request. In such cases, it might be worth considering consolidating all data points into a single request. This can be achieved by making an index request specifying the boundaries of the desired data points and receiving only the relevant information as JSON.

For instance, you could fetch all data points by sending a request to GET /users/:user_id/charts.json to access all charts associated with a particular user. Assuming the existence of the following route:

resources :users, only: [] do
  resources :charts, only: :index
end

Other strategies to enhance request speed include:

  1. Streamlining database queries (e.g., addressing the n + 1 problem) through tools like #includes. Monitoring the server log can help identify potential issues in this area.
  2. Improving computational efficiency by utilizing lightweight algorithms. Identify any bottlenecks during execution by setting breakpoints and analyzing performance at different stages. Some calculations can also be offloaded to the database by aggregating or performing other optimizations.
  3. Allocating additional server resources can expedite request handling. For example, assigning multiple workers to manage concurrent tasks or boosting request processing with additional threads. For instance, using a command like
    bundle exec puma --workers 3 --threads 0:16
    , where increasing the worker count activates cluster mode.
  4. Upgrading hardware specifications on the development machine, including enhancements like a better CPU or SSD, can accelerate operations.
  5. Implementing a load balancer such as NGINX can distribute workloads across multiple machines for improved performance.

Answer №2

If you want to ensure that your ajax calls are executed sequentially, consider using $.Deferred. This allows you to chain multiple ajax calls so that each one is made only after the previous one has completed. By doing this, your server will be able to handle one ajax call at a time and respond to other requests without being overwhelmed.

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

JQuery not functioning properly within a dynamically loaded AJAX section

After loading some pages with Ajaxtabs, I encountered an issue where jQuery and Owl Carousel were not functioning properly. The classes and styles from Owl Carousel were not being applied to the divs after loading parts of the page. Here is an example of ...

The ng-disabled directive is functioning properly, however it is not having any impact on the disabled attribute in

Having an issue with enabling or disabling a button based on the selection of a certain string from a dropdown menu. HTML <select ng-change="checkType()" ng-options="sth in sth for things"></select> <input ng-disabled="{{toggleDisable}}" ...

Retrieve a variety of items and pass them to a view using the mssql module in Node

I'm facing an issue while trying to retrieve data from multiple tables and pass them to my view. Below is the snippet of code I've written that's causing the error. router.get('/', function(req, res, next) { sql.connect(config ...

How to make views in React Native adjust their size dynamically in a scrollview with paging functionality

Has anyone successfully implemented a ScrollView in React Native with paging enabled to swipe through a series of images? I am having trouble making the image views fill each page of the scroll view without hardcoding width and height values for the image ...

Update the 'checked' attribute of a radio button when the form is submitted

How do I dynamically change the content of an HTML table based on which radio button a user selects using jQuery? For example, when the page loads, I want the United Kingdom radio button to be checked and the table content to display as 'blue'. I ...

Finding tool for locating object names in JSON

JSON data: [ { "destination": "Hawaii", "Country": "U.S.A", "description": "...and so forth", "images": { "image": [ "hawaii1.jpg", "hawaii2.jpg", ...

Error: The JavaScript variable 'undefined' is being used as a function, which is incorrect. This error occurs when trying to execute the function `mockBackend

I am currently working on unit testing an AngularJS controller using Karma and Jasmine. Below is the test suite I have created: describe('Controllers', function(){ var $scope, ctrl; beforeEach(module('curriculumModule')); ...

Ext JS - A grid cell containing varying values, accompanied by a selection of combo boxes

I'm currently implementing the Ext JS Grid component and have a list of fields with their respective data types: ID (int) Name (string) Foods (List<string>) Each user can have multiple foods, selected from a Food DataStore. Displaying this in ...

Tips for ensuring a custom menu closes when clicking outside of it instead of on the menu itself

Building off a recent inquiry, I am aiming to have my menu close whenever I click outside of it. At the moment, clicking the "Hamburger Menu Button" opens and closes the menu. It will also close when I click a link on the menu or the menu itself. However, ...

Preventing Broken URLs in Jquery each

What is the best way to prevent taking images with broken URLs? jQuery.each(jQuery('img'), function(index, obj) { imageStack.add(jQuery(obj)); }); ...

Using Grails with AJAX: remoteLink results in a page redirect instead of updating the specified div

I am facing an issue with creating an ajax-enabled web application using the g:remoteLink<code> tag. Instead of updating the specified div, it redirects the whole page to my template.</p> <p><strong>This is what I have implemented: ...

Is there a way to calculate the height of a component that is only rendered conditionally?

I have a scenario where I need to dynamically adjust the height of a component that is conditionally rendered without explicitly setting it. The height should automatically match the size of its content. To achieve this, I am using a reference to determin ...

AngularJs - Customizable dynamic tabs that automatically adapt

Below is the HTML code snippet: <div> <ul data-ng-repeat ="tab in tabs"> <li data-ng-class="{active: tab.selected == 'true'}" message-key="Tab"> </li> </ul> </div> As shown ...

Forking a Node.js child process to assign it CPU affinity

Looking to utilize the child_process.fork function in Node.js for spawning a new process. This example is also applicable with the spawn function. To optimize CPU usage and make sure that these child processes are distributed evenly across all cores of th ...

Is there a way to efficiently import multiple Vue plugins in a loop without the need to manually type out each file individually?

I am looking for a way to streamline this code by using a loop to dynamically import all .js files from a specified directory (in this case, the 'plugins' directory). const plugins = ['AlertPlugin', 'AxiosPlugin', 'Confi ...

Using canvas to smoothly transition an object from one point to another along a curved path

As a beginner in working with canvas, I am facing a challenge of moving an object from one fixed coordinate to another using an arc. While referring to the code example of a solar system on https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutori ...

The client.postMessage() function in a service worker is not being recognized by the onmessage handler within an AngularJS controller

Handling Service Worker Messages: let angularClient; self.addEventListener('message', function(event) { // store the client that sent the message in the angularClient variable angularClient = event.ports[0]; }); Service Worker Notificat ...

Using an external logout function in Classic ASP

Basically, I am looking for a solution to the following scenario: In a classic ASP site, there is a link that redirects to an .ASPX file. This .ASPX file then sets user credentials using session variables and redirects to a third-party vendor-hosted site. ...

How to add a new row to a Kendo grid with a unique custom styling

I am looking for a way to insert new data into a Kendo grid, but I want the added row to have a custom class so that I can style it with a different background color. How can I achieve this? I have searched through all the documentation but couldn't f ...

Conceal descendant of list item and reveal upon clicking

In my responsive side menu, there is a submenu structured like this: .navbar ul li ul I would like the child menus to be hidden and only shown when the parent menu is clicked. Although I attempted to achieve this with the following code, it was unsucces ...