I have an app running on Nest.Js / Node.Js which does text processing and because of that it has an .map (or .forEach) iteration that takes a lot of resources (tokenizing a sentence, then removing the stopwords, etc — for each sentence of which there may be tens of thousands).
For reproducibility, I provide the code I use below, without the text processing details — just a long heavy loop to emulate my problem:
const before = Date.now()
const statements = [...Array(100)]
let l = 0
let p = 0
const processed =
statements.map((value, index) => {
// a set of consecutive functions that take a long time to execute
for (let i = 0; i < 100000; i++) {
l = l + i * Math.random()
}
// console.log(index + ' ' + l + ' ' + (Date.now() - before))
p = index
return l
})
console.log(processed)
const after = Date.now()
console.log(p + ' results in ' + (after - before) + ' ms')
For very big files the process takes up to 100% of the CPU, so the app becomes unresponsive.
I was wondering if you know of any solution to prevent the app from taking all the CPU made available to it. Like is there a way to set any single process to take 80% and always leave 20% for the other users?
PS I run it from Amazon's ECS so of course I can create clusters and also use PM2 for clusterization, but I wonder how I can avoid the 100% load from a single process within a Javascript / Node.Js app itself. I mention the Nest.Js framework because maybe there's a solution there as well.