---
title: Workers, threads and cluster
project: Total.js V4
version: 0.0.99
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/workers-and-threads/
updated: 2026-11-16T15:41:10.817Z
---

# Workers, threads and cluster

> Run code in worker threads and child processes, run shell commands, and run the app as a cluster or as separate threads.

A Total.js 4 application runs in one Node.js process by default. When work is too heavy for that process, or when you want to use more CPU cores, the framework gives you four tools:

| Tool | What it starts | Typical use |
| --- | --- | --- |
| `NEWTHREAD()` | A `worker_threads` thread from `/workers/` | CPU-heavy code that shares the process |
| `NEWFORK()`, `WORKER()`, `WORKER2()` | A child process from `/workers/` | Isolated jobs, scripts that may crash |
| `SHELL()` | A shell command | Running system tools (`convert`, `git`, `tar`) |
| Cluster (`options.cluster`) | Several instances of the whole app | Serving HTTP on more cores |

The `/threads/` directory is a different feature: it splits one project into several separate apps that run behind the main one (see the last part of this guide).

## The /workers/ directory

Worker scripts live in `/workers/` (the config key `directory_workers`, default `/workers/`). `PATH.workers('resize.js')` returns the full path of a file in it. You pass the name without `.js`. A name that starts with `@` points to a package (`PATH.package()`), and for `NEWTHREAD()` and `NEWFORK()` a name that starts with `~` is an absolute path to the script.

## NEWTHREAD() and NEWFORK()

`NEWTHREAD(name, [data])` runs `/workers/{name}.js` as a Node.js `worker_threads` thread and returns the `Worker`. `data` reaches the thread as `workerData`. `NEWFORK(name)` runs the same kind of file as a child process and returns the `ChildProcess`. Both objects get the same methods, so the calling code does not change when you switch:

```js
var worker = NEWTHREAD('resize', { quality: 90 });

worker.on('message', function(msg) {
	console.log('Done', msg);
	worker.kill();
});

worker.postMessage({ filename: PATH.public('photo.jpg') });
```

On a thread, `kill()` and `exit()` call `terminate()`. On a fork, `postMessage()` is `send()` and `terminate()` sends `SIGTERM`.

## The worker side

Inside the worker file, require the framework and call `NEWTHREAD()` (or `NEWFORK()`) **without a name**. It returns a small helper object that works the same in a thread and in a fork:

```js
// /workers/resize.js
require('total4');

var worker = NEWTHREAD();

worker.message = function(msg) {
	// worker.data contains the "data" argument of NEWTHREAD()
	worker.send({ filename: msg.filename, quality: worker.data.quality });
	worker.exit();
};

// Kill the worker if it runs longer than 30 seconds
worker.setTimeout(30000);
```

| Member | What it does |
| --- | --- |
| `worker.data` | The `data` of `NEWTHREAD(name, data)`; an empty object in a fork |
| `worker.message` | Assign a function; it receives every message from the parent |
| `worker.send(msg)` | Sends a message to the parent (alias `postMessage`) |
| `worker.exit([code])` | Ends the worker (aliases `kill`, `close`) |
| `worker.setTimeout(ms)` | Ends the worker with code `1` after `ms` milliseconds |

If the worker needs your schemas, modules or config, call `LOAD()` in it. `LOAD()` loads parts of the app without starting the HTTP server and sets `isWORKER` to `true`:

```js
require('total4');

LOAD('config,modules,schemas', function() {
	var worker = NEWFORK();
	worker.message = function(msg) {
		worker.send(msg);
	};
});
```

## Thread pools

`NEWTHREADPOOL(name, count, [isfork])` starts `count` workers of the same file and lends one to each job. `pool.exec(fn)` calls `fn(worker, release)` when a worker is free. Call `release()` when the job is done, or the worker stays busy:

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

function resize(filename, callback) {
	pool.exec(function(worker, release) {
		worker.on('message', function(msg) {
			release();
			callback(null, msg);
		});
		worker.postMessage({ filename: filename });
	});
}
```

The pool removes the `message` listeners of a worker before it gives it to the next job.

## WORKER() and WORKER2()

`WORKER(name, [timeout], [args])` is the older way to fork `/workers/{name}.js`. It returns the `ChildProcess`, stores it in `F.workers` while it runs, and kills it with `SIGKILL` when `timeout` (milliseconds) passes. The worker uses `process.on('message')` and `process.send()`, or the helper of `NEWFORK()`.

`WORKER2(name, [args], callback, [timeout])` runs the script silently, collects its standard output, and calls `callback(err, buffer)` when the process ends. Use it for scripts that print a result.

## SHELL()

`SHELL(command, [callback], [cwd])` runs a command with `child_process.exec()` in the app directory (or `cwd`). The callback gets `(err, stdout, stderr)`. Without a callback it returns a promise of the standard output. The config key `default_shell` chooses the shell:

```js
var output = await SHELL('git rev-parse HEAD');
```

Never put user input into the command without escaping it.

## Cluster

Set `options.cluster` in the start script to run several instances of the whole app behind one port. The value is a number of instances or `'auto'`:

```js
// index.js
const options = {};
options.cluster = 4;
// options.cluster = 'auto';
// options.cluster_limit = 8;
// options.tz = 'Europe/Bratislava';
require('total4/release')(options);
```

The main (master) process starts the instances one after the other. Each instance gets `F.id` (`'0'`, `'1'`, ...) and `F.isCluster === true`. An instance that exits is started again after one second. With `'auto'`, the master starts one instance, measures their response time every five seconds, adds an instance when the average is over 70 ms (up to `cluster_limit`) and removes the last one when there is free capacity.

In cluster mode the master sets the time zone of all instances to `options.tz`, or to `'utc'` when you do not set it. Sessions are shared between instances automatically; the cache (`CACHE()`, `F.cache`) only when `allow_cache_cluster` is `true`.

The master writes its state to `index.js.json` (the start script name plus `.json`) about every 50 seconds. To restart all instances without stopping the app, create an empty file named `restart` in the app directory; the master restarts the instances two seconds apart and deletes the file.

## Messages between instances

`F.cluster.emit(name, [a], [b], [c], [d], [e])` raises the event `name` in **every** instance, the sender included. Listen with `ON()`:

```js
ON('products_changed', function(id) {
	CACHE('products', null);
});

F.cluster.emit('products_changed', '123');
```

`EMIT2()` also reaches the other instances (see [Scheduling and events](../../guides/scheduling-and-events/)). `F.cluster.master(name, ...)` sends an event to the master process only, where `F.cluster.on(name, fn)` registers the listener. The arguments travel as IPC messages, so send only plain, serialisable values.

## The /threads/ directory

Set `options.threads` in the start script, and each subdirectory of `/threads/` becomes its own app in its own process:

```js
const options = {};
options.threads = '/api/';
// options.logs = 'isolated';
require('total4/release')(options);
```

For `/threads/users/` the main app forwards every request under `/api/users/` to that thread and removes the prefix, so the thread declares `ROUTE('GET /')` for `/api/users/`. With `options.threads = true` the prefix is only the thread name (`/users/`). The global `THREAD` holds the name inside the thread.

A thread loads every `.js` file of its directory (also in subdirectories) the way it loads controllers, with `exports.install`. It skips the root `/controllers/` and `/middleware/` but loads the other shared directories (schemas, modules, definitions...). It reads its own `config`, `config-debug`, `config-release` and `.env` files from its directory, its views from `views/` and static files from `public/`. With `options.logs = 'isolated'` its output goes to `/threads/{name}/logs/debug.log`. When you also set `options.cluster`, every thread runs as a cluster of that size.
