# ADR 0010 — Operations and durable workflows on PostgreSQL

**Status:** accepted. **Date:** 2026-12-03.

## Context
Business applications need queues, durable events, long-running workflows, scheduling, idempotency, broadcasting,
observability, diagnostics and backup, without losing tenant isolation or
operability by agents.

## Alternatives considered
- **pg-boss / graphile-worker**: mature queues on PostgreSQL, but with their own connections, migrations and context
  model; they do not carry the tenant envelope or take part in the transaction of Fellow's `sql()`.
- **Temporal**: its workflow model is the reference, but it requires its own cluster (server, database, workers
  with an SDK) — a disproportionate operational cost for municipalities and small teams.
- **Inngest / Trigger.dev**: hosted services or additional servers; an external dependency for the core business
  flow.
- **BullMQ / broker (Redis, RabbitMQ)**: another persistent component to operate, with no transaction shared with the data.

## Decision
- **Queue in PostgreSQL itself**, on Bun.SQL: `fellow_jobs` with `FOR UPDATE SKIP LOCKED`, an expiring lease,
  exponential backoff, dead-letter and an idempotency key. `dispatch` writes within the current transaction:
  the job and the business data are committed or discarded together (outbox).
- **Durable events** use the same queue: `emitEvent` writes `fellow_events` and one delivery job per durable
  consumer, keyed `event:consumer`. Non-durable listeners remain synchronous.
- **Workflows by step replay**: each `ctx.step` records its result; after a suspension (sleep, signal, transient
  failure) the function is re-executed and completed steps return the recorded result. Compensations run in
  reverse order on failure or cancellation. Explicit versions protect in-flight instances.
- **Context is always explicit**: jobs, deliveries and workflows store the envelope (tenant, subject, roles,
  request id, traceparent) and run within it; RLS applies in workers as it does in requests. Operational tables are
  global (the worker has to claim jobs from all tenants); per-tenant queries filter explicitly.
- **Scheduling** by UTC cron with a key per schedule, tenant and minute: multiple workers never duplicate runs.
- **HTTP idempotency** declared in the contract (`idempotent`), with a body hash and a reservation before the handler.
- **Broadcasting over Server-Sent Events** (no WebSocket): authentication and permissions from the pipeline, channels always
  in the caller's tenant, sending after commit, Redis pub/sub for multiple instances.
- **OpenTelemetry through the neutral API**; the SDK is optional and loaded only when installed.
- **Local diagnostics**: errors grouped by fingerprint and `fellow diagnose` correlating request,
  jobs, events, audit, workflow, code and known causes.
- **Logical backups** with pg_dump and a SHA-256 manifest, run by a backup role with BYPASSRLS separate from the
  application role; restoring requires a human approval bound to the contents of the file.

## Consequences
- No new service to operate; throughput is bounded by PostgreSQL (thousands of jobs per minute), enough
  for the target audience. Larger volumes can swap the queue while keeping `defineJob`/`dispatch`.
- Delivery is at least once: handlers must be idempotent (`once`, keys, `on conflict`).
- Code outside `ctx.step` runs on every replay; the documentation and the generator make this rule explicit.
- Broadcasts have no delivery guarantee; clients reload state when reconnecting.

## Evidence
`packages/core/tests/operations.test.ts`, `broadcast.test.ts` and `packages/cli/tests/ops.test.ts`: outbox transaction and
rollback, retries and dead-letter, durable per-consumer deliveries, workflow replay and compensation,
early signals, scheduling without duplication across workers, HTTP idempotency, SSE across processes via Redis,
backup and verification. The `records` example routes documents through a real workflow.

## Conditions for reassessment
Volume above tens of thousands of jobs per minute, workflows with thousands of steps (expensive replay) or a need
for real-time delivery guarantees — cases for a dedicated broker or workflow engine behind the same APIs.
