
# Background work and workers

A worker is your web image running another command, for work nobody should wait on, like confirmation emails. Declare it with `[service.worker] command`, queue jobs in Postgres, and make each safe to run twice. Success: `agc ship` passes `background work survives crashes and duplicate workers` and returns `"outcome": "live"`.

## Ask your agent

```text
When a parent books a camp spot, send the confirmation email from a background
worker instead of in the request, so a slow mail send never fails the booking.
```

## Steps

```toml
[service.worker]
command   = "node server/worker.ts"     # production
dev       = "npm run worker:dev"        # your mirror (optional; defaults to command)
instances = 2                           # production, 1 to 4 (default 1)
```

A migration for the queue:

```bash
agc migration new jobs
```

```sql
CREATE TABLE jobs (
  id bigserial PRIMARY KEY, kind text NOT NULL, payload jsonb NOT NULL,
  run_at timestamptz NOT NULL DEFAULT now(), attempts int NOT NULL DEFAULT 0,
  locked_until timestamptz, done_at timestamptz, last_error text
);
CREATE INDEX jobs_due ON jobs (run_at, id) WHERE done_at IS NULL;
```

Enqueue in the same transaction as the write the job belongs to:

```sql
BEGIN;
INSERT INTO bookings (id, camp_id, parent_id) VALUES ($1, $2, $3);
INSERT INTO jobs (kind, payload) VALUES ('booking_confirmation', jsonb_build_object('booking_id', $1));
COMMIT;
```

Claim one job with a 60-second lease (the worker loops on this):

```sql
UPDATE jobs SET locked_until = now() + interval '60 seconds', attempts = attempts + 1
 WHERE id = (SELECT id FROM jobs WHERE done_at IS NULL AND run_at <= now() AND (locked_until IS NULL OR locked_until < now())
             ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1)
RETURNING *;
```

On success, set `done_at = now(), locked_until = NULL`. On failure, clear the lease, push `run_at` out (the starter uses `2^attempts` seconds, capped at an hour) and keep `last_error`. To schedule work for later, insert the job with a future `run_at`. Delete done jobs once they're old, or `jobs` only grows: the starters' worker runs `DELETE FROM jobs WHERE done_at < now() - interval '30 days'` when it starts and once a day after, never when `AGC_RUN` is `rehearsal`. Then:

```bash
agc up --detach
agc migrate
agc check
agc ship
```

## How it works

**On your mirror.** `agc up` runs one worker process next to the app, from `dev` (or `command`). It gets the app's environment with `[service.worker] env` in place of the web's, and an empty `PORT`. When it exits, it restarts after 1 s, doubling to 30 s while it keeps dying quickly. One that ran over 30 s restarts after 1 s again. Its output goes to the mirror's log.

**In production.** Each release runs a `worker-v<N>` deployment with `instances` pods. The command runs under a shell wrapper that forwards SIGTERM to it. Once the new web version is live, older workers get SIGTERM and 60 seconds to finish the job in hand. Claim nothing new after SIGTERM. A ship that keeps or changes the worker follows the app's usual release policy. One that removes a live worker always goes to a person.

**Why a table, and why "safe twice".** A job inserted in the same transaction as its booking exists exactly when the booking does. With a lease, a worker that dies loses its claim and the job runs again. So a half-run job must not redo its effects: reuse the email `key`, and make every step before the send safe to repeat (offering a spot, charging, changing a status).

**Let the database sleep.** Each app's database suspends when idle and wakes in about a second. An idle worker should hold no connection and listen for nothing (no `LISTEN`). The starter polls every 10 s while it finds jobs, with a fresh connection per poll. Each empty poll doubles the wait, up to 10 minutes, and claiming a job drops it back to 10 s. A job a request queues doesn't wait for that: the starter's web process runs it just after it answers, with the worker's poll as the backstop, so an email goes out within a second or two. Only a job queued with no request behind it can wait up to the ceiling. The starter reads `WORKER_POLL_SECONDS` and `WORKER_IDLE_MAX_SECONDS`; those are the starter's names, not platform settings.

**How rehearsals test it.** A release with a worker is rehearsed twice, once calm and once under chaos. The second time, Agent Cloud kills the worker mid-job (twice), runs a second worker against the same jobs, and drops the answer to each message's first email send. The same flow steps must send the same mail both times. A duplicate or a lost message fails the release with `background work survives crashes and duplicate workers`, naming each address whose mail differed by its flow and step, with its calm and crashing counts (counts only, never message contents). In the crashing run each `MAIL` step waits 90 s past its `within`, room for a 60-second lease to lapse and the job to run again. Add `MAIL` steps to smoke flows so there's mail to compare ([Sending email](/docs/build/sending-email.md)).

## Reference

| `[service.worker]` key | Meaning |
|---|---|
| `command` | Production start command; without it there is no worker |
| `dev` | What `agc up` runs; defaults to `command` |
| `instances` | Production pods, clamped to 1 to 4; not a number means 1 |
| `cpu`, `memory` | Per-instance request, as for `[service.web]`; see [Sizing and capacity](/docs/targets/sizing-and-capacity.md) |
| `env` | Plain, non-secret variables for the worker only, e.g. `env = { BATCH_SIZE = "50" }`; secret-shaped values are refused with `ship.env_secret` |
| `build` | Must equal `[service.web] build`, or be absent |

## Errors

| code | exit | cause | fix |
|---|---|---|---|
| (check) `background work survives crashes and duplicate workers` | 11 | Flows sent different mail with workers killed and racing, or a flow failed under chaos | Reuse the email `key`; make every step before a send safe to repeat |
| `ship.worker_build` | 1 | `[service.worker] build` differs from the web's | Remove it, or make it match |


A CLI setup failure, before the operation runs: if the machine has an identity but the current folder has no manifest, `agc check` exits 1. Run it from the linked app folder, or initialize that repository.

```json
{
  "ok": false,
  "product": "agent.cloud",
  "command": "check",
  "error": {
    "retryable": false,
    "code": "app.not_linked",
    "message": "No agentcloud.toml in this directory or above it.",
    "fix": "Run `agc init` in the app repository.",
    "docs": "agc help onboarding"
  },
  "next": [
    {
      "cmd": "agc init",
      "why": "create the app on agent.cloud and write agentcloud.toml"
    }
  ]
}
```

## Limits

| What | Value |
|---|---|
| `instances` | 1 to 4 |
| Worker shutdown grace | 60 s |
| Workers on a mirror | 1 |
| Mirror restart backoff | 1 s, doubling to 30 s |

## Agent notes

- Send email from the worker, never in the request.
- A worker has no page. In production read it with `agc logs --process worker`: its lines, plus the platform's when it restarts or runs out of memory.
- `instances` above 1 only helps if claims use `FOR UPDATE SKIP LOCKED`; otherwise workers block each other.
- Don't fix a failed crash rehearsal by loosening the check. It's telling you a job isn't idempotent.

## Related

- [Sending email](/docs/build/sending-email.md)
- [Logs](/docs/ship/investigating-a-reported-problem.md#logs)
- [Rehearsals](/docs/concepts/rehearsals.md)
- [Migrations](/docs/data/migrations.md)
- [Workflow events and replay](/docs/build/workflow-events-and-replay.md)

<!-- feedback:start -->
---
Wrong, outdated or unclear? Run `agc feedback docs "build/background-work-and-workers: <what is wrong>" --body <file>` with the sentence quoted in the file. No code or app data is sent.
<!-- feedback:end -->
