# HTTP API: Monitoring, Workers & Dashboard

HTTP REST endpoints for health probes, stats, Prometheus metrics, memory compaction, storage health, worker registration, and dashboard snapshots.

Canonical: https://bunqueue.dev/api/http/monitoring/

---

*[Interactive doc iso diagram: Wire /healthz and /ready probes, scrape /prometheus, and inspect heap or storage - 18 telemetry endpoints: probes stay fast and public for Kubernetes/Docker, while /stats, /storage, and optional METRICS_AUTH protect internals - open the HTML page to view it.]*

All 18 operational endpoints: health probes, metrics, memory compaction, storage health (11), worker registration (4), and dashboard snapshots (3).

## Health & Liveness Probes

All probe routes skip authentication and HTTP rate limiting:

| Method | Path | Auth | Response |
| --- | --- | --- | --- |
| `GET` | `/health` | No | JSON health check (`503` with `status: "degraded"` and `storage` details if storage is degraded). |
| `GET` | `/healthz` | No | `200` `text/plain` `"OK"` (Kubernetes liveness). |
| `GET` | `/live` | No | `200` `text/plain` `"OK"` (liveness alias). |
| `GET` | `/ready` | No | `200` `{ "ok": true, "ready": true }`, or `503` when storage is degraded. |

```json
{
  "ok": true,
  "status": "healthy",
  "uptime": 86400,
  "version": "x.y.z",
  "queues": { "waiting": 150, "active": 12, "delayed": 30, "completed": 50000, "dlq": 3 },
  "connections": { "tcp": 8, "ws": 4, "sse": 2 },
  "memory": { "heapUsed": 45, "heapTotal": 64, "rss": 82 }
}
```

Memory values are in MB; `/health` reports `uptime` in **seconds**.

## Stats, Metrics & Diagnostics

| Method | Path | Auth | Description |
| --- | --- | --- | --- |
| `GET` | `/ping` | Yes | Returns `{ "ok": true, "data": { "pong": true, "time": 1700000000000 } }`. |
| `GET` | `/stats` | Yes | Full server counters, throughput rates, memory (MB), and internal collection sizes (`stats.uptime` is in **milliseconds**). |
| `GET` | `/metrics` | Yes | Lightweight JSON totals (`totalPushed`, `totalPulled`, `totalCompleted`, `totalFailed`). |
| `GET` | `/prometheus` | Optional | `text/plain; version=0.0.4` gauges, counters, and latency histograms. Public unless `METRICS_AUTH=true` (`503` if enabled with no `AUTH_TOKENS`). |
| `GET` | `/storage` | Yes | Storage health (`{ "ok": true, "data": { "diskFull": false, "error": null, "since": null } }`). |
| `POST` | `/gc` | Yes | Runs Bun GC and internal memory compaction (`compactMemory()`), returning `before` and `after` heap stats in MB. |
| `GET` | `/heapstats` | Yes | JSC heap breakdown: top 20 object types by count, internal collection sizes, and heap metrics. |

```bash
curl -H "Authorization: Bearer $TOKEN" http://localhost:6790/stats
curl -X POST -H "Authorization: Bearer $TOKEN" http://localhost:6790/gc
```

**`GET /stats` response shape:**

```json
{
  "ok": true,
  "stats": {
    "waiting": 150, "prioritized": 10, "delayed": 30, "active": 12,
    "dlq": 3, "completed": 50000, "waiting-children": 2,
    "totalPushed": 100000, "totalPulled": 99500, "totalCompleted": 98000, "totalFailed": 200,
    "uptime": 86400000, "cronJobs": 4, "cronPending": 4,
    "pushPerSec": 120, "pullPerSec": 118, "completePerSec": 117, "failPerSec": 1
  },
  "memory": { "heapUsed": 45, "heapTotal": 64, "rss": 82, "external": 2, "arrayBuffers": 1 },
  "collections": { "jobIndex": 1500, "completedJobs": 5000, "processingTotal": 12, "queuedTotal": 150, "temporalIndexTotal": 30 }
}
```

**Storage health & backups:**
- **SQLite:** `diskFull: true` rejects durable writes while in-memory work continues degraded.
- **PostgreSQL:** `error` and `since` report DB/projection degradation and `/ready` returns `503` until authority returns.
- **Memory-only:** no persistent storage health reported.
- **S3 backups:** configured via env vars; emit `storage:backup-started`, `storage:backup-completed`, and `storage:backup-failed` ([S3 Backup](https://bunqueue.dev/guide/backup/)).

## Workers

| Method | Path | Body | Response & Event |
| --- | --- | --- | --- |
| `GET` | `/workers` | none | `{ "ok": true, "data": { "workers": [...], "stats": { "total", "active" } } }`. |
| `POST` | `/workers` | `{ "name", "queues", "concurrency"?, "workerId"?, "hostname"?, "pid"?, "startedAt"? }` | Registers a worker. Broadcasts `worker:connected`. |
| `DELETE` | `/workers/:id` | none | Unregisters a worker (`404` if unknown). Broadcasts `worker:disconnected`. |
| `POST` | `/workers/:id/heartbeat` | `{ "activeJobs"?, "processed"?, "failed"? }` | Keeps registration alive and updates counters (body optional). |

```bash
curl -X POST http://localhost:6790/workers -H "Content-Type: application/json" \
  -d '{"name": "email-worker-1", "queues": ["emails"], "concurrency": 10}'
curl -X POST http://localhost:6790/workers/w-1/heartbeat -H "Content-Type: application/json" \
  -d '{"activeJobs": 3, "processed": 1500, "failed": 12}'
```

## Dashboard Snapshots

Aggregated read-only snapshots that replace N+1 dashboard polling:

| Method | Path | Query Params | Response Contents |
| --- | --- | --- | --- |
| `GET` | `/dashboard` | none | `stats`, `throughput`, `latency` (`averages: { pushMs, pullMs, ackMs }`, `percentiles: { push, pull, ack }` with `p50/p95/p99`), `memory`, `collections`, `workers` (capped at 100 + `truncated`), `crons` (capped at 100 + `truncated`), `storage`, optional `cluster` (PostgreSQL mode only), and `timestamp`. |
| `GET` | `/dashboard/queues` | `limit` (`1..500`, default `100`), `offset` (default `0`) | Paginated `{ name, waiting, delayed, active, dlq, paused }` rows plus `total`, `limit`, `offset`, `timestamp`. |
| `GET` | `/dashboard/queues/:queue` | `includeJobs=true` (optional) | All 8 paused-aware state counts, lifetime `totalCompleted`/`totalFailed`, `paused`, `priorityCounts`, `dlqPreview` (up to 10 entries), and (when `includeJobs=true`) up to 10 summaries per state (`waiting`, `active`, `delayed`, `paused`). |

In PostgreSQL mode, `GET /dashboard` includes a `cluster` inventory of registered brokers in the namespace (omitted in SQLite and memory modes):

```json
{
  "cluster": {
    "mode": "postgres",
    "namespace": "default",
    "brokerId": "pod-alpha",
    "staleThresholdMs": 30000,
    "nodes": [
      {
        "brokerId": "pod-alpha",
        "startedAt": 1705315200000,
        "heartbeatAt": 1705318795000,
        "uptimeMs": 3595000,
        "heartbeatAgeMs": 5000,
        "status": "online",
        "activeLeases": 4,
        "workers": 2,
        "isSelf": true
      }
    ]
  }
}
```

Each node's `status` is `"online"` or `"stale"` (`heartbeatAgeMs > staleThresholdMs`).

```bash
curl "http://localhost:6790/dashboard/queues?limit=50&offset=0"
curl "http://localhost:6790/dashboard/queues/emails?includeJobs=true"
```

> **Tip**
>
> For zero-polling live dashboards, pair an initial `/dashboard` fetch with `stats:snapshot`, `health:status`, and `queue:counts` over [WebSocket Pub/Sub](https://bunqueue.dev/api/http/realtime-events/).
