Worker Threads vs Async Loop for I/O‑Bound Node.js Microservices
In a recent project we built a thin‑service that fans out to 30+ third‑party APIs per request, aggregates the JSON payloads and returns a single response. The CPU work is trivial – just a few map/reduce steps – but the latency budget is tight (≤150 ms). Two patterns emerged:
Pure async/await – each call is wrapped in a fetch promise and we await Promise.all. The event loop stays single‑threaded, memory overhead is low, and back‑pressure is handled by the HTTP client library. However, under burst traffic the kernel’s socket buffers fill, and the process spends most of its time in the poll phase, making it hard to isolate a misbehaving downstream service.
Worker‑thread pool – we spin up a small pool (e.g., 4‑8) using worker_threads. Each worker receives a batch of URLs, performs the same Promise.all logic, and posts the aggregated result back. This adds a context‑switch cost and extra heap per worker, but it gives us natural isolation: a hung request only blocks its worker, not the main loop. It also lets us pin workers to specific CPU cores if the host is CPU‑constrained.
// main thread snippet
const { Worker } = require('worker_threads');
function runInWorker(urls) {
return new Promise((res, rej) => {
const w = new Worker('./worker.js', { workerData: urls });
w.on('message', res);
w.on('error', rej);
});
}
Open questions
- At what request‑per‑second threshold have you found the thread pool starts to win over pure async in production?
- Which metrics and tooling do you rely on to tune the pool size and detect thread‑starvation without adding too much overhead?
Looking forward to hearing your real‑world numbers and any gotchas you hit when rolling this out in Kubernetes or bare‑metal environments.
0 Answers
Post Your Answer
Use ``` code ``` for syntax highlighting