---
title: Workers, threads and cluster
project: Total.js V5
version: 0.0.20
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/workers-and-threads/
updated: 2026-11-19T16:16:57.153Z
---

# Workers, threads and cluster

> Worker threads, thread pools, cluster mode, shell commands, Python scripts and Python pipelines.

Total.js 5 can move work out of the main process in several ways: **worker threads** (`NEWTHREAD()`), **forked processes** (`NEWFORK()`), a **pool** of threads or forks (`NEWTHREADPOOL()`), a **cluster** of HTTP processes (the `cluster` option of the start script) and external programs (`SHELL()` and `PYPELINE()`). Everything here is built on the Node.js modules `worker_threads`, `child_process` and `cluster`, which the framework exposes as `F.Worker`, `F.Child` and `F.Cluster`.

## The `workers/` folder

A worker is a plain script in the `workers/` folder of the application. The name you pass to `NEWTHREAD()` or `NEWFORK()` is the file name without `.js`, so `NEWTHREAD('resize')` runs `workers/resize.js`. A name that starts with `~` is an absolute path: `NEWTHREAD('~/opt/scripts/resize.js')`.

```text
myapp/
├── index.js
├── controllers/
└── workers/
	└── calc.js
```

## A worker thread

The worker script loads the framework and calls `NEWTHREAD()` **without a name**. Inside a worker that returns the worker object `F.worker`, with the data from the main thread and the methods to talk back:

```js
// workers/calc.js
require('total5');

var worker = NEWTHREAD();

worker.message = function(msg) {
	var sum = msg.a + msg.b;
	worker.send({ sum: sum, user: worker.data.user });
};
```

In the main application `NEWTHREAD(name, [data])` starts the thread and returns the Node.js `Worker`. `data` is copied into the thread as `worker.data`:

```js
// controllers/default.js
exports.install = function() {
	ROUTE('GET /sum/', sum);
};

function sum($) {
	var thread = NEWTHREAD('calc', { user: 'Peter' });
	thread.on('message', function(msg) {
		$.json(msg);
		thread.kill();
	});
	thread.postMessage({ a: 1, b: 2 });
}
```

Messages go through the structured clone of Node.js: objects, arrays, strings, numbers, dates and buffers arrive as copies, functions do not. The thread runs with the same working directory as the application, so `PATH.root()` and the other paths point to the application root.

`F.worker` has these members:

| Member | Description |
| --- | --- |
| `worker.data` | The `data` passed to `NEWTHREAD(name, data)`, or `{}` |
| `worker.is` | `true` when the script runs as a worker (the argument `--worker`) |
| `worker.isfork` | `true` in a process from `NEWFORK()`, `false` in a thread |
| `worker.message` | Assign a function: it receives every message from the parent |
| `worker.send(msg)` | Sends a message to the parent (alias `worker.postMessage()`) |
| `worker.exit([code])` | Ends the process of the worker with the code (default `0`); aliases `kill()` and `close()` |
| `worker.setTimeout(ms)` | Ends the worker with code `1` after `ms` milliseconds; call it again to restart the countdown |

`setTimeout()` is a watchdog: call it when a job starts, and the worker ends itself if the job takes too long.

```js
worker.message = function(msg) {
	worker.setTimeout(10000);
	heavyjob(msg, function(err, response) {
		worker.send({ error: err ? err + '' : null, response: response });
	});
};
```

On the main side the returned object is a normal Node.js `Worker` (`on('message')`, `on('error')`, `on('exit')`, `postMessage()`, `terminate()`). The framework adds `kill()` and `exit()`, both of which call `terminate()`.

## A forked process

`NEWFORK(name)` runs the script from `workers/` in a new Node.js process (`child_process.fork()`) instead of a thread. A fork has its own memory and its own event loop, so a crash or a blocking job cannot affect the application. The script calls `NEWFORK()` without a name to get the same `F.worker` object:

```js
// workers/report.js
require('total5');

var worker = NEWFORK();

worker.message = function(msg) {
	worker.send({ id: msg.id, done: true });
};
```

```js
var fork = NEWFORK('report');

fork.on('message', function(msg) {
	if (typeof(msg) === 'string')
		return; // internal messages of the framework, e.g. 'total:init'
	console.log(msg);
	fork.terminate();
});

fork.postMessage({ id: 100 });
```

The returned object is a Node.js `ChildProcess`; the framework adds `postMessage()` (the same as `send()`) and `terminate()`, which kills the process with `SIGKILL`. Messages are serialized as JSON. A fork gets no `data` (`worker.data` is `{}`), so send the input as the first message. The working directory of a fork is the folder of its script, so `PATH.root()` inside a fork points to `workers/`. The framework in the fork sends the string `total:init` to the parent after it starts; skip string messages, as in the example.

## A pool of threads

`NEWTHREADPOOL(name, count, [isfork])` starts `count` threads of the same script at once (or `count` forks when `isfork` is `true`) and lends them to jobs one by one. The workers get no data, so `worker.data` is `{}` and the input goes in the messages. A job gets a free worker and a `release` function; until it calls `release()`, the worker is not given to another job. Jobs that arrive while all workers are busy wait in a queue.

```js
var pool = NEWTHREADPOOL('calc', 4);

pool.exec(function(worker, release) {
	worker.on('message', function(msg) {
		console.log(msg.sum);
		release();
	});
	worker.postMessage({ a: 5, b: 5 });
});
```

`pool.exec()` without a function returns a promise that resolves with the worker; call `worker.release()` when the job is done:

```js
var worker = await pool.exec();
worker.on('message', function(msg) {
	console.log(msg.sum);
	worker.release();
});
worker.postMessage({ a: 1, b: 1 });
```

Before a worker goes to the next job, the pool removes all its `message` listeners, so every job attaches its own. The pool is also stored in `F.workers[name]`, and `pool.workers` and `pool.pending` hold the workers and the waiting jobs. `pool.count` is the number of workers. A worker that exits (or crashes) is replaced by a new one, so the pool keeps its size.

## Cluster mode

A cluster runs the HTTP application in several processes that share one port. Set the `cluster` option in the start script to a number of processes, or to `'auto'`:

```js
// index.js
require('total5');

const options = {};
options.port = 8000;
options.release = true;
options.cluster = 4;
// options.cluster = 'auto';
// options.limit = 10;

Total.run(options);
```

The first process becomes the **master**. It prints a `CLUSTER` header (PID, versions, thread count, mode), starts the first process, waits until it has loaded, starts the others and then calls `options.callback(forks)` if you set it (the other processes may still be loading). Each process loads the whole application and listens on the shared port; Node.js spreads the connections among them. The master itself serves no requests.

| Option | Description |
| --- | --- |
| `cluster` | The number of processes, or `'auto'` |
| `limit` | With `'auto'`: the maximum number of processes |
| `tz` | The time zone of the processes (`process.env.TZ`), default `'utc'` |
| `logs` | `'isolated'` prints the cluster header even when the master runs under another process |
| `callback` | `function(forks)` called in the master after all processes have started |

All other options (`port`, `ip`, `config`, …) go to `F.http()` in every process. The processes run in release mode when `options.release` is `true` (the official start script sets it with `--release`) or `options.watcher` is `false`. Otherwise they run in debug mode and the master restarts all of them when a source file changes.

With `'auto'` the master starts one process and pings every process each 5 seconds. When the average answer takes longer than 70 ms it adds a process (up to `limit`); when the processes answer fast again it removes the last one, if it has fewer than two pending requests.

A process that exits is started again after one second. To restart all processes yourself, create an empty file named `restart` in the application directory: the master checks for it every 5 seconds, deletes it and restarts the processes one by one, two seconds apart. The master also writes the statistics of all processes into `<start script>.json` (for example `index.js.json`) about every 50 seconds.

Inside a process of the cluster:

```js
F.isCluster;   // true
F.isWorker;    // true
F.id;          // '1', '2', ... the identifier of the process
F.clusterid;   // the same identifier
```

The framework adds `F.clusterid` to the names of its temporary files, so the processes do not overwrite each other's files in `tmp/`.

## Messages between cluster processes

Every message a process receives arrives as the `$message` event. An object sent to the master with `process.send()` is passed by the master to all ready processes, the sender included. Use it to keep in-memory caches in sync:

```js
// definitions/sync.js
ON('$message', function(msg) {
	if (msg && msg.type === 'clearcache')
		MAIN.products = null;
});

// anywhere in a request
function update($) {
	if (F.isCluster)
		process.send({ type: 'clearcache', from: F.id });
	else
		MAIN.products = null;
	$.success();
}
```

Do not use the `TYPE` property in your messages and do not send strings that start with `total:`; the framework uses them for its own messages.

## Shell commands

`SHELL(cmd, [callback], [cwd])` runs a command in the system shell with `child_process.exec()`. With a callback you get `(err, stdout)`; without one it returns a promise with the standard output. The command runs in the application directory unless you pass `cwd`, and the config key `$shell` selects another shell (for example `/bin/bash`).

```js
SHELL('git rev-parse HEAD', function(err, stdout) {
	console.log(stdout.trim());
});

var files = await SHELL('ls -1', PATH.public());
```

## Python scripts

`F.python(filename, [callback])` runs a Python script once, in the folder of the script, and gives you its standard output. `F.pipinstall(name, [callback])` installs a Python package with `pip`. Both use the command from the config key `$python` (`python3` by default) and return a promise without a callback:

```js
await F.pipinstall('requests');
var output = await F.python(PATH.root('scripts/report.py'));
console.log(output);
```

For a script that keeps running and exchanges messages with the application, use a pipeline.

## Python pipelines

`PYPELINE(name, [options])` starts a `python3` process and talks to it through a Unix socket. `name` is a file in the `pypelines/` folder without `.py` (`PYPELINE('ocr')` runs `pypelines/ocr.py`), an absolute path with `~`, or inline Python code: a name that contains a new line, `;` or a quote is run with `python3 -c`.

The framework creates the socket in `tmp/` and passes its path to the script as the first argument (`sys.argv[1]`). Every message in both directions is a 4-byte big-endian length followed by the payload. By default the payload is JSON (with `type: 'text'` the `data` event gets a string, with any other `type` a buffer):

```python
# pypelines/upper.py
import sys, socket, struct, json

s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(sys.argv[1])

def read(n):
	data = b''
	while len(data) < n:
		chunk = s.recv(n - len(data))
		if not chunk:
			sys.exit(0)
		data += chunk
	return data

while True:
	size = struct.unpack('>I', read(4))[0]
	msg = json.loads(read(size))
	out = json.dumps({ 'text': msg['text'].upper() }).encode()
	s.sendall(struct.pack('>I', len(out)) + out)
```

```js
var py = PYPELINE('upper');

py.on('data', function(msg) {
	console.log(msg.text); // HELLO
});

py.send({ text: 'hello' });
```

Messages sent before the script connects wait and go out when it connects. The pipeline emits `open` when the script connects, `data` for every message, and `restart` when it starts the script again. With `autorestart: true` (the default) a script that ends is started again; `py.close()` stops it for good. When the application exits, the framework kills all running Python processes.

The full list of methods and options is in the reference of [Workers, threads and cluster](../../reference/workers-and-threads/). Scheduled jobs are described in [Scheduling and events](../scheduling-and-events/).
