- Docs
- Production & Operations
- Kubernetes
Run bunqueue on 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.
How it works
Section titled “How it works”Three stateless layers keep operations simple:
- Apps & workers connect to one ClusterIP
Service(bunqueue:6789). - Broker pods hold no local disk state—any pod accepts jobs, serves workers, and restarts cleanly.
- PostgreSQL 17-19 stores jobs, locks, retries, and schedules, synchronizing pods via
LISTEN/NOTIFY.
Your apps talk to one Service. PostgreSQL keeps all 4 pods in sync.
Step 1: Prepare PostgreSQL 17-19
Section titled “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. Each pod opens 5 connections by default (4 pooled SQL queries + 1 LISTEN channel): budget replicas × (BUNQUEUE_POSTGRES_POOL_SIZE + 1).
1 broker pod = 5 PostgreSQL connections
replicas × (BUNQUEUE_POSTGRES_POOL_SIZE + 1). Four pods use 20 connections total, comfortably inside PostgreSQL's default limit of 100.Optional: in-cluster PostgreSQL 19 manifest (staging/dev only)
# 00-postgres-dev.yaml (use managed PostgreSQL or CloudNativePG in production)apiVersion: apps/v1kind: StatefulSetmetadata: { 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: v1kind: Servicemetadata: { 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
Section titled “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):
kubectl create namespace bunqueueAUTH_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}"Step 3: Deploy bunqueue (Service + 4 Pods + PDB)
Section titled “Step 3: Deploy bunqueue (Service + 4 Pods + PDB)”Three rules built into this manifest:
- Leave
BUNQUEUE_BROKER_IDunset so each pod generates a fresh<pod>:<pid>:<uuid>identity on restart without waiting 30s for old session expiry. - Set
DATA_PATH: ''to disable local SQLite and run withreadOnlyRootFilesystem: true. - Keep
/healthzand/readyprobes so draining pods immediately flip/readyto503and hand active leases to siblings in ~4s.
What happens during a Kubernetes rolling restart (SIGTERM)
/ready to 503, stops claiming new work, hands active renewed leases safely to surviving pods, and exits cleanly.Save as bunqueue-k8s.yaml and run kubectl apply -f bunqueue-k8s.yaml:
apiVersion: v1kind: Servicemetadata: 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/v1kind: Deploymentmetadata: 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/v1kind: PodDisruptionBudgetmetadata: { name: bunqueue, namespace: bunqueue }spec: minAvailable: 2 selector: matchLabels: { app.kubernetes.io/name: bunqueue }Step 4: Connect your app and workers
Section titled “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:
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); });}import os, signalfrom 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()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()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
Section titled “Step 5: Verify everything is healthy”# 1. Confirm all 4 broker pods are Running and Readykubectl -n bunqueue rollout status deployment/bunqueue --timeout=120skubectl -n bunqueue get pods -o wide
# 2. Forward ports locally and check liveness + readinesskubectl -n bunqueue port-forward svc/bunqueue 6789:6789 6790:6790 &curl -fsS http://127.0.0.1:6790/healthzcurl -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] Nodesbunqueue 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 focusPOD_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 nodesStep 6: Failover, chaos results, and sizing
Section titled “Step 6: Failover, chaos results, and sizing”Pod crashes and PostgreSQL restarts recover automatically inside PostgreSQL—no custom operator scripts required.
Pod crashes and PostgreSQL restarts recover automatically
/ready back to 200 OK in 5-6 seconds after a DB restart.Live chaos test results
Section titled “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):
| 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
Section titled “High-volume tuning, scaling, and upgrades”From the 3-AZ Proxmox Jepsen & HA Verification Report (> 100k bursts on synchronous_commit=on):
- Worker batch size: use
batchSize: 10(1,697 jobs/svs1,306at32and699at50on ZFSsynchronous_commit=on) to amortize WALfsyncwith lowFOR UPDATE SKIP LOCKEDcontention. - High-volume retention: set
removeOnComplete: trueon high-throughput queues so completed rows do not consume broker snapshot memory. - Burst ceilings (
2 GiBpods): raiseBUNQUEUE_POSTGRES_POOL_SIZE=12,BUNQUEUE_POSTGRES_MAX_CONCURRENT_OPERATIONS=32,BUNQUEUE_POSTGRES_MAX_QUEUED_OPERATIONS=512,BUNQUEUE_POSTGRES_MAX_SNAPSHOT_JOBS=250000, andBUNQUEUE_MAX_COMPLETED_JOBS=5000(keepreplicas × (POOL_SIZE + 1)under PostgreSQLmax_connections). - Probe & partition hygiene: keep
livenessProbe.timeoutSeconds: 5to avoid false restarts under load; the 5s in-flight stall detector automatically flips/readyto503on silent packet drops (iptables -j DROP), evicting blackholed pods from Service Endpoints in ~8s. - Scale brokers:
kubectl -n bunqueue scale deployment/bunqueue --replicas=6(verifyreplicas × 5fitsmax_connections). - Autoscale workers: target
bunqueue_queue_jobs_waiting{queue="orders"}orbunqueue_jobs_waitingon/prometheus(:6790) via KEDA orHPA. - Upgrades: both Queue (
bunqueue_schema_migrations) and Workflow (bunqueue_workflow_schema_migrations) recordmin_compatible_versionfor fail-closed expand-and-contract upgrades. Additive releases (min_compatible_version <= vN) support zero-downtimeRollingUpdate(maxUnavailable: 0) across mixedvN/vN+1pods without running older DDL over newer schemas; breaking schema bumps (min_compatible_version > vN,<= 0, orNULL) fail closed and requirestrategy: { type: Recreate }.
Optional production add-ons
Section titled “Optional production add-ons”Mount your cert-manager secret read-only and send SIGHUP after rotation for zero-downtime certificate reload (Native TLS Guide).
# Add inside Deployment spec.template.specvolumes: - 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 }Allow :6789 only from labeled app namespaces (kubectl label ns app bunqueue-access=true) and :6790 from monitoring.
apiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata: { 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 }]Scrape /prometheus on :6790 with kube-prometheus-stack (Monitoring & Alerts).
apiVersion: monitoring.coreos.com/v1kind: ServiceMonitormetadata: { name: bunqueue, namespace: bunqueue }spec: selector: matchLabels: { app.kubernetes.io/name: bunqueue } endpoints: - { port: http, path: /prometheus, interval: 15s }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.
Where to go next
Section titled “Where to go next”- Deployment Guide · SQLite & PostgreSQL Storage · Production Checklist
- Active-Active HA Verification Report (TLA+ 193.69M states, trace validation, 10,000-seed DST, 3-AZ Proxmox Jepsen
LINEARIZABLE, 10/10 chaos suites) - v2.9.25 Chaos Report (live 4-broker k3s + PostgreSQL 19 telemetry)