Node.js Multiprocessing
We all know that Node.js runs in a single-threaded mode, but it uses event-driven mechanisms to handle concurrency, which helps us create multiple child processes on multi-core CPU systems, thereby improving performance.
Each child process always has three stream objects: child.stdin, child.stdout, and child.stderr. They may share the parent process's stdio streams, or they may be independent stream objects that are piped.
Node provides the child_process and cluster modules to create child processes.
child_process module
-
exec - child_process.exec executes a command in a child process, buffers the child process's output, and returns the output as arguments to a callback function.
-
execFile - Directly executes an executable file, slightly safer.
-
spawn - child_process.spawn creates a new process using the specified command-line arguments.
-
fork - child_process.fork is a special form of spawn() used to run a module in a child process; for example, fork('./son.js') is equivalent to spawn('node', ['./son.js']). Unlike the spawn method, fork establishes a communication channel between the parent and child processes for inter-process communication.
cluster module
- On a single port with multiple worker processes sharing the listen, to achieve one process per core HTTP service.
- Suitable for scaling a web service horizontally to fully utilize multiple cores.
- Note: The official recommendation is for new projects to carefully evaluate (such as directly using a reverse proxy + multiple processes, or
worker_threadsfor CPU-intensive work), butclusteris still widely usable.
The exec() method
child_process.exec executes a command in a child process, buffers the child process's output, and returns the output as arguments to a callback function.
The syntax is as follows:
child_process.exec(command[, options], callback)
Parameters
The parameters are described as follows:
command: String, the command to run, with arguments separated by spaces
options: an object, which can be:
- cwd, String, the current working directory of the child process
- env, Object, key-value pairs of environment variables
- encoding, String, the character encoding (default: 'utf8')
- shell, String, the shell in which to execute the command (default: on UNIX it is
/bin/sh, on Windows it iscmd.exe, the shell should recognize the-cswitch on UNIX, or/s /con Windows. On Windows, command-line parsing should be compatible withcmd.exe) - timeout, Number, the timeout in milliseconds (default: 0)
- maxBuffer, Number, the maximum amount of data (in bytes) allowed in stdout or stderr; if exceeded, the child process will be killed (default: 200*1024)
- killSignal, String, the termination signal (default: 'SIGTERM')
- uid, Number, sets the user process ID
- gid, Number, sets the process group ID
**callback:** a callback function with three parameters: error, stdout, and stderr.
The exec() method returns the maximum buffer, waits for the process to finish, and returns the buffer contents all at once.
Example
Let's create two js files, support.js and master.js.
Code for the support.js file:
console
.
log
(
"
Process
"
process
.
argv
[
2
]
"
executed.
"
)
;
Code for the master.js file:
const
fs
=
require
(
'
fs
'
)
;
const
child_process
=
require
(
'
child_process
'
)
;
for
(
var
i
=
0
;
i
<
3
;
i
++
)
{
var
workerProcess
=
child_process
.
exec
(
'
node support.js
'
i
,
function
(
error
,
stdout
,
stderr
)
{
if
(
error
)
{
console
.
log
(
error
.
stack
)
;
console
.
log
(
'
Error code:
'
error
.
code
)
;
console
.
log
(
'
Signal received:
'
error
.
signal
)
;
}
console
.
log
(
'
stdout:
'
stdout
)
;
console
.
log
(
'
stderr:
'
stderr
)
;
}
)
;
workerProcess
.
on
(
'
exit
'
,
function
(
code
)
{
console
.
log
(
'
Child process exited with code
'
code
)
;
}
)
;
}
The output of the code above is:
$ node master.js
子进程已退出,退出码 0
stdout: 进程 1 执行。
stderr:
子进程已退出,退出码 0
stdout: 进程 0 执行。
stderr:
子进程已退出,退出码 0
stdout: 进程 2 执行。
stderr:
Analysis:
exec will start 3 child processes, executing respectively:
node support.js 0node support.js 1node support.js 2
Each child process outputs immediately after running:
进程 0 执行。
进程 1 执行。
进程 2 执行。
This part is the child process's standard output (stdout), which is buffered and returned all at once when the child process ends exec callbacks.
When a child process exits, it first triggers the exit event, and then exec callback is executed (note: the Node.js documentation states that the exit event occurs when the process ends, while exec callback is stdio triggered after the stream closes; usually exit prints before the callback).
The output order is nondeterministic, because the 3 child processes execute in parallel and which one finishes first depends on OS scheduling.
The spawn() method
child_process.spawn creates a new process using the specified command-line arguments. The syntax is as follows:
child_process.spawn(command[, args][, options])
Parameters
The parameters are described as follows:
command: the command to run
args: Array, an array of string arguments
options Object
- cwd String, the current working directory of the child process
- env Object, key-value pairs of environment variables
- stdio Array|String, the stdio configuration of the child process
- detached Boolean, whether this child process will become the leader of a new process group
- uid Number, sets the user process ID
- gid Number, sets the process group ID
The spawn() method returns streams (stdout & stderr) and is used when a process returns large amounts of data. spawn() starts receiving a response as soon as the process begins executing.
Example
Let's create two js files, support.js and master.js.
Code for the support.js file:
console
.
log
(
"
Process
"
process
.
argv
[
2
]
"
executed.
"
)
;
Code for the master.js file:
const
fs
=
require
(
'
fs
'
)
;
const
child_process
=
require
(
'
child_process
'
)
;
for
(
var
i
=
0
;
i
<
3
;
i
++
)
{
var
workerProcess
=
child_process
.
spawn
(
'
node
'
,
[
'
support.js
'
,
i
]
)
;
workerProcess
.
stdout
.
on
(
'
data
'
,
function
(
data
)
{
console
.
log
(
'
stdout:
'
data
)
;
}
)
;
workerProcess
.
stderr
.
on
(
'
data
'
,
function
(
data
)
{
console
.
log
(
'
stderr:
'
data
)
;
}
)
;
workerProcess
.
on
(
'
close
'
,
function
(
code
)
{
console
.
log
(
'
Child process exited with code
'
code
)
;
}
)
;
}
The output of the code above is:
$ node master.js stdout: 进程 0 执行。
子进程已退出,退出码 0
stdout: 进程 1 执行。
子进程已退出,退出码 0
stdout: 进程 2 执行。
子进程已退出,退出码 0
The fork method
child_process.fork is a special form of the spawn() method used to create processes. The syntax is as follows:
child_process.fork(modulePath[, args][, options])
Parameters
The parameters are described as follows:
modulePath: String, the module to run in the child process
args: Array, an array of string arguments
options:Object
- cwd String, the current working directory of the child process
- env Object, key-value pairs of environment variables
- execPath String, the executable used to create the child process
- execArgv Array, an array of string arguments for the child process's executable (default: process.execArgv)
- silent Boolean, if
true, the child process'sstdin,stdoutandstderrwill be piped to the parent process; otherwise, they will be inherited from the parent. (default:false) - uid Number, sets the user process ID
- gid Number, sets the process group ID
In addition to all the methods of a ChildProcess instance, the returned object also has a built-in communication channel.
Example
Let's create two js files, support.js and master.js.
Code for the support.js file:
console
.
log
(
"
Process
"
process
.
argv
[
2
]
"
executed.
"
)
;
Code for the master.js file:
const
fs
=
require
(
'
fs
'
)
;
const
child_process
=
require
(
'
child_process
'
)
;
for
(
var
i
=
0
;
i
<
3
;
i
++
)
{
var
worker_process
=
child_process
.
fork
(
"
support.js
"
,
[
i
]
)
;
worker_process
.
on
(
'
close
'
,
function
(
code
)
{
console
.
log
(
'
Child process exited with code
'
code
)
;
}
)
;
}
The output of the code above is:
$ node master.js
进程 0 执行。
子进程已退出,退出码 0
进程 1 执行。
子进程已退出,退出码 0
进程 2 执行。
子进程已退出,退出码 0
cluster: A multi-process HTTP service on a single port
A minimal working multi-core HTTP service
Example
// server-cluster.js
import
cluster from
'node:cluster'
;
import
os from
'node:os'
;
import
http from
'node:http'
;
import
{
pbkdf2Sync
}
from
'node:crypto'
;
if
(
cluster.
isPrimary
)
{
const
cpuCount
=
Math
.
max
(
1
,
os.
cpus
(
)
.
length
)
;
console.
log
(
`Master process $
{
process.
pid
}
, starting $
{
cpuCount
}
worker processes`
)
;
for
(
let i
=
0
;
i
<
cpuCount
;
i
++
)
cluster.
fork
(
)
;
cluster.
on
(
'exit'
,
(
worker
,
code
)
=>
{
console.
warn
(
`Worker process $
{
worker.
process
.
pid
}
exited (code
=
$
{
code
}
), restarting…`
)
;
cluster.
fork
(
)
;
}
)
;
}
else
{
const
server
=
http.
createServer
(
(
req
,
res
)
=>
{
// Simulate CPU-intensive computation
pbkdf2Sync
(
'password'
,
'salt'
,
100
_000
,
64
,
'sha512'
)
;
res.
writeHead
(
200
,
{
'content-type'
:
'text/plain; charset=utf-8'
}
)
;
res.
end
(
`Handled by worker $
{
process.
pid
}
\n`
)
;
}
)
;
server.
listen
(
3000
,
(
)
=>
{
console.
log
(
`Worker process $
{
process.
pid
}
Listen for
3000
`
)
;
}
)
;
}
Run: node server-cluster.js; making multiple requests to http://localhost:3000 will show responses from different PIDs.
**Note:** In production, multiple instances usually have a reverse proxy/load balancer in front (Nginx, Envoy, K8s Service), or are aggregated on a single port by cluster.
WebSocket/sticky sessions require a "sticky session" (the same client lands on the same worker). You can use source-address hashing in a Layer 4 load balancer, or implement stickiness at the application layer yourself (such as distributing by req.socket.remoteAddress).
Graceful restart (zero-downtime approach)
**Approach:** The primary process receives a reload signal → first forks a new worker and waits for it to be listening → then disconnects the old worker and waits for requests to finish before exiting.
Example
// Simplified example (inside the cluster.isPrimary branch)
process.
on
(
'SIGUSR2'
,
async
(
)
=>
{
console.
log
(
'Received SIGUSR2, starting graceful restart'
)
;
const
workers
=
Object
.
values
(
cluster.
workers
??
{
}
)
;
// 1) Start the new one
const
fresh
=
cluster.
fork
(
)
;
await
new
Promise
(
r
=>
fresh.
once
(
'listening'
,
r
)
)
;
// 2) Take the old ones offline one by one
for
(
const
w of workers
)
{
w
?
.
disconnect
(
)
;
// Force-kill if it hasn't exited after the timeout
setTimeout
(
(
)
=>
w
?
.
process
.
kill
(
'SIGKILL'
)
,
5000
)
;
}
}
)
;
Windows doesn't have SIGUSR2; you can use an HTTP / RPC management interface to trigger a reload.
Build your own "process pool": control concurrency and reuse child processes
When you have many independent CPU tasks (such as batch compression, encryption, or crawler parsing), frequent fork/spawn is costly; in this case you need a Process Pool to reuse several child processes, throttling like a "thread pool".
**File:** pool/worker.js
Example
// pool/worker.js
process.
on
(
'message'
,
async
(
msg
)
=>
{
if
(
msg.
type
===
'task'
)
{
const
{
id
,
payload
}
=
msg
;
// Simulate a heavy task (Fibonacci)
const
fib
=
(
n
)
=>
(
n
<=
1
?
n
:
fib
(
n
1
)
fib
(
n
2
)
)
;
const
result
=
fib
(
payload.
n
)
;
process.
send
(
{
type
:
'done'
,
id
,
result
}
)
;
}
}
)
;
**File:** pool/index.js
Example
// pool/index.js
import
{
fork
}
from
'node:child_process'
;
import
os from
'node:os'
;
export
class
ProcessPool
{
constructor
(
{
file
,
size
=
Math
.
max
(
1
,
os.
cpus
(
)
.
length
1
)
}
=
{
}
)
{
this
.
file
=
file
;
this
.
size
=
size
;
this
.
idle
=
[
]
;
this
.
busy
=
new
Map
(
)
;
// worker -> taskId
this
.
queue
=
[
]
;
for
(
let i
=
0
;
i
<
size
;
i
++
)
this
._spawn
(
)
;
}
_spawn
(
)
{
const
w
=
fork
(
this
.
file
)
;
w.
on
(
'message'
,
(
m
)
=>
{
if
(
m
?
.
type
===
'done'
)
{
const
cb
=
this
.
callbacks
.
get
(
m.
id
)
;
if
(
cb
)
cb.
resolve
(
m.
result
)
;
this
.
callbacks
.
delete
(
m.
id
)
;
this
._markIdle
(
w
)
;
this
._drain
(
)
;
}
}
)
;
w.
on
(
'exit'
,
(
)
=>
{
// Automatically refill the pool
this
.
busy
.
delete
(
w
)
;
const
idx
=
this
.
idle
.
indexOf
(
w
)
;
if
(
idx
=
0
)
this
.
idle
.
splice
(
idx
,
1
)
;
this
._spawn
(
)
;
}
)
;
if
(
!
this
.
callbacks
)
this
.
callbacks
=
new
Map
(
)
;
this
.
idle
.
push
(
w
)
;
}
_markIdle
(
w
)
{
this
.
busy
.
delete
(
w
)
;
if
(
!
this
.
idle
.
includes
(
w
)
)
this
.
idle
.
push
(
w
)
;
}
_acquire
(
)
{
return
this
.
idle
.
length
?
this
.
idle
.
shift
(
)
:
null
;
}
_drain
(
)
{
while
(
this
.
queue
.
length
&&
this
.
idle
.
length
)
{
const
{
id
,
payload
,
resolve
,
reject
}
=
this
.
queue
.
shift
(
)
;
const
w
=
this
._acquire
(
)
;
this
.
busy
.
set
(
w
,
id
)
;
this
.
callbacks
.
set
(
id
,
{
resolve
,
reject
}
)
;
w.
send
(
{
type
:
'task'
,
id
,
payload
}
)
;
}
}
runTask
(
payload
)
{
const
id
=
Math
.
random
(
)
.
toString
(
36
)
.
slice
(
2
)
;
return
new
Promise
(
(
resolve
,
reject
)
=>
{
this
.
queue
.
push
(
{
id
,
payload
,
resolve
,
reject
}
)
;
this
._drain
(
)
;
}
)
;
}
close
(
)
{
for
(
const
w of
this
.
idle
)
w.
kill
(
)
;
for
(
const
w of
this
.
busy
.
keys
(
)
)
w.
kill
(
)
;
}
}
**File:** pool/demo.js
Example
// pool/demo.js
import
{
ProcessPool
}
from
'./index.js'
;
const
pool
=
new
ProcessPool
(
{
file
:
'./pool/worker.js'
,
size
:
4
}
)
;
const
tasks
=
Array
.
from
(
{
length
:
10
}
,
(
_
,
i
)
=>
pool.
runTask
(
{
n
:
35
(
i
%
3
)
}
)
)
;
const
t0
=
Date
.
now
(
)
;
const
results
=
await Promise.
all
(
tasks
)
;
console.
log
(
'Result:'
,
results
)
;
console.
log
(
'Elapsed (ms):'
,
Date
.
now
(
)
t0
)
;
await
new
Promise
(
r
=>
setTimeout
(
r
,
100
)
)
;
// Wait for messages to finish flushing
pool.
close
(
)
;
Explanation:
- Encapsulate "tasks" as messages; the process pool is responsible for distributing and reusing workers.
- In real business scenarios, you can put parsing/transcoding/compression into
worker.js. - Note Task timeout、Retry、Idempotency The difference between Backpressure(an upper limit on queue length).
Practical example: An HTTP endpoint throws heavy tasks into the process pool
Example
// app.js
import
http from
'node:http'
;
import
{
ProcessPool
}
from
'./pool/index.js'
;
const
pool
=
new
ProcessPool
(
{
file
:
'./pool/worker.js'
,
size
:
4
}
)
;
const
server
=
http.
createServer
(
async
(
req
,
res
)
=>
{
if
(
req.
url
?
.
startsWith
(
'/fib?'
)
)
{
const
url
=
new
URL
(
req.
url
,
'http://localhost'
)
;
const
n
=
Number
(
url.
searchParams
.
get
(
'n'
)
||
35
)
;
try
{
const
result
=
await pool.
runTask
(
{
n
}
)
;
res.
writeHead
(
200
,
{
'content-type'
:
'application/json'
}
)
;
res.
end
(
JSON.
stringify
(
{
pid
:
process.
pid
,
n
,
result
}
)
)
;
}
catch
(
e
)
{
res.
writeHead
(
500
)
;
res.
end
(
'error'
)
;
}
}
else
{
res.
writeHead
(
404
)
.
end
(
'Not Found'
)
;
}
}
)
;
server.
listen
(
3000
,
(
)
=>
console.
log
(
'http://localhost:3000'
)
)
;
Access: /fib?n=38 etc.; the primary process is not blocked, and tasks are computed in child processes.