# Monitoring, backups and upgrades

> Operate a self-hosted pushq server: health checks, Prometheus metrics, logging, leader election, task retention, backups and upgrades.

Source: https://pushqueue.dev/docs/self-hosting/operations/

This page covers what you need once pushq is running: probing it, monitoring it, keeping it highly available, backing it up and upgrading it.

## Health and readiness checks

| Endpoint | Auth | Answers | Use it for |
|---|---|---|---|
| `GET /healthz` | none | `200` with body `ok` while the process is up. Doesn't touch the database. | Liveness probes: restart the process if this fails. |
| `GET /readyz` | none | `200` with `{"role": "...", "dialect": "..."}` when the database answers a ping; `503` with a problem+json body (`"detail": "database unreachable"`) when it doesn't. | Readiness probes and load balancer health checks. |

```bash
curl -s http://localhost:8080/readyz
```

```json
{"role":"leader","dialect":"postgres"}
```

`dialect` is `sqlite` or `postgres`. `role` says what this replica's dispatcher is doing:

| `role` | Meaning |
|---|---|
| `leader` | This replica runs the dispatcher. A SQLite server is always `leader` once started. |
| `follower` | Another replica holds the dispatcher lock. This one still serves the full API. |
| `stopped` | The dispatcher has shut down (the process is exiting). |

A `follower` is healthy. Don't take followers out of the load balancer: every replica serves the API.

Use `/readyz` for Kubernetes readiness probes and `/healthz` for liveness probes:

```yaml
livenessProbe:
  httpGet: { path: /healthz, port: 8080 }
readinessProbe:
  httpGet: { path: /readyz, port: 8080 }
```

`GET /v1/version` (any API key) returns `{"version", "commit", "dialect"}`, and `pushq version` prints the same for a binary.

## Prometheus metrics

`GET /metrics` serves Prometheus metrics. It is public by default; set `metrics.public: false` (or `PUSHQ_METRICS_PUBLIC=false`) to require an admin API key or a dashboard session. In [SaaS mode](https://pushqueue.dev/docs/self-hosting/saas-mode/) with metrics not public, only the operator's config-file keys can read it.

```yaml
# prometheus.yml
scrape_configs:
  - job_name: pushq
    static_configs:
      - targets: ["pushq-a:8080", "pushq-b:8080"]
    # with metrics.public: false
    # authorization: { credentials: pq_admin_... }
```

The metrics are aggregate on purpose: there are no per-queue labels, because a server with 10,000+ dynamic queues would explode label cardinality. For per-queue numbers use `GET /v1/queues/{queue}/stats`.

| Metric | Type | Labels | Meaning |
|---|---|---|---|
| `pushq_dispatches_total` | counter | `code_class`: `2xx`, `3xx`, `4xx`, `5xx`, `error` | Delivery attempts by response class. `error` means no HTTP response (timeout, connection, DNS, TLS, or a request that couldn't be built). |
| `pushq_dispatch_errors_total` | counter | `error_kind`: `non_2xx`, `timeout`, `connect`, `dns`, `tls`, `config` | Failed delivery attempts by cause. |
| `pushq_dispatch_duration_seconds` | histogram | none | Delivery round-trip latency, default Prometheus buckets. |
| `pushq_dispatch_inflight` | gauge | none | Deliveries currently in flight. Compare with `dispatcher.global_concurrency`. |
| `pushq_tasks_claimed_total` | counter | none | Tasks leased by the dispatcher for delivery. |
| `pushq_task_retries_total` | counter | none | Failed attempts that were rescheduled for retry. |
| `pushq_tasks_dead_lettered_total` | counter | none | Tasks copied to a dead-letter queue after exhausting retries. |
| `pushq_leases_expired_total` | counter | none | Leases reclaimed by the sweeper because no result was recorded in time (for example after a crash). |
| `pushq_active_queues` | gauge | none | Queues the dispatcher is currently tracking. |

The endpoint also exposes the standard Go runtime (`go_*`) and process (`process_*`) collectors.

Only the replica that is `leader` dispatches, so dispatch metrics come from that replica. Sum across replicas in your queries so a leader change doesn't look like a drop.

Useful queries:

```text
# Delivery error ratio over 5 minutes
sum(rate(pushq_dispatches_total{code_class!="2xx"}[5m]))
  / sum(rate(pushq_dispatches_total[5m]))

# p95 delivery latency
histogram_quantile(0.95, sum(rate(pushq_dispatch_duration_seconds_bucket[5m])) by (le))

# Dispatcher saturation (alert when close to global_concurrency)
max(pushq_dispatch_inflight)
```

## Structured logging

Logs go to stderr. Choose the format and level in the config (see [logging settings](https://pushqueue.dev/docs/self-hosting/configuration/#logging)):

```yaml
log:
  level: info    # debug | info | warn | error
  format: json   # text | json
```

At `info` you get startup and shutdown messages, warnings (such as an unauthenticated server, or a lost leader lock) and errors. At `debug` you also get one line per HTTP request (`method`, `path`, `status`, `dur_ms`) and dispatcher detail. `pushq dev` always logs at `debug`.

## High availability and leader election

Run two or more replicas against one Postgres database for high availability. SQLite servers are single-node.

- **Every replica serves the API.** Enqueues, queue changes and reads work on any replica.
- **One replica dispatches.** Replicas compete for a session-level Postgres advisory lock. The holder becomes `leader` and runs the dispatcher; the rest are `follower` and retry the lock every 5 seconds.
- **Failover.** The leader pings its lock connection every 5 seconds. If that connection dies, the lock is gone and another replica takes over at its next attempt. On a graceful shutdown (`SIGTERM`), the leader releases the lock immediately.
- **Wakeups.** With Postgres, new tasks and queue changes reach the leader through `LISTEN`/`NOTIFY`, so a task enqueued on a follower is dispatched without waiting for a poll.

### Lease fencing

The lock is an optimization that avoids duplicate work, not what keeps delivery correct. Correctness comes from per-task leases:

1. When the dispatcher claims a task, it writes a fresh lease token and a lease expiry of `dispatch_deadline_seconds + dispatcher.lease_grace` (default grace 60s).
2. A delivery's result is recorded only if the task still carries that lease token. A stale worker, for example from a replica that lost leadership mid-delivery, can't overwrite a newer attempt.
3. Every `dispatcher.sweep_interval` (default 15s), the leader finds leases that expired without a result, records a `lease_lost` attempt, and retries or fails the task by its retry policy. The attempt counts toward `max_attempts`, because the request may well have reached your endpoint.

This is why blue/green deploys and crash failover are safe. It is also why delivery is at-least-once: make your handlers idempotent. See [at-least-once delivery](https://pushqueue.dev/docs/concepts/delivery/).

## Task retention and cleanup

The leader deletes finished tasks in the background, every `dispatcher.cleanup_interval` (default 60s), in batches. If a backlog remains, it runs again a second later instead of waiting a full interval.

| What | Kept for | Setting |
|---|---|---|
| Succeeded tasks and their attempts | 24h | `retention.succeeded` |
| Failed tasks and their attempts | 7 days | `retention.failed` |
| Deleted tasks (tombstones) | 1h | `limits.dedup_window` |
| Tasks removed by a purge | Deleted in the background right after the purge | none |

A finished or deleted task's ID stays reserved for at least `limits.dedup_window`, so retention shorter than the dedup window is extended to it. Longer retention means more rows to scan; size your database accordingly.

## Back up the database

All state lives in the database: queues, tasks, attempt history, dashboard accounts, sessions, invites, API keys and teams. The binary itself is stateless.

### Back up SQLite

The database runs in WAL mode, so copying only the `.db` file while the server runs can miss recent writes. Use SQLite's online backup, which is safe while pushq runs:

```bash
sqlite3 /var/lib/pushq/pushq.db ".backup '/backups/pushq-$(date +%F).db'"
```

Or stop the service and copy `pushq.db` together with any `pushq.db-wal` and `pushq.db-shm` files.

To restore, stop pushq, put the backup in place as `pushq.db` (removing stale `-wal` and `-shm` files), and start it.

### Back up Postgres

Use your normal Postgres tooling:

```bash
pg_dump --format=custom --file=pushq-$(date +%F).dump "postgres://pushq:secret@db/pushq"
pg_restore --clean --dbname="postgres://pushq:secret@db/pushq" pushq-2026-11-28.dump
```

Managed Postgres snapshots and point-in-time recovery work too.

:::note
Restoring a backup brings back tasks as they were at backup time. Tasks that were delivered after the backup may be delivered again, consistent with at-least-once delivery.
:::

## Upgrade to a new version

1. Read the [release notes](https://github.com/blissfulrays/pushq/releases) for the version you're moving to.
2. Back up the database.
3. Replace the binary or change the image tag, then restart. `pushq serve` applies any new database migrations on startup; each migration runs in its own transaction and is recorded in a `schema_migrations` table, so restarting is safe.
4. Check `GET /readyz` and `GET /v1/version` on each replica.

With several Postgres replicas, upgrade one replica at a time, or follow the [blue/green procedure](https://pushqueue.dev/docs/self-hosting/deploy/#zero-downtime-bluegreen-deploys). To apply migrations before you switch traffic, run the new binary's `pushq migrate -c pushq.yaml` first.

Pin an exact image tag (`:1.0.0`) in production so upgrades happen when you choose. `:latest` moves on every stable release and `:edge` on every release, prereleases included.

There is no `down` migration. To roll back to an older binary after a release that changed the schema, restore the backup you took in step 2.

## Read more

- [Deploy to production](https://pushqueue.dev/docs/self-hosting/deploy/): systemd, docker-compose and blue/green deploys.
- [Server configuration reference](https://pushqueue.dev/docs/self-hosting/configuration/): retention, dispatcher and metrics settings.
- [Retries and backoff](https://pushqueue.dev/docs/concepts/retries/): how failed deliveries are retried.
- [Dead-letter queues](https://pushqueue.dev/docs/concepts/dead-letter-queues/): where tasks go after their last attempt.
