# Database, queue and live updates

> How runs are queued, claimed, resumed and followed live, on Postgres.

Source: https://werker.cloud/docs/engineering/database-and-events (updated 2026-12-02)

How runs are queued, claimed, resumed and followed live.

## Postgres, with many workspaces

- Werker uses Postgres. An instance can hold many workspaces; hosted
  offerings are planned in
  [#77](https://github.com/werker-ai/werker/issues/77).
- The queue uses row-locking and live updates use LISTEN/NOTIFY.

## Work queue

Runs are rows in a table. Workers claim them with one statement, for
example (table and column names are illustrative):

```sql
UPDATE runs SET status = 'running', started_at = now()
WHERE id = (
  SELECT id FROM runs
  WHERE status = 'queued'
  ORDER BY queued_at
  FOR UPDATE SKIP LOCKED
  LIMIT 1
)
RETURNING id;
```

- `FOR UPDATE SKIP LOCKED` lets several workers claim at once: a row
  locked by one claimant is skipped by the others, so none block and
  none get the same row.
- A trigger on insert calls `pg_notify('runs_queued', '')`. Workers
  `LISTEN` on that channel and drain the queue when notified.
- A fallback poll every 30 seconds drains the queue as well
  (`packages/runtime/src/worker.ts`).
- On start and after every reconnect a worker drains once.

## Durable runs

Each run's Pi Durable state is in Postgres, in the `durable` schema:
Pi's own tables (conversations, entries, tasks, submissions, documents
and their revisions) with the columns of Pi's SQLite storage, keyed by
run and scoped to the workspace by row-level security. The storage is
`packages/runtime/src/run/durable/`; its SQL is in
`packages/db/src/durable/`.

- Each commit is one transaction. It takes a share lock on the run's
  row and is refused when `runs.attempts` is no longer the writer's
  claim, so a worker that lost its claim cannot write over the next
  one.
- A lost connection, a server restart, a serialization failure or a
  deadlock is retried, eight tries over about 11 seconds, before Pi
  ends the run.
- The state is deleted once the run is done, failed or cancelled: by
  the worker when it stops running the run, and by a sweep every 10
  minutes (`durable_state_runs()`). A run waiting for input keeps it.

A workflow is one durable task (`werker.workflow` in
`packages/runtime/src/workflow.ts`): each step is an agent in a child
conversation the task owns, earlier steps' outputs are added to the
next step's prompt, and the checkpoint holds the step index, the
outputs so far and the current step's conversation ID. A run's lease
is 30 seconds; when a worker dies, another claims the run again (the
attempt number goes up) and the run resumes from its storage.

Model keys are stored sealed in `secrets` (see
[integrations](integrations.md)). The worker holds only
`WERKER_SECRET_KEY`, opens a run's key when the run starts and passes
it to pi-ai, whose environment lookup is off. A model the connection's
adapter does not list is refused when the run is queued.

## Running several runs at once

Settings live in the database; workers re-read them whenever they look
for work. An instance admin sets them in Admin → Sandboxes. The app
role can read them but not write them: the web app changes them
through `update_instance_settings()` after checking the user is an
instance admin.

- `instance_settings` (one row):
  - `worker_concurrency`: runs one worker executes at once (default
    1). A machine can override it with `WERKER_WORKER_CONCURRENCY`,
    since it depends on that machine's size.
  - `default_workspace_run_limit`: the running-runs cap for workspaces
    without their own; none by default.
  - `sandbox_max_running`: most sandboxes at once on the sandbox host,
    counting running runs and waiting runs whose sandbox keeps
    running; none by default.
- `workspace_limits`, set with
  `pnpm db:workspace-limit --workspace <slug> --max-running-runs <n>`
  (or `--clear`): one workspace's cap.
- The cap counts running runs with a live lease across all workers.
  `claim_next_run()` skips runs of workspaces at their cap and claims
  the oldest other run; claims take a transaction lock so two workers
  cannot overshoot a cap. Each run gets its own sandbox, so the cap
  also bounds a workspace's sandboxes.
- Leases are 30 seconds, renewed every 10.

## Live updates (pub/sub)

1. A table trigger calls `pg_notify` on a channel. The payload can
   name a key, such as a run ID.
2. Each process holds one dedicated `LISTEN` connection and dispatches
   notifications to the handlers registered for each channel.
3. A handler bumps a version counter for the key, debounced so a burst
   of changes causes one wake.
4. A stream waiting for that key wakes and re-reads from the database,
   then sends the result to the browser.

A notification signals that something changed; the data is read with a
query.

### What is live in the web app

Both streams are woken by `NOTIFY` and send only what a query under
the workspace's row-level security returned:

- **A workspace's runs and decisions** (`/runs/activity`, server-sent
  events with a `runs` and a `decisions` feed, read through
  `workspace_activity` in
  `apps/app/src/lib/run/workspace-activity.ts`). The triggers in
  `packages/db/sql/001_schema.sql` notify `workspace_runs` with the
  workspace ID when a run is queued, changes status, gets its agent or
  workflow, or reports a step; lease renewals do not notify.
  `follow_runs` in `packages/core/src/feeds/run-feeds.ts` re-reads the
  latest 50 runs and sends the list only when it differs. The sidebar,
  header, run notices, dashboard and decisions page all read this one
  stream, so a browser tab holds one connection for it. The runs page
  shows one page of every run (`get_runs_page`) and reads it again
  when the stream reports a change (`follow_runs` in
  `apps/app/src/lib/run/follow-runs.ts`).
- **One run's events** (`/runs/[id]/events`, server-sent events), open
  only while that run is under way. It sends events after the last one
  the page has, not the whole list.

- **A factory's status** (`follow_factory_status` in
  `packages/core/src/factories/status.ts`, sent as `status` on a
  factory's and a room's activity stream). Woken by `workspace_runs`,
  `factory_messages_changed` and `factory_threads_changed`; re-reads
  with `read_factory_status` in `packages/db/src/factories/status.ts`.

### Which kind of stream a page uses

A stream holds a connection for as long as it is open, and a browser
allows six per host over HTTP/1.1, shared by every tab.

- **Always open, in the layout:** `/runs/activity`, one event stream
  for the workspace's runs and decisions. The layout subscribes for as
  long as the tab is open; pages that follow runs subscribe to the
  same store, so they open nothing more.
- **Not used for anything always open:** `query.live`
  (`watch_project_preview` in
  `apps/app/src/lib/remote/projects.remote.ts` uses it).
- **Opened by a page:** server-sent events from `event_stream`
  (`apps/app/src/lib/server/live/event-stream.ts`), read with
  `live_events` (`apps/app/src/lib/live-events.ts`), which closes the
  connection when the page is left. The page reads its data once with
  an ordinary query and then follows the stream. The factories index
  (`/factories/activity`), a factory (`/factories/[id]/activity`) and
  a room (`/factories/[id]/threads/[thread_id]/activity`) do this.

How the runs stream is shared and guarded:

- **One read per workspace and change.** Every stream following the
  same workspace in a web process shares one listener and one query
  per change (`SharedFeed` in
  `packages/core/src/feeds/shared-feed.ts`); the first stream starts
  it and the last one to close stops it.
- **Access is checked again.** Before a value is sent the session is
  read again, at most once a minute (`while_permitted` in
  `apps/app/src/lib/server/live/live.ts`). Signing out, losing the
  role or leaving the workspace ends the stream. The run-events stream
  is checked only when it opens; it closes when its run stops.
- **The dashboard opens no stream of its own.** Its numbers are a
  plain query (`get_run_overview`, `read_run_overview` in
  `packages/db/src/runs/overview.ts`) read again whenever the runs
  stream reports a change.

Workflow events carry what they are about in `run_events.data`
(`RunEventData` in `packages/domain/src/runs.ts`).

Limits:

- Each open tab holds one streaming connection, two on the page of a
  run that is under way. More tabs than the browser's six connections
  over HTTP/1.1 wait for a connection. Not handled in the app; HTTP/2
  is left to a reverse proxy.

## Retention

`instance_settings` holds `keep_run_detail_days` (default 90),
`keep_audit_days` (365) and `keep_ended_items_days` (30), set with
`update_retention_settings` and read in
`packages/db/src/retention.ts`; null keeps for ever. Once a day, and
at start, every worker calls `delete_expired_records()`
(`packages/runtime/src/loops/retention.ts`), which deletes
`run_events` and `observability.run_spans` of runs that ended more
than the run-detail days ago, `audit_events` older than the audit days
(their entities cascade), and `project_previews` and `starter_changes`
that ended or were discarded more than the ended-items days ago.
`run_usage`, `run_totals` and `run_steps` are not touched. Several
workers deleting at once is harmless.

## How LISTEN/NOTIFY behaves

- `LISTEN` belongs to a session, so it needs its own connection, not
  one from a pool.
- Notifications are fire-and-forget and are not replayed. Anything
  sent while a listener is disconnected is lost, so after reconnecting
  every handler is woken as if everything changed.
- Waiting streams also wake on a fallback timeout and re-read, in case
  a notification never arrived.

## Limits

- The pools have no `error` handler, so a dropped idle connection can
  end the process
  ([#6](https://github.com/werker-ai/werker/issues/6)).
