# Workers

> A queue worker or any command that keeps running, on a machine of its own: restarted when it stops, moved to each new version, always on or only while there is work.

A worker is a command that keeps running: a queue worker that takes jobs from BullMQ or a database, a consumer of a message stream, a bot that waits for events. It runs on a machine of its own, apart from the replicas that answer visitors, made from the version of the app that is live, with the app's [environment variables](https://arrangic.com/docs/environment-variables.md). A supervisor of the platform runs as many copies of the command as you ask for, starts again any copy that stops, moves them to each new version you deploy, and gives them time to finish what they do before they stop.

A worker can run all the time, or stop when the queue is empty so that nothing is counted until there is work again.

## Add a worker

Open the app, **Settings**, **Workers**, **Add worker**:

| Field | What to enter |
| --- | --- |
| **Name** | Lower-case letters, digits and dashes, such as `emails` or `queue-high`. It tags the worker's lines in the logs |
| **Command** | One line, run from the root directory of the app without root rights, such as `node worker.js` or `npm run worker`. A script in your repository can hold more |
| **Processes** | How many copies of the command run on the worker's machine. Each takes jobs on its own |
| **Stop timeout** | How many seconds each copy gets to finish after it is asked to stop: 10 to 300, 30 unless you change it |
| **Runs** | **Always on**, or **Scale to zero** with how often the platform looks for new jobs |

The owner and the admins of the team add, change and remove workers. A member sees the workers, their states and their logs; the page says "Only team admins can add, change or remove workers."

The command cannot hold control or invisible characters. Unlike a cron job, a command or a deploy command, a worker's command runs without `set -e`: it decides its own exit code.

The dialog says what the worker costs before you save. A new or changed worker starts with the next redeploy, like a [variable](https://arrangic.com/docs/environment-variables.md) or a [size](https://arrangic.com/docs/scaling.md): the pill next to the app's status says **New workers**, and **Redeploy now** applies it.

## How a worker runs

- **On a machine of its own.** The [size and region](https://arrangic.com/docs/scaling.md) of the app, the image of the live version, the app's variables. Replicas are not touched, and a sleeping app stays asleep.
- **Nothing reaches it.** A worker has no address and gets no requests. It does its work through your queue, your database or an outside service.
- **Without root rights,** like the app. It can write in the folder of the app, in the home folder and in `/tmp`; nothing it writes outlives its machine.
- **With its lines in the logs.** Every line a copy prints appears under **Logs**, tagged with the worker and the copy: `[emails #2] sent order 4812`. The machine filter lists the worker's machine under its name. Lines of the supervisor start with `[supervisor]`; the level filter has a **Supervisor** entry that shows only those.
- **Counted like a replica,** by the second, at the price of the app's size, also for the monthly cap of the app. See [What it costs](#what-it-costs).

### Started again when it stops

A copy that ends, with any exit code, is started again. The wait before the start grows from one second to thirty, and goes back to one second once a copy has run for a minute. So a command that exits on purpose after a while, as `queue:work --max-time` does, is simply started afresh.

A copy that ends ten times within five minutes keeps crashing. The supervisor says so in the logs, waits five minutes before the next try, and the team gets the notification **App keeps crashing** with the worker's name and the exit code. The Workers page shows **Keeps crashing** since when, until a copy stays up again.

A copy that is ended by the system is said in the logs as likely out of memory: the copies share the memory of the worker's machine, which is the app's size.

### Each deployment moves the workers

When you deploy, the replicas take the new version first. Once they do, each worker's machine moves to the new version: every copy gets the stop signal, the stop timeout to finish, and starts again on the new code. You never run `queue:restart` yourself.

A worker that cannot run the new version fails the deployment, the same way a replica that does not start does: a copy that ends within ten seconds of starting marks the deployment as failed, its own last lines are in the deployment log, and the app keeps the version it had, workers included.

### Stopping

When a copy is asked to stop, for a deployment, a pause, a restart or a removal, it gets `SIGTERM`, then the stop timeout to finish its current job. A copy still running after the timeout is ended, and the logs say so. Give a worker whose jobs take long a longer timeout; 300 seconds is the most.

**Restart** under **More actions** restarts the workers along with the replicas. **Pause** stops them; **Resume** starts them again.

## Always on or scale to zero

| | Always on | Scale to zero |
| --- | --- | --- |
| The machine | Runs all the time | Stops when every copy has ended without an error, and starts again to look for work |
| Your command | Keeps running, or exits and is started again | Must end with exit code 0 once the queue is empty |
| A crash | Started again | Started again |
| New jobs | Taken at once | Taken when the worker is next started: at the interval you choose, or at once through the wake URL |
| Counted | The whole month | Only while it runs |

### Looking for new jobs

A worker that scales to zero is started by the platform every 1, 5, 15, 30 or 60 minutes, as you set under **Look for new jobs**. It works through the queue, ends, and the machine stops. A job queued in between waits at most that long. A start while the worker already runs changes nothing.

Each start that finds no work still runs for a few seconds; the dialog says what a day of such starts costs for the interval you pick.

### The wake URL

To have a job picked up within seconds, call the worker's wake URL right after queueing it. Every machine of the app has it in a variable named after the worker, `PLATFORM_WAKE_URL_` and the name in capitals with dashes as underscores: `PLATFORM_WAKE_URL_EMAILS` for `emails`, `PLATFORM_WAKE_URL_QUEUE_HIGH` for `queue-high`.

```js
await queue.add('send', { orderId });

await fetch(process.env.PLATFORM_WAKE_URL_EMAILS, { method: 'POST' });
```

The call is a `POST` with no body and answers `202` when the worker is starting. Calls within a few seconds of each other start it once, so a burst of a thousand jobs costs one start. The URL is a secret of the team's, like a [deploy hook](https://arrangic.com/docs/deployments.md#deploy-hook); the Workers page has a button that copies it, for code that runs elsewhere.

A call answers `409` with the reason when the worker has no machine yet (deploy once), when the app is paused, or when the team may not run apps. A URL of a worker that was removed answers `404`.

## Commands for common queues

Your worker code is ordinary: connect to the queue, take jobs, and stop taking jobs when `SIGTERM` arrives while finishing the current one. The platform's supervisor does the rest. A queue on a [Valkey](https://arrangic.com/docs/redis.md) cache belongs on one whose [eviction policy](https://arrangic.com/docs/redis.md#eviction-policy) is `noeviction`, the default, so no job is dropped when it is full.

### BullMQ

Always on: a worker that runs until it is asked to stop.

```js
// worker.js

const worker = new Worker('emails', sendEmail, { connection: { url: process.env.REDIS_URL } });

process.on('SIGTERM', async () => {
    await worker.close(); // finishes the job in hand, takes no new one
    process.exit(0);
});
```

Scale to zero: the same worker, ended once the queue has drained for a moment.

```js
// worker.js

const connection = { url: process.env.REDIS_URL };
const queue = new Queue('emails', { connection });
const worker = new Worker('emails', sendEmail, { connection });

worker.on('drained', async () => {
    const waiting = await queue.getWaitingCount();

    if (waiting === 0) {
        await worker.close();
        process.exit(0);
    }
});

process.on('SIGTERM', async () => {
    await worker.close();
    process.exit(0);
});
```

Command: `node worker.js`. Where the app queues a job, call the wake URL afterwards (see above).

### Bull, Bee-Queue and pg-boss

The shape is the same: create the worker, process jobs, close it on `SIGTERM`.

```js
// Bull
const queue = new Queue('emails', process.env.REDIS_URL);
queue.process(sendEmail);
process.on('SIGTERM', () => queue.close().then(() => process.exit(0)));

// Bee-Queue
const queue = new Queue('emails', { redis: { url: process.env.REDIS_URL }, isWorker: true });
queue.process(sendEmail);
process.on('SIGTERM', () => queue.close().then(() => process.exit(0)));

// pg-boss
const boss = new PgBoss(process.env.DATABASE_URL);
await boss.start();
await boss.work('emails', sendEmail);
process.on('SIGTERM', () => boss.stop({ graceful: true }).then(() => process.exit(0)));
```

For scale to zero, end the process when the queue is empty: Bull's `queue.getWaitingCount()`, Bee-Queue's `queue.checkHealth()`, pg-boss's `boss.getQueueSize('emails')`.

### Agenda

Agenda schedules jobs in MongoDB and needs one process running to run them; it fits **Always on** with one process.

```js
const agenda = new Agenda({ db: { address: process.env.MONGODB_URL } });
agenda.define('send email', sendEmail);
await agenda.start();
process.on('SIGTERM', () => agenda.stop().then(() => process.exit(0)));
```

### Several processes

Each copy runs your command once more with `PLATFORM_WORKER_COPY` set to its number (1, 2, 3) and `PLATFORM_WORKER_NAME` to the worker's name, so a copy can tell itself apart in the logs or take a queue of its own. Queue libraries share a queue between copies safely: no job runs twice.

### Laravel

A [Laravel](https://arrangic.com/docs/frameworks/laravel.md) worker uses the commands you know:

| Runs | Command |
| --- | --- |
| Always on | `php artisan queue:work --tries=3 --max-time=3600` |
| Always on, with Horizon | `php artisan horizon` |
| Always on, the scheduler | `php artisan schedule:work` |
| Scale to zero | `php artisan queue:work --stop-when-empty --tries=3` |

`queue:work` already stops after the current job on `SIGTERM`, and `--max-time` ends the process now and then so a code or memory leak never lasts; the supervisor starts it again. The queue lives in a database or a [Valkey](https://arrangic.com/docs/redis.md) cache the web replicas and the worker share: the `sync` driver runs jobs in the request, and the `database` driver on SQLite stays on one machine. The `database` driver on a [Postgres database](https://arrangic.com/docs/postgres.md) works, but a worker that polls it every few seconds never lets the database sleep, so its compute runs all month; a Valkey cache keeps the queue off the database. Keep a queue's cache at the [eviction policy](https://arrangic.com/docs/redis.md#eviction-policy) `noeviction`, the default: full, it refuses new jobs with an error your app sees, where a policy that drops keys could drop queued jobs without a word.

## What it costs

A worker's machine is counted like a replica: by the second, at the price of the app's size and region, and it counts as one more machine towards the app's monthly cap. An always-on worker runs the whole month, so it costs what one replica of the app's size costs at most. A worker that scales to zero is counted only while it runs: its starts and its jobs.

## Limits

- Worker processes per app, across all its workers: 2 on Hobby, 5 on Pro, 10 on Business; 1 during the trial. The dialog says how many are left.
- Stop timeout: 10 to 300 seconds.
- A worker uses the size of its app.

## Workers and cron jobs

A [cron job](https://arrangic.com/docs/cron-jobs.md) runs a command once, on a schedule, and its machine goes when the command ends. A worker keeps running, or is started again whenever there is work. Work that happens at a fixed time, such as a nightly report, is a cron job; work that arrives whenever visitors do, such as emails and webhooks, is a worker.

---

This page on the site: https://arrangic.com/docs/workers  
All pages of the documentation: https://arrangic.com/llms.txt
