Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use worker-threads?

Tags:

node.js

nestjs

I am currently working on a backend which provides rest endpoints for my frontend with nestjs. In some endpoints I receive e.g. an array of elements which I need to process.

Concrete Example: I receive an array of 50 elements. For each element I need to make a SQL request. Therefore I need to loop over the array and do stuff in SQL.

I always ask myself: At what amount of elements should I use for example worker threads to not block the event loop?

Maybe I misunderstood the blocking of the event loop and someone can enlight me.

like image 433
Max Avatar asked Oct 24 '25 19:10

Max


1 Answers

I don't think that you'll need worker-threads in this scenario. As long as the sql-queries are executed asynchronsouly, i.e. the sql-query calls do not block, you will be fine. You can use Promise.all to speed up the processing of the loop, as the queries will be executed in parallel, e.g.

const dbQueryPromises = [];

for(const entry of data) {
   dbQueryPromises.push(dbConnection.query(buildQuery(entry)));
}

await Promise.all(dbQueryPromises);

If, however, your code performs computation-heavy operations inside the loop, then you should consider worker-threads as the long running operations on your call stack will block the eventloop.

like image 63
eol Avatar answered Oct 26 '25 10:10

eol