Worker deployment
About 2115 wordsAbout 7 min
This page covers worker_runtime_mode: server — the daemon and cron patterns. Spora has two runtime modes; the full three-configuration overview is in Deployment modes. For the zero-config browser-driven mode (worker_runtime_mode: client), see Client-worker mode.
In server mode, the agent worker is either a long-lived daemon (php bin/spora worker:run --daemon, supervised by Docker / systemd / supervisord) or a once-per-minute cron entry (php bin/spora worker:run --once --include-queue). The daemon is the canonical pick for VPS / Docker / classical-server operators; the cron variant fits VPS / CI / batch environments where a long-lived process is impractical.
Shared-host operators: cron isn’t really viable here. Most cPanels cap cron execution at 30–60 seconds. A long LLM response loop gets SIGKILLed mid-step and the row is left in a half-finished orchestrator state that the reaper then flags as orphaned. For shared hosts, client-worker mode (
SPORA_WORKER_RUNTIME_MODE=clientin.env) is the intended path — the browser drives tasks, no daemon required.
Cron Mode (VPS / CI / Batch, worker_runtime_mode: server)
* * * * * /usr/bin/php /path/to/spora/bin/spora worker:run --once --include-queue >> /path/to/spora/storage/worker.log 2>&1Each invocation:
- Claims one due
scheduled_runs_nextentry (aSELECT … FOR UPDATEinside a transaction, then anUPDATE … WHERE id = ?) and dispatches it — creating aQUEUEDtask, marking the entryDONE, and queueing the next occurrence - Claims the oldest
QUEUEDtask (lockForUpdate) - Sets it to
RUNNING - Processes it to completion — or parks it at
PENDING_APPROVAL/AWAITING_INPUT, aborts it at max steps, or fails it - Sweeps due Agent API callbacks
- Exits
Backlog (further due scheduled runs and queued tasks) is picked up by the next cron fire, one entry per minute.
The worker is also the Agent API’s webhook delivery path
A chat started with a callback_url gets an outbox row that the worker settles, so callback latency in this mode is bounded by your cron interval, not by the API request — that returns 202 immediately. --reap-only skips both the queue and this sweep (app/Console/Commands/WorkerRunCommand.php), so it never delivers a callback. A worker that is configured but not alive leaves chats QUEUED and callbacks undelivered with no error anywhere; see Agent API → Operational notes.
Timezone: The worker pins UTC internally before polling, so the host’s TZ environment variable or date.timezone PHP ini setting has no effect on schedule timing. Deployers on shared hosting do not need to configure their system clock — every due_at <= $now comparison happens against UTC. All timestamp columns on scheduled_runs and scheduled_runs_next are stored in UTC.
Limitation: A cron fire that lands while the previous worker is still running does not start a second worker — the single-instance lock is held by a live process, so the new invocation exits with “Another worker instance is already running.” The entry that fire would have claimed waits for the next one, so a task that regularly takes longer than a minute means most fires are skipped and the backlog drains slower than one entry per minute. For tasks that regularly exceed 1 minute, use daemon mode instead, or flip to client-worker mode (SPORA_WORKER_RUNTIME_MODE=client in .env) and let the browser drive the tasks.
Daemon Mode (VPS / Docker)
php bin/spora worker:run --daemonThe daemon polls both the QUEUED task queue and the scheduled_runs_next table every iteration, and sweeps due Agent API callbacks alongside them. It runs until SIGTERM or SIGINT.
Options (defined at app/Console/Commands/WorkerRunCommand.php:123-130):
| Flag | Default | Description |
|---|---|---|
--daemon / -d | on (if neither --once nor --reap-only) | Run as persistent daemon (exit on SIGTERM/SIGINT) |
--once | off | Process due scheduled_runs_next (and QUEUED tasks with --include-queue), then exit. Cron mode. |
--include-queue | off | With --once: also drain the QUEUED task queue in the same run |
--reap-only | off | Reap orphaned RUNNING tasks once, then exit. No queue processing. |
--limit / -l | 0 (unlimited) | Max QUEUED tasks to process per run (0 = unlimited) |
--sleep / -s | 500000 (μs = 0.5s) | Microseconds to sleep when the queue is empty |
--stale-minutes | 60 (config) | Minutes after which a RUNNING task is treated as orphaned (0 = disabled; omit to use config) |
--workers / -w | 0 (unlimited, config) | Max concurrent child processes (0 = unlimited). Daemon mode only |
--daemon, --once, and --reap-only are mutually exclusive (app/Console/Commands/WorkerRunCommand.php:285-309). If none is given, the command defaults to daemon mode.
Daemon + Docker Compose
worker:
build: .
command: php bin/spora worker:run --daemon
restart: unless-stopped
environment:
SPORA_WORKER_RUNTIME_MODE: 'server'
SPORA_SECRET_KEY: ${SPORA_SECRET_KEY}
SPORA_DB_HOST: ${SPORA_DB_HOST}
SPORA_DB_NAME: ${SPORA_DB_NAME}
SPORA_DB_USER: ${SPORA_DB_USER}
SPORA_DB_PASSWORD: ${SPORA_DB_PASSWORD}restart: unless-stopped restarts the container after host reboots or Docker daemon restarts, but not after the process exits due to a bug — use a process supervisor (see below).
Daemon + Systemd
[Unit]
Description=Spora Agent Worker
After=network.target
[Service]
ExecStart=/usr/bin/php /var/www/spora/bin/spora worker:run --daemon
Restart=on-failure
RestartSec=10
User=www-data
WorkingDirectory=/var/www/spora
[Install]
WantedBy=multi-user.targetRestart=on-failure restarts the daemon after any non-zero exit (crash, OOM kill), with a 10-second backoff. Combine with guard@.service or a process manager for precise memory/CPU limits.
Process Supervisor (supervisord)
[program:spora-worker]
command=php /var/www/spora/bin/spora worker:run --daemon
autostart=true
autorestart=true
numprocs=1
redirect_stderr=true
stdout_logfile=/var/log/spora-worker.logautorestart=true handles both crashes and unexpected exits. numprocs must stay at 1: a second daemon on the same host cannot acquire the single-instance lock and exits — see Concurrent Workers.
Stale Task Reaping
Tasks can be orphaned in RUNNING when a worker process is killed ungracefully (OOM, SIGKILL, server crash) between claiming a task and completing it.
The reaper sweeps RUNNING (and AWAITING_SUB_AGENTS) tasks whose lease has expired and whose updated_at is older than --stale-minutes, and marks them FAILED with error_code: WORKER_DISCONNECTED. Retry-chain rows are left alone, and --stale-minutes 0 disables the sweep entirely. It runs:
- Daemon mode: At startup, then every 5 minutes regardless of queue state
- Cron mode: At startup (before the drain loop)
Note: The reaper runs inside the queue drain loop in daemon mode — it is triggered every 5 minutes even when the queue is non-empty. This ensures orphaned tasks are cleaned up even during sustained high load.
The --stale-minutes value should exceed your worst-case LLM round-trip time. Set it generously (at least 5 minutes) to avoid false positives on slow providers.
A reaped task is retried when the agent asks for it. If the agent has retry_after_minutes and max_retries both above zero, the reaper arms the same automatic retry every other failure path arms: the row keeps error_code: WORKER_DISCONNECTED, gains a retry_after stamp, and the server worker picks the task up once that delay has elapsed. The failed run is re-run in place with its history intact — the same chain a rate limit produces. An agent without a retry policy is only marked FAILED, and the operator retries it by hand.
The message names the actor that vanished. The error_message the reaper writes says what disappeared: on a server-worker install the task reads “The worker running this task stopped before it finished. Click Retry to start a fresh attempt.”; in client-worker mode it reads “The browser driving this task disconnected. Click Retry to start a fresh attempt.” — there, the browser’s SharedWorker is the thing that disappeared.
A parent waiting on its children is left alone. A sub-agent’s parent sits in AWAITING_SUB_AGENTS while its children run, and it holds no lease of its own. The sweep only reaps such a parent once nothing below it is still running, still leased, or waiting on a retry of its own — so a parent whose child is about to be retried is not failed out from under it. When the whole chain below has gone stale, the parent is swept with them.
Client mode does not arm the retry. Only the server worker claims scheduled retries, so in client-worker mode the reaper marks the row
FAILEDand leaves the retry to the operator. See Client-worker mode.
Concurrent Workers
Only one worker can process a given task simultaneously — on MySQL, MariaDB and PostgreSQL the mechanism is the lockForUpdate() row lock in the claim transaction. On SQLite that row lock does not exist (the dialect compiles it away), and the exclusion comes from SQLite’s own write lock instead.
For multiple workers on the same machine:
- Daemon mode: Only one daemon can run per storage directory. A second daemon on the same host hits the same
storage/spora-worker.lock, prints Another worker instance is already running, and exits — it does not wait or retry. Multiple daemons therefore need separateSPORA_STORAGE_DIRvalues or separate hosts; across hosts the row lock, not the flock, is what makes them safe. - Cron mode: Running multiple identical cron entries is safe but wasteful — the
flocklock file means only one process runs at a time, the others exit immediately. Use a single cron entry instead. - Never run both daemon and cron workers against the same storage directory — the daemon reaper and cron drain race on the same queue, and the second one will fail to acquire the
flock. Pick one.
Single-Instance Enforcement
A flock() lock file at storage/spora-worker.lock prevents two worker processes (daemon or --once) from running against the same database at the same time (app/Console/Worker/WorkerLock.php:46-70, called from app/Console/Commands/WorkerRunCommand.php:262). If a second worker starts while the first is still running, it exits immediately with an error rather than competing for tasks. --reap-only skips the lock so multiple reapers can co-exist.
The worker writes its own pid into the lock file. A worker that finds the lock held by a pid that no longer exists takes it over instead of refusing to start — the lock outlives a crashed daemon because the daemon’s task:run children inherit the lock descriptor, and a new lock file is a new inode that those children cannot hold.
Who owns the lock is decided under a second lock file, storage/spora-worker.lock.takeover, so two workers starting at the same moment cannot each end up holding a lock.
Client mode skips this section. When
worker_runtime_mode: client,bin/spora worker:runexits with a docs-link error; the per-hostflockis not used. See Client-worker mode for the browser-driven equivalent.
PENDING_APPROVAL Tasks
Tasks in PENDING_APPROVAL status wait for human approval. There is no automatic timeout — the task remains paused indefinitely until the user approves or rejects the pending tool calls.
This is intentional: a human should make the decision, and the task can stay paused for as long as needed. If the task must be abandoned, delete it or set its status to FAILED in the database directly — POST /abort is not available in this status and answers 409. A hand-edited row keeps its pending_state and its PENDING_APPROVAL tool-call rows, and carries none of the failure_reason / error_code the reaper would have written.
Health Monitoring
Watch these signals of a healthy deployment (SQLite syntax — see footnote for MySQL/MariaDB):
-- Tasks stuck in QUEUED (queue not draining)
SELECT COUNT(*) FROM tasks WHERE status = 'QUEUED' AND created_at < datetime('now', '-5 minutes');
-- Tasks stuck in RUNNING (worker may be dead or stuck on LLM)
SELECT COUNT(*) FROM tasks WHERE status = 'RUNNING' AND updated_at < datetime('now', '-10 minutes');
-- API callbacks owed but never delivered (sweep not running)
SELECT COUNT(*) FROM api_callbacks
WHERE delivered_at IS NULL
AND next_attempt_at IS NOT NULL
AND next_attempt_at < datetime('now', '-10 minutes');Alert when any count is non-zero for more than 2 consecutive minutes. A non-zero callback count with an empty queue is the signature of a worker that is running but whose callback sweep is failing — check storage/spora.log for Agent API callback sweep failed.
MySQL / MariaDB: replace
datetime('now', '-N minutes')withNOW() - INTERVAL N MINUTE(e.g.NOW() - INTERVAL 5 MINUTE).
Environment Variables Reference
See Environment variables for the consolidated reference. Most variables can also be set in config.php (gitignored, shared-hosting friendly) using the same snake_case config keys, or via SPORA_* env vars, which override config.php. A value stored in the settings database overrides both. Example: SPORA_WORKER_STALE_MINUTES=90 env var overrides worker_stale_minutes: 60 in config.php.