TS Class with Interval and Mongoose Fetching: Addressing Memory Leakage

In TypeScript, I created a class that utilizes a websocket to emit pre-fetched data from mongoose based on certain parameters.

PLEASE NOTE: The code provided here is for demonstration purposes only and not the actual implementation. It has been simplified for easier understanding

import { Server as SocketServer } from 'socket.io';
import { Animal, AnimalModel } from './animal.model.ts'; 
// ^^^^^^^ this consists of basic properties interface and a mongoose schema

export class Stream {
    private io: SocketServer;
    private breed: string;
    private animals: Array<Animal>;
  
    constructor(
        io: SocketServer,
        breed: string
    ) {
      this.io = io;
      this.breed = breed;
      
      this.fetch(); // initial fetch
      setInterval(() => this.emit(), 1000); // emit every second
      setInterval(() => this.fetch(), 1000); // fetch it every second for updates
      // ^^^ when I comment out this line, memory leakage seems to be resolved
    }

    /**
    * Fetch the list of animals based on the specified breed
    */ 
    private async fetch(): Promise<void> {
       this.animals = await AnimalModel.find({breed: this.breed}).limit(20).exec(); // each fetch retrieves around 100kb
    }

    /**
    * Emit the list of animals to subscribers of the breed
    */
    private emit(): void {
        this.io.in(this.breed).emit("animals", JSON.stringify(this.animals))
    }  
}

The generation of these animals is done like this:

import { AnimalModel } from './animal.model.ts'; 

const socket = makeSocket(); // function to create a new socket.io instance

const initialize = async () => {
    // About 25 animals
    const animalsList = await AnimalModel.find().exec();
    animalsList.forEach(animal => {
       new Stream(socket, animal.breed); // creates a new stream for each animal breed with a reference to the socket
    });
};

initialize();

The issue arises when each fetch operation (per breed) consumes about 100kb, resulting in approximately 2.5MB being added to the memory heap every second. By excluding the fetch operation, further increase in memory usage is prevented. It appears that the fetch function is not releasing resources properly.

I have spent hours attempting various solutions, including using Chrome NodeJS debug tool and experimenting with different functions, but no success so far. Can anyone provide assistance or suggest alternative code that avoids memory leaks?

PS: I have Heap snapshots available if needed

Answer №1

After some investigation, I was able to pinpoint the root of the problem.

It turned out that each query to the database was taking approximately 0.2 seconds to complete. With a total of 102 streams being queried concurrently, it added up to a whopping 19 seconds!

Furthermore, the stream was making queries every second, causing an exponential increase in requests over time.

To address this issue, I adjusted the interval timing to align with the expected network request duration.

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

Exploring Javascript parameters with the power of jquery

Is it possible to pass a parameter from PHP into a JavaScript function within HTML? I am currently facing an issue where my code crashes when it reaches a certain condition. This is the code snippet causing the problem: $str="<input type='submit&a ...

Issues arise when using jQuery to manipulate HTML content within an Asp.Net environment

Recently, I found myself in a puzzling situation with a div that has the attribute runat="server". <div id="results" runat="server" class="results"></div> Using jQuery, I added HTML content to this div. $('.results').html('Add ...

Guide on ensuring all dynamic components of a NodeJS SailsJS web application are loaded using ajax requests

Exploring SailsJS and NodeJS for the first time, I decided to dive into a tutorial on creating a basic web application using these technologies. My main query is regarding rendering views (excluding the template) through Ajax. I aim to achieve a similar f ...

Cutting an in-memory Base64 PNG using ONLY JavaScript on the client side without relying on canvas

Scenario: Working with JavaScript in a SDK environment, either on node.js or a browser. Situation: I have a base64 string containing a PNG image encoded using base64 (extracted from selenium webdriver's takeScreenshot function). Inquiry: How can I c ...

Ways to access the previous and following elements that belong to a specific class, but are not directly related

Below is the code snippet provided: <ul> <li class="active"> <div class="course_video_heading"><span class="minus"></span> Introduction <div class="course_duration" align="right">1m 21s</div></div&g ...

Display JSON information on a webpage with the help of Backbone framework

At an event in my view, when a key is pressed and released, it triggers a fetch request to the TMDB API. class Movieseat.Views.Moviesearch extends Backbone.View template: JST['movieseats/moviesearch'] el: '#moviesearch' initial ...

Having trouble parsing PHP JSON encoded data in JavaScript

When I make an AJAX call to a PHP script that returns a JSON encoded object, I encounter some issues. $.post("php/getCamera.php", { cam_id: identifier }, function(data){ console.log(data); //var camera = JSON.parse( ...

There seems to be an issue with saving posts to the database when using RESTful services

Problem with POST request not saving data properly in database I am using Node.js with Express and Mongoose for RESTful services. Here is my model: var mongoose = require('mongoose'), Schema = mongoose.Schema; var bookModel = new Schema({ title ...

The function queryDatabases is not supported in the DocumentDB JavaScript API

Currently, I am developing a service for Azure Functions using JavaScript/Node.js. However, I encounter an error when trying to access the function DocumentClient.queryDatabases. Despite having the correct references installed in Visual Studio Code and bei ...

Using Typescript generics to create parameter and argument flexibility for both classes and

I'm facing an issue where I need to effectively chain multiple function calls and ensure that TypeScript verifies the correctness of their linkage. export class A<T, K> { public foo(a: A<K, T>): A<K, T> { return a; } } cons ...

Tips for troubleshooting a React extension

Struggling to kick off the development of an internal-use add-in, I find myself stuck at the simple task of logging information with console.log. A previous inquiry on this issue can be found here. My approach involved using the yo office command within t ...

JavaScript was unable to compute the area based on the given inputs

Expected CalculatorActual Calculator I am in the process of developing a unit conversion calculator for area measurements in Nepal using JavaScript. The calculator will convert traditional units like Ropani, Anna, Paisa, and Dam to square feet and square m ...

Is it possible to show a pop-up window containing aggregated data when the jQuery double-click event

How can I create a pop-up window to display aggregated data when the Double-click event is triggered in jQuery? In my code, each questionId has multiple related reasons. When a user clicks or selects a questionId button/event, the selected questionId will ...

Determining the distance between two points in miles using Next.js

Are you familiar with the concept of geographical coordinates? Take for example these two points: point1 = {lat: 40.6974034, lng: -74.1197636} point2 = {lat: 42.694034, lng: -75.117636} My goal is to find the distance between these two poi ...

Is there a way for me to record the variable's name instead of its linked data?

Currently, I am developing a node.js program that monitors the prices of different currencies. While I can successfully retrieve the prices, I would like the program to also display the names of the currencies along with their prices. In the code snippet b ...

The issue of banding caused by Bloom and Antialiasing in Three.js rendering

I'm attempting to incorporate a glowing effect into my scene. To achieve this, I understand that using a bloom filter with the EffectComposer is the ideal approach. However, I've encountered an issue where utilizing the EffectComposer compromises ...

Is there a way to save a Vue file as a PDF in Vue.js?

I am looking for a way to enable users to download a Vue file as a PDF when they click on a button in the main component. Any suggestions on how to achieve this would be greatly appreciated. download.vue <template> <div> This file contai ...

Show an empty table/data grid with blank rows using Material UI

I am attempting to showcase a table with empty lines and a predefined height, even when there is no data to display initially. By default, the table appears without any visible lines. My goal is to have these empty lines displayed, ensuring that the table ...

Use the IONIC CAPACITOR application to send a 20-byte command to a BLE device

Hello everyone, I am currently working on an application that is designed to connect to a BLE device. I have a requirement to write 20 Bytes to the device using BleClient.write function. 34h 01h 50h 4Fh 4Ch 49h 54h 45h 43h 00 00 00h 00h 00h 00h 00h 00h 00h ...

Tips for dynamically changing the body class based on the page in a remix

I am trying to set parameters for the body class in root.jsx, which will change based on the page being viewed. I want to assign different values to the class in each route - for example, in _index it should be "company homepage", and in the restaurants ro ...