CodePark/ questions / Workers, cluster & child processes
START PRACTICINGPRACTICE
Backend question · Node.js › Workers, cluster & child processes

An API is slow because each request waits on several database queries and HTTP calls. A teammate proposes moving request handling into worker_threads. What is the best assessment?

It will mostly not help: the work is I/O-bound and the event loop already waits on it concurrently; workers help CPU-bound work

Workers will mostly not help, because this work is I/O-bound (it spends its time waiting for the database and the network). Waiting on a socket does not keep the main thread busy. So one event loop can already have many queries and HTTP calls running at the same time.

"Each worker can wait on I/O in parallel" is wrong: the event loop already waits in parallel. Workers only add memory use and messaging cost, and they do not make the waits shorter. "The main thread can only run one database query at a time" is wrong for the same reason.


Better fixes:

• Run independent calls at the same time with
Promise.all.
• Tune the connection pools.

• Add caching.

• Optimize the queries.