# HTTP API: Real-time Events (SSE & WebSocket)

Server-Sent Events (SSE) and WebSocket pub/sub protocol, command dispatch, wildcards, authentication, and the complete 86-event catalog.

Canonical: https://bunqueue.dev/api/http/realtime-events/

---

*[Interactive doc iso diagram: Stream 86 job/queue events live over SSE or dispatch commands over WebSocket - Zero polling: subscribe to GET /events for one-way browser feeds, or connect WS /ws for wildcard pub/sub plus JSON command execution - open the HTML page to view it.]*

4 real-time channels on port `6790`: **SSE** for one-way streaming and **WebSocket** for selective pub/sub plus JSON command dispatch.

| Protocol | Path | Scope |
| --- | --- | --- |
| SSE | `GET /events` | All typed events + periodic snapshots |
| SSE | `GET /events/queues/:queue` | Job events for `:queue` + periodic/dashboard events |
| WebSocket | `ws://host:6790/ws` | Selective pub/sub (86 explicit events + wildcards) and JSON commands |
| WebSocket | `ws://host:6790/ws/queues/:queue` | `job:*` scoped to `:queue` + non-job pub/sub + JSON commands |

## Server-Sent Events (SSE)

SSE emits named events matching WebSocket pub/sub names (`job:completed`, `queue:counts`, `stats:snapshot`, etc.). Job events include `id:` (`Last-Event-ID` resume) and JSON `data:` `{ queue, jobId, timestamp, error?, progress?, prev?, delay? }`.

- First frame is unnamed: `{ "connected": true, "clientId": "..." }`.
- `:heartbeat` comments stream every 30s; snapshots stream automatically (`stats:snapshot` 5s, `health:status` 10s, `storage:status` 30s).
- Attach listeners with `addEventListener` (`onmessage` receives only the initial unnamed frame).
- For `Authorization: Bearer <token>`, use `@microsoft/fetch-event-source` (native `EventSource` cannot send custom headers).

```javascript
const events = new EventSource('http://localhost:6790/events');
for (const name of ['job:completed', 'job:failed', 'queue:counts']) {
  events.addEventListener(name, (e) => console.log(`[${e.type}]`, JSON.parse(e.data)));
}
```

## WebSocket Pub/Sub & Commands

Pub/sub envelope: `{ "event": "job:completed", "ts": 1710000000000, "data": { "queue": "payments", "jobId": "abc-123" } }`.

### Subscribe & Unsubscribe

Send `Subscribe` after connecting for selective delivery, or `Unsubscribe` (`events: []` clears all):

```jsonc
{ "cmd": "Subscribe", "events": ["job:*", "queue:counts", "stats:snapshot"], "reqId": "1" }
// -> { "ok": true, "subscribed": ["job:*", "queue:counts", "stats:snapshot"], "reqId": "1" }
{ "cmd": "Unsubscribe", "events": ["job:progress"] }
{ "cmd": "Unsubscribe", "events": [] }
```

**Legacy mode:** Sockets that never send `Subscribe` receive all job events in flat `{ eventType: "completed", queue, jobId, ... }` format.

### Sending Commands

Send any [TCP protocol command](https://bunqueue.dev/api/tcp/) as JSON on the same socket:

```javascript
ws.send(JSON.stringify({ cmd: 'Pause', queue: 'emails', reqId: '2' }));
// -> { "ok": true, "reqId": "2" }
```

### Authentication & Disconnect Cleanup

- **Auth:** With `AUTH_TOKENS` set, send `Authorization: Bearer <token>` on the HTTP upgrade request (`401` before open; post-connect `{ "cmd": "Auth" }` does not replace handshake auth). Native browser `WebSocket` cannot set custom headers.
- **Disconnect cleanup:** Closing a socket releases eligible active deliveries owned by that client without charging an attempt. Renewed leases stay active until expiry/stall recovery; detached pulls are unaffected. Eligible `cron:` prevent-overlap deliveries are discarded on memory/SQLite (and on PostgreSQL unless dependency-protected, which uses ordinary transactional release).

### Complete Dashboard Example

```javascript
const ws = new WebSocket('ws://localhost:6790/ws');
ws.onopen = () => ws.send(JSON.stringify({
  cmd: 'Subscribe',
  events: ['job:*', 'queue:counts', 'stats:snapshot', 'health:status', 'worker:*', 'dlq:*', 'cron:*', 'queue:paused', 'queue:resumed'],
}));
ws.onmessage = (e) => {
  const msg = JSON.parse(e.data);
  if (msg.event === 'queue:counts') updateQueueRow(msg.data.queue, msg.data);
  else if (msg.event === 'stats:snapshot') updateOverviewCards(msg.data);
  else if (msg.event === 'dlq:added') showAlert(msg.data.jobId, msg.data.reason);
  else if (msg.reqId) handleCommandResponse(msg);
};
```

### Wildcard Patterns

| Pattern | Matches |
| --- | --- |
| `*` | Every emitted event |
| `job:*` | All 21 explicit job events (plus legacy `job:waiting` and `job:duplicated` bridge emissions; use `job:deduplicated` for exact deduplication subscription) |
| `queue:*` | All 10 queue events (including coalesced `queue:counts`) |
| `flow:*`, `config:*`, `batch:*`, `client:*`, `cleanup:*` | Both events in each namespace |
| `worker:*` | All 7 worker events |
| `dlq:*`, `cron:*`, `webhook:*` | All 6 events in each namespace |
| `storage:*` | All 5 storage events |
| `ratelimit:*`, `server:*` | All 4 events in each namespace |
| `concurrency:*` | All 3 concurrency events |
| `stats:*`, `health:*`, `auth:*`, `memory:*` | Single event in each namespace |

## Complete Explicit Event Catalog (86 Events)

Payload fields marked with `?` are included when available on that code path.

### Job Lifecycle (21)

| Event | Payload | Trigger |
| --- | --- | --- |
| `job:pushed` | `queue, jobId` | Job enqueued |
| `job:active` | `queue, jobId` | Worker claimed job |
| `job:completed` | `queue, jobId` | Job acknowledged |
| `job:failed` | `queue, jobId, error` | Job failed |
| `job:removed` | `queue, jobId, prev?` | Job cancelled or deleted |
| `job:promoted` | `jobId` | Delayed job promoted to waiting |
| `job:progress` | `queue, jobId, progress` | Progress updated (0-100) |
| `job:delayed` | `queue, jobId, delay` | Job delayed or scheduled for retry |
| `job:stalled` | `queue, jobId, stallCount?, action?` | Stall detected |
| `job:retried` | `queue, jobId, prev?` | Failed job retried |
| `job:discarded` | `jobId` | Job discarded to DLQ |
| `job:priority-changed` | `jobId, newPriority` | Priority changed |
| `job:data-updated` | `jobId` | Payload updated |
| `job:delay-changed` | `jobId, newDelay` | Delay updated |
| `job:timeout` | `queue, jobId, timeout` | Processing timeout exceeded |
| `job:lock-expired` | `queue, jobId, renewalCount` | Ownership lock expired |
| `job:deduplicated` | `queue, jobId, strategy` | Push matched an existing dedup key |
| `job:waiting-children` | `queue, jobId, dependsOn?` | Job waiting on dependencies |
| `job:dependencies-resolved` | `queue, jobId` | All dependencies completed |
| `job:moved-to-delayed` | `jobId, delay` | Active job explicitly delayed |
| `job:expired` | `queue, jobId, ttl, age` | Job TTL expired |

### Queue & Flow (12)

| Event | Payload | Trigger |
| --- | --- | --- |
| `queue:counts` | `queue, waiting, prioritized, active, completed, failed, delayed` | Coalesced (10ms window) count update after lifecycle activity; replaces per-queue polling |
| `queue:paused` | `queue` | Queue paused |
| `queue:resumed` | `queue` | Queue resumed |
| `queue:drained` | `queue, count` | Queued jobs drained |
| `queue:cleaned` | `queue, state, count` | Old jobs cleaned |
| `queue:obliterated` | `queue` | Queue destroyed |
| `queue:created` | `queue` | First job pushed to a new queue |
| `queue:removed` | `queue` | Queue removed |
| `queue:idle` | `queue, idleSeconds` | Queue empty for `QUEUE_IDLE_THRESHOLD_MS` (default `30000`) |
| `queue:threshold` | `queue, size, threshold` | Size exceeded `QUEUE_SIZE_THRESHOLD` (default `0` = off) |
| `flow:completed` | `parentJobId, queue, childrenCount` | All flow children completed |
| `flow:failed` | `parentJobId, failedChildId, queue, error` | Flow child failed terminally |

### DLQ & Cron (12)

| Event | Payload | Trigger |
| --- | --- | --- |
| `dlq:added` | `queue, jobId, reason` | Entry moved to DLQ |
| `dlq:retried` | `queue, jobId, count` | Single DLQ entry retried |
| `dlq:retry-all` | `queue, count` | All DLQ entries retried |
| `dlq:purged` | `queue, count` | DLQ purged |
| `dlq:auto-retried` | `queue, count` | Background auto-retry ran |
| `dlq:expired` | `queue, count` | Expired DLQ entries pruned |
| `cron:created` | `name, queue, pattern?, every?, nextRun` | Cron added |
| `cron:updated` | `name, queue, pattern?, every?, nextRun` | Cron updated |
| `cron:deleted` | `name` | Cron removed |
| `cron:fired` | `name, queue` | Cron pushed a job |
| `cron:missed` | `name, queue, error` | Cron missed execution window |
| `cron:skipped` | `name, queue, reason` | Tick skipped due to overlap or missing worker |

### Workers, Limits & Webhooks (20)

| Event | Payload | Trigger |
| --- | --- | --- |
| `worker:connected` | `workerId, name, queues, hostname?, pid?` | Worker registered |
| `worker:disconnected` | `workerId, name?, clientId?` | Worker unregistered or disconnected |
| `worker:heartbeat` | `workerId` | Worker heartbeat received |
| `worker:idle` | `workerId, processedJobs` | Worker reached zero active jobs |
| `worker:removed-stale` | `workerId, name` | Stale worker pruned |
| `worker:overloaded` | `workerId, name, activeJobs, concurrency, overloadedSeconds` | At max concurrency for `WORKER_OVERLOAD_THRESHOLD_MS` (`30000`) |
| `worker:error` | `workerId, name, failedJobs, processedJobs, failureRate` | Failure milestones (5, 10, 25, 50, 100) |
| `ratelimit:set` | `queue, max, duration?, ttl?` | Queue rate limit set |
| `ratelimit:cleared` | `queue` | Queue rate limit cleared |
| `ratelimit:hit` | `clientId` | Client exceeded protocol/HTTP rate limit |
| `ratelimit:rejected` | `queue` | Pull rejected by queue token bucket |
| `concurrency:set` | `queue, concurrency` | Queue concurrency limit set |
| `concurrency:cleared` | `queue` | Queue concurrency limit cleared |
| `concurrency:rejected` | `queue` | Pull rejected because concurrency slots were full |
| `webhook:added` | `id, url, events` | Webhook created |
| `webhook:removed` | `id` | Webhook deleted |
| `webhook:fired` | `webhookId, url, event` | Delivery succeeded |
| `webhook:failed` | `webhookId, url, event, error` | Delivery failed |
| `webhook:enabled` | `webhookId` | Webhook enabled |
| `webhook:disabled` | `webhookId` | Webhook disabled |

### Batch, Client, Config, Storage, Server & Periodic (21)

| Event | Payload | Trigger |
| --- | --- | --- |
| `batch:pushed` | `queue, total, inserted, duplicates` | Bulk push inserted >= 1 job |
| `batch:pulled` | `queue, count` | Batch pull delivered > 1 job |
| `client:connected` | `clientId, transport` | TCP client connected |
| `client:disconnected` | `clientId, transport` | TCP client disconnected |
| `auth:failed` | `clientId?` or `transport` | TCP or HTTP auth failed |
| `cleanup:orphans-removed` | `count` | Silent active jobs recovered as stalls |
| `cleanup:stale-deps-removed` | `count` | Stale dependency links pruned |
| `config:stall-changed` | `queue, config` | Stall config updated |
| `config:dlq-changed` | `queue, config` | DLQ config updated |
| `stats:snapshot` | `waiting, active, delayed, completed, dlq, totalPushed, totalCompleted, totalFailed, pushPerSec, pullPerSec, uptime, queues, workers, cronJobs` | Periodic snapshot every 5s |
| `health:status` | `ok, uptime, memory: { rss, heapUsed }, connections` | Periodic snapshot every 10s |
| `storage:status` | `collections, diskFull` | Periodic snapshot every 30s |
| `storage:backup-started` | `bucket` | S3 backup started |
| `storage:backup-completed` | `bucket, key` | S3 backup finished |
| `storage:backup-failed` | `bucket, error` | S3 backup failed |
| `storage:size-warning` | `sizeMB, thresholdMB` | SQLite DB exceeded `STORAGE_WARNING_MB` |
| `server:started` | `tcpPort, httpPort, shards` | Server listeners ready |
| `server:shutdown` | `signal` | Graceful shutdown initiated |
| `server:recovered` | `queues, jobs` | Persistent state recovered on startup |
| `server:memory-warning` | `heapUsedMB, thresholdMB, rssMB` | Heap exceeded `MEMORY_WARNING_MB` |
| `memory:compacted` | `{}` | Manual memory compaction finished |
