# Deploy bunqueue on Kubernetes

Step-by-step guide to stateless bunqueue brokers on Kubernetes with PostgreSQL 17-19: diagrams, copy-ready YAML manifests, probes, graceful drains, TLS, and failover.

Canonical: https://bunqueue.dev/guide/kubernetes/

---

Run stateless bunqueue broker pods behind one Kubernetes `Service` backed by PostgreSQL 17-19—no Redis cluster, no broker StatefulSet, and zero lost jobs across restarts.

**The whole setup in 4 bullets**

- Two moving parts: a stateless bunqueue Deployment (start with 4 pods) and PostgreSQL 17-19.
- Zero manual migrations: the first pod creates or upgrades Schema v22 automatically on boot.
- Two critical env rules: set DATA_PATH="" and leave BUNQUEUE_BROKER_ID unset so crashed pods rejoin immediately.
- Verified from TLA+ (193.69M states) to 3-AZ Proxmox Jepsen (Porcupine LINEARIZABLE): 345,990 jobs + 200 multi-pod workflows across 10 chaos suites, 0 lost.

> **Tip: Try it live in your browser**
>
> Kill pods, partition a broker from PostgreSQL, trigger rolling updates, and watch lease fencing in the interactive [Kubernetes Cluster Simulator](https://bunqueue.dev/k8s-simulator/).

## How it works

Three stateless layers keep operations simple:

1. **Apps & workers** connect to one ClusterIP `Service` (`bunqueue:6789`).
2. **Broker pods** hold no local disk state—any pod accepts jobs, serves workers, and restarts cleanly.
3. **PostgreSQL 17-19** stores jobs, locks, retries, and schedules, synchronizing pods via `LISTEN/NOTIFY`.

*[Interactive k8s iso diagram: Your apps talk to one Service. PostgreSQL keeps all 4 pods in sync. - Simple mental model: because broker pods store no local disk state, you can scale them up, restart them, or lose a node without losing a single job - open the HTML page to view it.]*

## Step 1: Prepare PostgreSQL 17-19

Use any **PostgreSQL 17, 18, or 19** database (**19.0** recommended)—managed (RDS, Cloud SQL, Neon, Supabase) or [CloudNativePG](https://cloudnative-pg.io/). Each pod opens **5 connections** by default (`4` pooled SQL queries + `1` `LISTEN` channel): budget `replicas × (BUNQUEUE_POSTGRES_POOL_SIZE + 1)`.

*[Interactive k8s iso diagram: 1 broker pod = 5 PostgreSQL connections - Easy math: replicas × (BUNQUEUE_POSTGRES_POOL_SIZE + 1). Four pods use 20 connections total, comfortably inside PostgreSQL's default limit of 100 - open the HTML page to view it.]*

> **Tip: No migration job needed**
>
> On first boot, one pod acquires a brief schema lock, creates all tables and `Schema v22` indexes automatically, and sibling pods join immediately after.

**Optional: in-cluster PostgreSQL 19 manifest (staging/dev only)**

```yaml
# 00-postgres-dev.yaml (use managed PostgreSQL or CloudNativePG in production)
apiVersion: apps/v1
kind: StatefulSet
metadata: { name: postgres, namespace: bunqueue }
spec:
  serviceName: postgres
  replicas: 1
  selector:
    matchLabels: { app.kubernetes.io/name: postgres }
  template:
    metadata:
      labels: { app.kubernetes.io/name: postgres }
    spec:
      containers:
        - name: postgres
          image: postgres:19.0-alpine
          ports: [{ containerPort: 5432, name: pg }]
          env:
            - { name: POSTGRES_DB, value: bunqueue }
            - { name: POSTGRES_USER, value: bunqueue }
            - name: POSTGRES_PASSWORD
              valueFrom: { secretKeyRef: { name: bunqueue-secrets, key: postgres-password } }
          volumeMounts:
            # PostgreSQL 18+ / 19.0 images mount persistent storage at /var/lib/postgresql
            - { name: pgdata, mountPath: /var/lib/postgresql }
  volumeClaimTemplates:
    - metadata: { name: pgdata }
      spec:
        accessModes: [ReadWriteOnce]
        resources: { requests: { storage: 20Gi } }
---
apiVersion: v1
kind: Service
metadata: { name: postgres, namespace: bunqueue }
spec:
  selector: { app.kubernetes.io/name: postgres }
  ports: [{ name: pg, port: 5432, targetPort: pg }]
```

## Step 2: Create the namespace and secret

Store two keys in `bunqueue-secrets`: `postgres-url` (percent-encode special password characters like `@` or `/`) and `auth-tokens` (random bearer token shared by clients and workers):

```bash
kubectl create namespace bunqueue
AUTH_TOKEN=$(openssl rand -hex 32)

kubectl -n bunqueue create secret generic bunqueue-secrets \
  --from-literal=postgres-url="postgres://bunqueue:<password>@postgres.bunqueue.svc.cluster.local:5432/bunqueue?sslmode=require" \
  --from-literal=auth-tokens="${AUTH_TOKEN}"
```

> **Note: Zero-downtime token rotation**
>
> `AUTH_TOKENS` accepts comma-separated tokens (`new-token,old-token`). Add the new token, roll clients, then remove the old one.

## Step 3: Deploy bunqueue (Service + 4 Pods + PDB)

Three rules built into this manifest:

1. **Leave `BUNQUEUE_BROKER_ID` unset** so each pod generates a fresh `<pod>:<pid>:<uuid>` identity on restart without waiting 30s for old session expiry.
2. **Set `DATA_PATH: ''`** to disable local SQLite and run with `readOnlyRootFilesystem: true`.
3. **Keep `/healthz` and `/ready` probes** so draining pods immediately flip `/ready` to `503` and hand active leases to siblings in ~4s.

*[Interactive k8s iso diagram: What happens during a Kubernetes rolling restart (SIGTERM) - Why drains take 4 seconds, not 30: the draining pod flips /ready to 503, stops claiming new work, hands active renewed leases safely to surviving pods, and exits cleanly - open the HTML page to view it.]*

Save as `bunqueue-k8s.yaml` and run `kubectl apply -f bunqueue-k8s.yaml`:

```yaml
# bunqueue-k8s.yaml
apiVersion: v1
kind: Service
metadata:
  name: bunqueue
  namespace: bunqueue
  labels: { app.kubernetes.io/name: bunqueue }
spec:
  type: ClusterIP
  selector: { app.kubernetes.io/name: bunqueue }
  ports:
    - { name: tcp, port: 6789, targetPort: tcp }
    - { name: http, port: 6790, targetPort: http }
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: bunqueue
  namespace: bunqueue
  labels: { app.kubernetes.io/name: bunqueue }
spec:
  replicas: 4
  strategy:
    # Recreate prevents old/new binaries mixing during schema upgrades.
    # For same-version config edits, RollingUpdate (maxUnavailable: 0) works too.
    type: Recreate
  selector:
    matchLabels: { app.kubernetes.io/name: bunqueue }
  template:
    metadata:
      labels: { app.kubernetes.io/name: bunqueue }
      annotations:
        prometheus.io/scrape: 'true'
        prometheus.io/port: '6790'
        prometheus.io/path: '/prometheus'
    spec:
      automountServiceAccountToken: false
      terminationGracePeriodSeconds: 45
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: ScheduleAnyway
          labelSelector:
            matchLabels: { app.kubernetes.io/name: bunqueue }
      initContainers:
        - name: wait-for-postgres
          image: postgres:19.0-alpine
          command: [/bin/sh, -ec, 'until pg_isready -d "$BUNQUEUE_POSTGRES_URL"; do sleep 1; done']
          env:
            - name: BUNQUEUE_POSTGRES_URL
              valueFrom: { secretKeyRef: { name: bunqueue-secrets, key: postgres-url } }
          securityContext:
            allowPrivilegeEscalation: false
            runAsNonRoot: true
            runAsUser: 70
            runAsGroup: 70
            capabilities: { drop: ['ALL'] }
      containers:
        - name: bunqueue
          image: ghcr.io/egeominotti/bunqueue:2.9.25
          ports:
            - { name: tcp, containerPort: 6789 }
            - { name: http, containerPort: 6790 }
          env:
            - { name: DATA_PATH, value: '' }
            - { name: BUNQUEUE_STORAGE_DRIVER, value: postgres }
            - name: BUNQUEUE_POSTGRES_URL
              valueFrom: { secretKeyRef: { name: bunqueue-secrets, key: postgres-url } }
            - { name: BUNQUEUE_POSTGRES_NAMESPACE, value: production }
            - { name: BUNQUEUE_POSTGRES_POOL_SIZE, value: '4' }
            - { name: SHUTDOWN_TIMEOUT_MS, value: '30000' }
            - { name: LOG_FORMAT, value: json }
            - name: AUTH_TOKENS
              valueFrom: { secretKeyRef: { name: bunqueue-secrets, key: auth-tokens } }
          startupProbe: { httpGet: { path: /healthz, port: http }, failureThreshold: 30, periodSeconds: 2 }
          livenessProbe: { httpGet: { path: /healthz, port: http }, failureThreshold: 3, periodSeconds: 10, timeoutSeconds: 5 }
          readinessProbe: { httpGet: { path: /ready, port: http }, failureThreshold: 3, periodSeconds: 5, timeoutSeconds: 3 }
          resources:
            requests: { cpu: 100m, memory: 128Mi }
            limits: { cpu: '1', memory: 512Mi }
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            runAsNonRoot: true
            runAsUser: 1001
            runAsGroup: 1001
            capabilities: { drop: ['ALL'] }
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: bunqueue, namespace: bunqueue }
spec:
  minAvailable: 2
  selector:
    matchLabels: { app.kubernetes.io/name: bunqueue }
```

## Step 4: Connect your app and workers

Connect clients to `bunqueue.bunqueue.svc.cluster.local:6789` with `BQ_TOKEN`, and call `worker.close()` on `SIGTERM` so in-flight jobs finish before termination:

**TypeScript (bunqueue-client)**

```ts
import { Queue, Worker } from 'bunqueue-client';

const connection = {
  host: process.env.BUNQUEUE_HOST ?? 'bunqueue.bunqueue.svc.cluster.local',
  port: Number(process.env.BUNQUEUE_PORT ?? 6789),
  token: process.env.BQ_TOKEN,
  poolSize: 4, // spreads TCP connections across all 4 broker pods
};

export const queue = new Queue('orders', { connection });
export const worker = new Worker('orders', async (job) => ({ processed: job.id }), {
  connection,
  concurrency: 16,
});

for (const sig of ['SIGTERM', 'SIGINT'] as const) {
  process.on(sig, async () => {
    await worker.close();
    await queue.close();
    process.exit(0);
  });
}
```

**Python**

```python
import os, signal
from bunqueue import Worker

worker = Worker(
    "orders",
    lambda job: {"processed": job.id},
    host=os.getenv("BUNQUEUE_HOST", "bunqueue.bunqueue.svc.cluster.local"),
    port=int(os.getenv("BUNQUEUE_PORT", "6789")),
    token=os.environ["BQ_TOKEN"],
    concurrency=16,
    autorun=False,
)
for sig in (signal.SIGTERM, signal.SIGINT):
    signal.signal(sig, lambda *_: worker.close())
worker.run()
```

**Go**

```go
worker := bunqueue.NewWorker(
    "orders",
    func(job *bunqueue.Job) (any, error) {
        return map[string]any{"processed": job.ID()}, nil
    },
    bunqueue.WorkerOptions{
        Host: "bunqueue.bunqueue.svc.cluster.local", Port: 6789,
        Token: os.Getenv("BQ_TOKEN"), Concurrency: 16, HeartbeatIntervalS: 10,
    },
)
worker.Run()
```

**Rust**

```rust
use bunqueue_client::{ConnectionOptions, Value, Worker, WorkerOptions};

let worker = Worker::new("orders", |job| Ok(Value::from(job.id())), WorkerOptions {
    connection: ConnectionOptions {
        host: "bunqueue.bunqueue.svc.cluster.local".into(), port: 6789,
        token: std::env::var("BQ_TOKEN").ok(), ..Default::default()
    },
    concurrency: 16, ..Default::default()
});
worker.run()?;
```

## Step 5: Verify everything is healthy

```bash
# 1. Confirm all 4 broker pods are Running and Ready
kubectl -n bunqueue rollout status deployment/bunqueue --timeout=120s
kubectl -n bunqueue get pods -o wide

# 2. Forward ports locally and check liveness + readiness
kubectl -n bunqueue port-forward svc/bunqueue 6789:6789 6790:6790 &
curl -fsS http://127.0.0.1:6790/healthz
curl -fsS http://127.0.0.1:6790/ready

# 3. Run automated broker diagnostics (add --pg "$BUNQUEUE_POSTGRES_URL" to check PostgreSQL directly)
bunqueue doctor --deep --host 127.0.0.1 --port 6789 --token "$AUTH_TOKEN"

# 4. Live TUI over port-forward: single Service VIP auto-discovers all PG peers in [8] Nodes
bunqueue top --host 127.0.0.1 --port 6789 --token "$AUTH_TOKEN"

# Or from inside the cluster/VPC, poll Deployment pod IPs directly for summed throughput, p99, RSS, and node focus
POD_NODES=$(kubectl -n bunqueue get pods -l app.kubernetes.io/name=bunqueue --field-selector=status.phase=Running \
  -o jsonpath='{range .items[*]}{.metadata.name}{"@"}{.status.podIP}{":6789,"}{end}' | sed 's/,$//')
bunqueue top --nodes "$POD_NODES" --token "$AUTH_TOKEN" --view nodes
```

## Step 6: Failover, chaos results, and sizing

Pod crashes and PostgreSQL restarts recover automatically inside PostgreSQL—no custom operator scripts required.

*[Interactive k8s iso diagram: Pod crashes and PostgreSQL restarts recover automatically - Zero manual intervention: session fencing stops dead pods from writing stale data, while a 5-second connect timeout brings /ready back to 200 OK in 5-6 seconds after a DB restart - open the HTML page to view it.]*

### Live chaos test results

Measured on a 4-broker `k3s v1.37.2` + `PostgreSQL 19.0` cluster (`512 MiB` limit per pod) across 8 minutes of rolling restarts, `SIGKILL` kills, node power-offs, and DB restarts ([v2.9.25 Chaos Report](https://bunqueue.dev/blog/bunqueue-v2-9-25/)):

| Scenario | What happens | Measured result |
| --- | --- | --- |
| **8 minutes of sustained chaos** | Kills, drains, large payloads, DB restarts | **`143,820 / 143,820`** settled, **`0`** lost, **`0`** duplicates |
| **Rolling deploy (`SIGTERM`)** | Pod drains owned leases, hands active ones to siblings | **`4 s`** pod drain · **`8 s`** full `Recreate` rollout |
| **PostgreSQL restarts** | Pods return `/ready 503`, retry rapidly, auto-heal | **`5-6 s`** back to `4/4 Ready 200 OK` |
| **Heavy backlog memory** | Bounded snapshot cache (`maxCompletedPayloadBytes`) | **`171-183 MiB`** steady RSS inside `512 MiB` limit |
| **Database scan efficiency** | `Schema v22` partial FIFO ready index | **`303k`** heap fetches (down **99.9%** from `326M`) |
| **Live Standby → Primary promotion** | `pg-primary` `SIGKILL` + `pg_promote` + HAProxy VIP cutover (`remote_apply` & `on`) | **`4.83 s`** `4/4` `/ready` auto-heal, **`0`** restarts, **`1,000/1,000`** jobs & **`40/40`** workflows |
| **Physical `pg_basebackup` + WAL PITR** | PG 19 Timeline 2 restore to `recovery_target_time` after post-cut `DELETE` | **`25/25`** mid-flight active jobs, **`6/6`** workflows & cron recovered; **`0`** post-cut leaks |
| **Multi-tenant & 4-SDK polyglot storm** | `250k` durable jobs (`20` tenants, `8` pods) + simultaneous TS/Python/Go/Rust SDKs | **`16,943 jobs/s`** enqueue, **`0`** leaks/restarts; **`1,000/1,000`** 4-SDK ring + shared pool in `6.08 s` |
| **Real `cgroup v2 OOMKill` & `PDB`** | Kernel `OOMKilled` (`Exit 137`) + `PodDisruptionBudget` (`minAvailable=2`) eviction | **`40/40`** jobs recovered (`10/10` orphaned leases); 2nd eviction blocked **`HTTP 429`**, **`200/200`** live jobs |

### High-volume tuning, scaling, and upgrades

From the [3-AZ Proxmox Jepsen & HA Verification Report](https://bunqueue.dev/blog/kubernetes-active-active-ha-verification/) (`> 100k` bursts on `synchronous_commit=on`):

- **Worker batch size:** use `batchSize: 10` (`1,697 jobs/s` vs `1,306` at `32` and `699` at `50` on ZFS `synchronous_commit=on`) to amortize WAL `fsync` with low `FOR UPDATE SKIP LOCKED` contention.
- **High-volume retention:** set `removeOnComplete: true` on high-throughput queues so completed rows do not consume broker snapshot memory.
- **Burst ceilings (`2 GiB` pods):** raise `BUNQUEUE_POSTGRES_POOL_SIZE=12`, `BUNQUEUE_POSTGRES_MAX_CONCURRENT_OPERATIONS=32`, `BUNQUEUE_POSTGRES_MAX_QUEUED_OPERATIONS=512`, `BUNQUEUE_POSTGRES_MAX_SNAPSHOT_JOBS=250000`, and `BUNQUEUE_MAX_COMPLETED_JOBS=5000` (keep `replicas × (POOL_SIZE + 1)` under PostgreSQL `max_connections`).
- **Probe & partition hygiene:** keep `livenessProbe.timeoutSeconds: 5` to avoid false restarts under load; the 5s in-flight stall detector automatically flips `/ready` to `503` on silent packet drops (`iptables -j DROP`), evicting blackholed pods from Service Endpoints in ~8s.
- **Scale brokers:** `kubectl -n bunqueue scale deployment/bunqueue --replicas=6` (verify `replicas × 5` fits `max_connections`).
- **Autoscale workers:** target `bunqueue_queue_jobs_waiting{queue="orders"}` or `bunqueue_jobs_waiting` on `/prometheus` (`:6790`) via [KEDA](https://keda.sh/) or `HPA`.
- **Upgrades:** both Queue (`bunqueue_schema_migrations`) and Workflow (`bunqueue_workflow_schema_migrations`) record `min_compatible_version` for fail-closed expand-and-contract upgrades. Additive releases (`min_compatible_version <= vN`) support zero-downtime `RollingUpdate` (`maxUnavailable: 0`) across mixed `vN`/`vN+1` pods without running older DDL over newer schemas; breaking schema bumps (`min_compatible_version > vN`, `<= 0`, or `NULL`) fail closed and require `strategy: { type: Recreate }`.

## Optional production add-ons

**Native TLS**

Mount your cert-manager secret read-only and send `SIGHUP` after rotation for zero-downtime certificate reload ([Native TLS Guide](https://bunqueue.dev/guide/tls/)).

```yaml
# Add inside Deployment spec.template.spec
volumes:
  - name: tls
    secret: { secretName: bunqueue-tls, defaultMode: 0400 }
containers:
  - name: bunqueue
    env:
      - { name: TLS_CERT_FILE, value: /etc/bunqueue/tls/tls.crt }
      - { name: TLS_KEY_FILE, value: /etc/bunqueue/tls/tls.key }
    volumeMounts:
      - { name: tls, mountPath: /etc/bunqueue/tls, readOnly: true }
```

**NetworkPolicy**

Allow `:6789` only from labeled app namespaces (`kubectl label ns app bunqueue-access=true`) and `:6790` from `monitoring`.

```yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: bunqueue-broker, namespace: bunqueue }
spec:
  podSelector:
    matchLabels: { app.kubernetes.io/name: bunqueue }
  policyTypes: [Ingress, Egress]
  ingress:
    - from: [{ namespaceSelector: { matchLabels: { bunqueue-access: 'true' } } }]
      ports: [{ protocol: TCP, port: 6789 }]
    - from: [{ namespaceSelector: { matchLabels: { kubernetes.io/metadata.name: monitoring } } }]
      ports: [{ protocol: TCP, port: 6790 }]
  egress:
    - to: [{ namespaceSelector: {}, podSelector: { matchLabels: { k8s-app: kube-dns } } }]
      ports: [{ protocol: UDP, port: 53 }, { protocol: TCP, port: 53 }]
    - ports: [{ protocol: TCP, port: 5432 }]
```

**Prometheus**

Scrape `/prometheus` on `:6790` with `kube-prometheus-stack` ([Monitoring & Alerts](https://bunqueue.dev/guide/monitoring/)).

```yaml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata: { name: bunqueue, namespace: bunqueue }
spec:
  selector:
    matchLabels: { app.kubernetes.io/name: bunqueue }
  endpoints:
    - { port: http, path: /prometheus, interval: 15s }
```

**Multi-Pod Workflows**

Point every pod's `bunqueue/workflow` `Engine` at the same PostgreSQL 17-19 database for token-fenced execution leases, durable `.sleep()` timers, and automatic orphan recovery with zero leader election. See [Workflow Durability](https://bunqueue.dev/guide/workflow/durability/).

## Where to go next

- [Deployment Guide](https://bunqueue.dev/guide/deployment/) · [SQLite & PostgreSQL Storage](https://bunqueue.dev/guide/databases/) · [Production Checklist](https://bunqueue.dev/guide/production/)
- [Active-Active HA Verification Report](https://bunqueue.dev/blog/kubernetes-active-active-ha-verification/) (TLA+ 193.69M states, trace validation, 10,000-seed DST, 3-AZ Proxmox Jepsen `LINEARIZABLE`, 10/10 chaos suites)
- [v2.9.25 Chaos Report](https://bunqueue.dev/blog/bunqueue-v2-9-25/) (live 4-broker k3s + PostgreSQL 19 telemetry)
