# Queues

## Introduction

While building your web application, you may have some tasks, such as processing an uploaded podcast, that take too long to perform during a typical web request. Laravel Bash's queue driver is the filesystem, and its lock is `mv`.

```text
storage/queue/pending/      jobs waiting to run
storage/queue/processing/   jobs a worker has claimed
storage/queue/failed/       jobs that failed or timed out
```

## Creating Jobs

```bash
./sail artisan make:job ProcessPodcast
```

A job is a function called `handle`, which gets the arguments it was dispatched with:

```bash
# app/Jobs/ProcessPodcast.sh
ProcessPodcast::handle() {
  local id=$1
  sleep 1
  if (( id % 7 == 0 )); then
    echo "Podcast $id is corrupt." >&2
    return 1
  fi
  Log::info "Processed podcast $id"
}
```

Returning anything other than 0 fails the job.

## Dispatching Jobs

```bash
dispatch ProcessPodcast 42
```

`dispatch` writes the job to a temporary file, then moves it into `pending/`:

```bash
printf -v id '%s-%s-%05d' "${EPOCHREALTIME/./}" "$BASHPID" "$RANDOM"
tmp=$(mktemp "$QUEUE_PATH/.dispatch.XXXXXX")
printf '%q' "$job" > "$tmp"
printf ' %q' "$@" >> "$tmp"
mv "$tmp" "$QUEUE_PATH/pending/$id.job"
```

- The file name starts with the time in microseconds, so `pending/` sorts oldest first, and the queue is first in, first out.
- `printf %q` quotes each argument so that Bash can read it back exactly, spaces and all.
- Writing elsewhere and moving the file in means a worker never sees half a job.

## Running the Queue Worker

```bash
./sail artisan queue:work --workers=4
```

### Claiming a job

Each worker loops over `pending/` and tries to move each job into `processing/`:

```bash
for file in "$QUEUE_PATH"/pending/*.job; do
  claimed="$QUEUE_PATH/processing/${file##*/}"
  mv "$file" "$claimed" 2> /dev/null || continue   # another worker got there first
  queue::run "$worker" "$claimed"
done
```

Four workers will see the same file at the same moment and all try to move it. A rename within one filesystem is a single `rename(2)` system call, which happens completely or not at all, so exactly one `mv` succeeds. The other three get "No such file or directory", and move on to the next job.

> [!WARNING]
> This only works when `pending/` and `processing/` are on the same filesystem. Across filesystems, `mv` copies and then deletes, which is not atomic. Don't put the queue on NFS.

### Running a job

Each job runs in its own `./artisan queue:handle` process, under `timeout`:

```bash
timeout "${QUEUE_JOB_TIMEOUT:-60}" ./artisan queue:handle "$file"
```

If it exits with 0, the file is deleted. Otherwise it's moved to `failed/`, with the exit code in its name. `timeout` exits with `124`, so a timed-out job is easy to spot:

```text
1796429649235062-141-28704.exit-1.job
1796429650114522-152-01733.exit-124.job
```

### Supervising the workers

`queue:work` starts the workers in the background, then supervises them with `wait -n -p`, which waits for any one child to exit and says which:

```bash
while :; do
  wait -n -p pid
  Log::warning "Worker ${worker_of[$pid]} (PID $pid) exited. Starting a replacement."
  queue::worker "${worker_of[$pid]}" &
done
```

Kill a worker with `kill -9` and a new one takes its place. That's what Supervisor is for in Laravel PHP.

## Dealing With Failed Jobs

```bash
./sail artisan queue:failed
./sail artisan queue:retry
```

`queue:retry` moves every file in `failed/` back into `pending/`, without the exit code.

## Trying It

The [Queues](/queues) example has buttons that dispatch jobs, and shows every worker claiming and finishing them as it happens. Open it in two tabs.

## Why not a FIFO?

`mkfifo` makes a named pipe, which looks like a queue. But when several workers read from one pipe, they can each get half a line. Writes are only atomic up to `PIPE_BUF` (4096 bytes on Linux), and a pipe forgets everything when nobody's reading, so jobs dispatched while the workers are down are lost. Files stay where you put them.
