# Durable queues and dead letters

**Last updated:** 2026-11-22T06:50:00-03:00 (UTC-3)

Durable queues hold background work that must survive a restart, a crash or a failing destination. A job is a PostgreSQL row: the gateway confirms it only after the row is committed, delivers it under a lease that a worker keeps alive with a heartbeat, retries it with a bounded exponential delay, and after its last attempt keeps it as a dead letter that an operator can inspect, send back or purge. Every replica runs the workers; the lease guarantees that a job is held by one worker at a time.

| Flag | Default | What it turns on |
| --- | --- | --- |
| `durable_queues` | `false` | The queue workers, the `log_delivery`, `alert_delivery` and `fx_refresh` workloads, the admin API under `/api/v1/admin/queues` and the console page **Settings → Durable queues**; an operator control under plan entitlements |

Three workloads run on the queues:

- **Log delivery**: a [log destination](/docs/features/observability/) batch that failed its two in-memory retries used to be dropped and counted. With `durable_queues` on, a batch that failed for a reason that may heal is queued instead and delivered later by any replica.
- **Alert delivery** (T168): an [alert channel](/docs/features/alerting/) delivery the outbox gave up on, after its own eight attempts, for a failure that may heal, is retried by the queue and then kept as a dead letter you can reprocess.
- **FX refresh** (T168): the [display currency](/docs/features/display-currency/) reference rates are fetched once per refresh slot for the whole deployment, with retries and a dead letter, instead of once per replica.

## How a job moves

```mermaid
stateDiagram-v2
    [*] --> ready: enqueue (committed)
    ready --> leased: claimed (attempt counted)
    leased --> done: handler succeeded
    leased --> delayed: retryable failure
    delayed --> ready: backoff elapsed
    leased --> ready: lease expired (worker crashed) / released on shutdown
    leased --> dead: permanent failure or last attempt
    dead --> ready: reprocess (operator)
    dead --> [*]: purge (operator) or retention
    done --> [*]: retention
```

- **Admission.** An enqueue is refused with `queue_full` when the queue already holds `max_depth` jobs that are waiting or dead-lettered. Dead letters count, so a destination that keeps failing cannot grow storage without bound: reprocess or purge them to make room. Admission takes a per-queue transaction lock, so the depth check is exact across replicas.
- **Durable confirmation.** An enqueue returns only after its transaction commits. A connection lost before `COMMIT` leaves no job. Code that writes its own rows can enqueue inside its own transaction, so the job exists exactly when those rows do.
- **Idempotency.** A job may carry an idempotency key, unique per queue. Enqueuing a known key admits nothing and returns the existing job, while that job is waiting, dead or kept as done (`completed_retention_hours`).
- **Lease and visibility timeout.** A worker claims a job with a lease of `visibility_timeout_seconds` and renews it every `heartbeat_seconds`. If the worker stops renewing it (the process crashed, hung or lost the database), the job is delivered again after the lease expires. A worker that lost its lease is stopped and cannot complete or fail the job any more. Claims use `FOR UPDATE SKIP LOCKED`, the same lease contract as batches and evaluation runs.
- **Attempts.** An attempt is counted when the job is claimed, not when it fails. A job whose worker crashes every time still reaches `max_attempts` and becomes a dead letter with the class `lease_expired`, instead of crashing workers forever.
- **Retries.** A retryable failure waits `backoff_base_seconds × 2^(attempt−1)`, capped at `backoff_max_seconds`, with jitter: the delay is uniform in the upper half of that step, so replicas that failed together do not retry together. A permanent failure dead-letters the job at once.
- **Error classes.** A failure is stored and logged as a short identifier (`timeout`, `unreachable`, `failed`, `rejected`, `denied`, `destination_removed`, `lease_expired`, `invalid_payload`), never as error text. Payloads never appear in logs.
- **Shutdown.** At SIGTERM a replica stops claiming jobs, without waiting for the drain delay. Jobs in flight get the shutdown deadline (`lifecycle.drain_delay` plus `lifecycle.shutdown_timeout`, counted from SIGTERM) to finish; past it they are cancelled and released, with the attempt they were charged refunded, so another replica takes them at once.
- **Payloads and retention.** A payload larger than `max_payload_bytes` is refused at enqueue. A done job keeps its metadata and idempotency key for `completed_retention_hours`, but its payload is erased when it completes. A dead letter keeps its payload for `dead_letter_retention_hours`, then it is deleted. Waiting jobs are never deleted by retention.

Delivery is at least once: when a handler's effect reached its destination but the answer was lost, the job runs again. Log records carry `request_id`, which a consumer can use to deduplicate.

## Enable

```yaml
features:
  durable_queues: true
  log_destinations: true # the log_delivery workload runs only while log destinations are on

durable_queues:
  poll_interval_ms: 1000
  log_delivery:
    max_depth: 1000
    max_attempts: 8
    max_payload_bytes: 1048576
    visibility_timeout_seconds: 60
    heartbeat_seconds: 15
    job_timeout_seconds: 30
    backoff_base_seconds: 5
    backoff_max_seconds: 900
    concurrency: 2
    completed_retention_hours: 24
    dead_letter_retention_hours: 168
  alert_delivery: {} # same fields and defaults as log_delivery
  fx_refresh: {}     # same fields and defaults as log_delivery
```

The `durable_queues` block is boot configuration: change it in the YAML (or the Helm values file) and restart. A value of 0 or an omitted field takes the default. The flag itself can also be changed at runtime through feature management (`feature_management`); turning it off stops the workers and the log-delivery hand-off but keeps the jobs, which resume when it is turned on again.

| Field | Default | Bounds | Meaning |
| --- | --- | --- | --- |
| `poll_interval_ms` | 1000 | 100–60000 | How often each replica looks for due jobs |
| `<queue>.max_depth` | 1000 | 1–1000000 | Waiting plus dead-lettered jobs; past it an enqueue is refused (`queue_full`) |
| `<queue>.max_attempts` | 8 | 1–100 | Deliveries, crashed ones included, before the dead letter. Captured per job at enqueue |
| `<queue>.max_payload_bytes` | 1048576 | 1024–16777216 | Largest payload accepted |
| `<queue>.visibility_timeout_seconds` | 60 | 5–3600 | Lease; an unrenewed job is delivered again after it |
| `<queue>.heartbeat_seconds` | 15 | 1–1800, at most half the visibility timeout | Lease renewal interval |
| `<queue>.job_timeout_seconds` | 30 | 1–3600 | Bound of one attempt; reaching it is a `timeout` failure |
| `<queue>.backoff_base_seconds` | 5 | 1–3600 | First retry step |
| `<queue>.backoff_max_seconds` | 900 | base–86400 | Largest retry step |
| `<queue>.concurrency` | 2 | 1–64 | Jobs of this queue one replica runs at once |
| `<queue>.completed_retention_hours` | 24 | 1–8760 | How long a done job keeps its metadata and idempotency key |
| `<queue>.dead_letter_retention_hours` | 168 | 1–8760 | How long a dead letter, payload included, is kept |

The queues are `log_delivery`, `alert_delivery` and `fx_refresh`; each has its own profile with the fields above (`durable_queues.<queue>.<field>`) and the same defaults and bounds.

## The log delivery workload

Each [log destination](/docs/features/observability/) keeps sending its batches as before: in memory, with two retries. When a batch still fails:

| Failure | Without `durable_queues` | With `durable_queues` |
| --- | --- | --- |
| Timeout, unreachable, HTTP 5xx, 408 or 429, sink replaced while sending | Dropped and counted | Queued as one job; `durably_queued` counts its records |
| HTTP 401/403 (`denied`) or 4xx/partial rejection (`rejected`) | Dropped and counted | Dropped and counted: retrying would fail the same way |
| Cloud credential unavailable | Kept in memory and retried | Unchanged |
| Queue full, payload too large, database down | — | Dropped and counted, with a `log_batch_queue_refused` warning |

A queued batch is keyed by its destination and content, so the same batch is queued once. Any replica delivers it through the destination's current configuration. On redelivery, a `denied` or `rejected` answer, or a destination that no longer exists (`destination_removed`), dead-letters the job at once; other failures are retried. While `log_destinations` is off, the jobs wait and spend no attempts. The log destination status (`GET /api/v1/admin/log-destinations`) reports `durably_queued` and `redelivered` record counts per destination.

Records are request metadata, never prompts or answers, but they do name users, keys and models: treat dead-letter inspection accordingly.

## The alert delivery workload

The [alert outbox](/docs/features/alerting/) sends each delivery itself, with eight attempts up to an hour apart, and then marks it `failed`. With `durable_queues` on:

| Last outbox attempt | Without `durable_queues` | With `durable_queues` |
| --- | --- | --- |
| Timeout, network error, HTTP 408, 429 or 5xx, credentials unavailable | `failed`; retried only by hand | `failed`, and queued as one job keyed by channel and alert |
| A permanent refusal (HTTP 4xx other than 408 and 429, or a refused destination) | `failed` | `failed`, not queued: it would fail the same way |
| Queue full or database down | — | `failed`, with an `alert_delivery_queue_refused` warning |

The job payload names the delivery only (`channel_id`, `alert_id`, `event`), never the URL, secret or message. A delivery is queued only after the outbox recorded it failed. The job holds the outbox row while it sends: a delivery retried by hand meanwhile (**Retry** on the alert channel) is not sent by the job, which then completes without sending, and a manual retry waits for a send in progress. A redelivery reads the alert again from its source and sends it through the channel's current configuration and signing secret; success marks the outbox row `delivered`. A removed or disabled channel dead-letters the job at once (`destination_removed`); a permanent refusal too; other failures are retried with the queue's backoff. While `alert_channels` is off the jobs wait. `subject` is the channel ID. A channel may receive a delivery twice (at least once): deduplicate by the `delivery_id` in the payload.

## The FX refresh workload

Without the queue every replica fetches the [reference rates](/docs/features/display-currency/) on its own `fx.refresh_interval` timer. With `durable_queues` on, each timer enqueues the fetch of the current slot (the time truncated to `fx.refresh_interval`) under the same idempotency key, so the first replica admits it and the others find it: one fetch per slot for the deployment. A failed fetch is retried with backoff and, past `max_attempts`, kept as a dead letter (`unreachable` or `storage_unavailable`); the stored day then ages into stale as before, never guessed. Every replica still reloads the latest stored day on its timer. A job is kept as done for `completed_retention_hours`; with a refresh interval longer than that, a slot could be fetched again after the done job is pruned, which only repeats the same read. While `fx_display` is off the jobs wait. `subject` is the source (`ecb`).

## Operate from the API or the console

Console page: **Settings → Durable queues** shows each queue's counts and profile, a **Queue profiles** table with the eleven bounds of every queue under their YAML names (from `durable_queues` in `GET /api/v1/admin/config`, read-only, restart to change), the dead letters with their error class and attempts, and, for roles that may manage them, **Inspect**, **Reprocess**, **Purge**, **Reprocess all** and **Purge all** (optionally limited to one error class).

| Permission | Roles | Grants |
| --- | --- | --- |
| `queues:read` | admin, viewer, operator | Queue counts and profiles; dead-letter metadata |
| `queues:manage` | admin, operator | Payload inspection, reprocess and purge |

Team roles have neither. Every inspection, reprocess and purge writes one audit row per job (`queue.dead_letter.inspect`, `queue.dead_letter.reprocess`, `queue.dead_letter.purge`) in the same statement as the change.

| Method and path | Permission | Purpose |
| --- | --- | --- |
| `GET /api/v1/admin/queues` | `queues:read` | Queues, profiles and counts (`ready`, `delayed`, `leased`, `dead_letters`, `done`) |
| `GET /api/v1/admin/queues/{queue}/dead-letters` | `queues:read` | Dead letters, newest first; `error_class`, `limit` (1–200, default 50), `cursor` |
| `GET /api/v1/admin/queues/{queue}/dead-letters/{id}` | `queues:manage` | One dead letter with the first 4096 bytes of its payload (audited) |
| `POST /api/v1/admin/queues/{queue}/dead-letters/{id}/reprocess` | `queues:manage` | Back to the queue with a fresh attempt budget, due at once |
| `DELETE /api/v1/admin/queues/{queue}/dead-letters/{id}` | `queues:manage` | Delete for good |
| `POST /api/v1/admin/queues/{queue}/dead-letters/reprocess` | `queues:manage` | Bulk reprocess |
| `POST /api/v1/admin/queues/{queue}/dead-letters/purge` | `queues:manage` | Bulk purge |

A bulk request selects explicit IDs or all dead letters, at most 500 per call, oldest first:

```json
{"ids": ["qj_0123456789abcdef0123456789abcdef"]}
```

```json
{"all": true, "error_class": "timeout", "limit": 100}
```

A bulk purge of `all` also needs `"confirm": true` (otherwise `400 confirmation_required`). The answer lists the jobs acted on:

```json
{"reprocessed": ["qj_0123456789abcdef0123456789abcdef"], "count": 1}
```

A dead letter as the list returns it:

```json
{
  "id": "qj_0123456789abcdef0123456789abcdef",
  "queue": "log_delivery",
  "subject": "siem",
  "state": "dead",
  "attempts": 8,
  "max_attempts": 8,
  "last_error_class": "timeout",
  "payload_bytes": 2048,
  "payload_sha256": "9f2c…",
  "reprocessed": 0,
  "idempotent": true,
  "enqueued_at": "2026-11-15T01:00:00Z",
  "available_at": "2026-11-15T01:42:10Z",
  "dead_at": "2026-11-15T02:10:00Z"
}
```

`subject` is the workload's label; for `log_delivery` it is the destination ID. Errors: `404 feature_disabled` with the flag off, `404 not_found` for an unknown queue or a job that is not a dead letter of it, `400 invalid_selection`, `401`/`403` for a missing or insufficient session, `503 storage_unavailable`.

## Upgrade notes

- Migration 155 creates `gateway_queue_jobs`. Migrate and upgrade every replica before turning the flag on: an older replica neither runs the workers nor hands log batches to the queue (its failed batches are still dropped and counted).
- With the flag off nothing changes: log destinations drop exhausted batches exactly as before, alert deliveries end `failed` and every replica fetches the reference rates itself.
- T168 adds the `alert_delivery` and `fx_refresh` queues and their YAML profiles; no migration. An older binary refuses the two profile keys in YAML and leaves their jobs in the table: remove the keys before rolling back. A recovered crash is delivered once more under a new lease, as for `log_delivery` (`TestQueueFXRefreshOncePerSlotPostgres`, `TestQueueAlertDeliveryAfterOutboxPostgres`).
