Skip to content
Get started
Get started
Deploy bunqueue on Kubernetes
View Markdown
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.

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.
3D Topology

Your apps talk to one Service. PostgreSQL keeps all 4 pods in sync.

Your APIs add jobs Workers pull & ack Service :6789 Stateless Deployment (4 identical pods · no Redis) pod-1 READY pod-2 READY pod-3 READY pod-4 READY PostgreSQL 17-19 All jobs · leases · LISTEN/NOTIFY · Schema v22
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.

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).

Capacity Sizing

1 broker pod = 5 PostgreSQL connections

1 Broker Pod 5 DB connections total 4 pooled SQL connections + 1 LISTEN stream PostgreSQL max_connections = 100 QUICK RULE: PODS × 5 2 pods → 10 conns 4 pods → 20 conns ★ 6 pods → 30 conns 8 pods → 40 conns Default 4 pods use only 20% of stock PostgreSQL connections — plenty of headroom left for your app.
Easy math: 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/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 }]

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 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}"

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

Section titled “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.
Zero-Downtime Rollouts

What happens during a Kubernetes rolling restart (SIGTERM)

move active traffic new pod joins 503 DRAIN 1. SIGTERM arrives /ready flips to 503 200 READY 2. Safe handoff Neighbor keeps running 4 s DONE 3. Fresh pod boots New ID, 0 s lockout Result: ~4 s graceful drain · 0 lost ACKs · 0 duplicate executions
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.

Save as bunqueue-k8s.yaml and run kubectl apply -f bunqueue-k8s.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 }

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);
});
}
# 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

Section titled “Step 6: Failover, chaos results, and sizing”

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

Automatic Failover

Pod crashes and PostgreSQL restarts recover automatically

CASE A · POD CRASHES (SIGKILL) CRASH leases recovered SURVIVOR Old pod is fenced out automatically. Healthy pods reclaim expired jobs via PostgreSQL. 0 lost jobs · 0 duplicates CASE B · POSTGRESQL RESTARTS 503→200 503→200 PG 19 Pods self-heal without manual restarts. 5 s connect timeout + rapid retry clears /ready. 4/4 pods Ready again in 5-6 s
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.

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):

ScenarioWhat happensMeasured result
8 minutes of sustained chaosKills, drains, large payloads, DB restarts143,820 / 143,820 settled, 0 lost, 0 duplicates
Rolling deploy (SIGTERM)Pod drains owned leases, hands active ones to siblings4 s pod drain · 8 s full Recreate rollout
PostgreSQL restartsPods return /ready 503, retry rapidly, auto-heal5-6 s back to 4/4 Ready 200 OK
Heavy backlog memoryBounded snapshot cache (maxCompletedPayloadBytes)171-183 MiB steady RSS inside 512 MiB limit
Database scan efficiencySchema v22 partial FIFO ready index303k heap fetches (down 99.9% from 326M)
Live Standby → Primary promotionpg-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 PITRPG 19 Timeline 2 restore to recovery_target_time after post-cut DELETE25/25 mid-flight active jobs, 6/6 workflows & cron recovered; 0 post-cut leaks
Multi-tenant & 4-SDK polyglot storm250k durable jobs (20 tenants, 8 pods) + simultaneous TS/Python/Go/Rust SDKs16,943 jobs/s enqueue, 0 leaks/restarts; 1,000/1,000 4-SDK ring + shared pool in 6.08 s
Real cgroup v2 OOMKill & PDBKernel OOMKilled (Exit 137) + PodDisruptionBudget (minAvailable=2) eviction40/40 jobs recovered (10/10 orphaned leases); 2nd eviction blocked HTTP 429, 200/200 live jobs

From the 3-AZ Proxmox Jepsen & HA Verification Report (> 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 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 }.

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.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 }