Skip to content
Get started
Get started
Python SDK (bunqueue-client)
View Markdown
sdks · python

Python SDK for AI & backend workers.

Official Python 3.10+ client over native binary MessagePack TCP. Ideal for ML inference, data pipelines, and async backend workers paired with any frontend runtime.

Python SDK (Protocol v3)

Run threaded Workers, ACK batching, atomic flows, and Simple Mode over TCP

push PY Python App Queue / Bunqueue persist TCP MsgPack v3 TCP :6789 + TLS pull + ack SRV bunqueue SQLite or PG 17-19 ML Threaded Worker ack_batch + retries pip install bunqueue-client · Python 3.10+ · Simple Mode & FlowProducer included
Built for Python AI & backend teams: install bunqueue-client (Python 3.10+) with concurrent workers, automatic heartbeats, and verified TLS.

Install bunqueue-client and connect over MessagePack TCP (pass an explicit Connection when customizing connect_timeout):

pip install bunqueue-client
import os
from bunqueue import Connection, Queue
queue = Queue(
"emails", host="queue.example.com", port=6789,
token=os.environ["BUNQUEUE_TOKEN"], tls=True, command_timeout=10.0,
)
# tls also accepts {"ca_file": "./ca.pem"} or ssl.SSLContext; share a Connection for connect_timeout:
conn = Connection(host="queue.example.com", port=6789, connect_timeout=5.0, tls=True)
custom_queue = Queue("emails", connection=conn)

Enqueue single jobs with Python snake_case options or send a batch in one TCP round-trip via add_bulk:

queue.add(
"charge", {"order_id": "ord_42", "amount": 1999},
job_id="order-ord_42", priority=10, delay=5000, attempts=5, durable=True,
)
queue.add_bulk([{"name": "ingest", "data": o, "job_id": f"order-{o['id']}"} for o in orders])

Worker runs a bounded thread pool with automatic lease heartbeats, optional ack_batch coalescing, and UnrecoverableError to bypass retries into the DLQ:

from bunqueue import UnrecoverableError, Worker
def process(job):
if not job.data.get("to"):
raise UnrecoverableError("missing recipient") # skip retries -> DLQ
send_email(job.data["to"])
return {"sent": True}
worker = Worker(
"emails", process, host="localhost", port=6789,
concurrency=10, batch_size=10, poll_timeout_ms=5000, lock_ttl_ms=30000, heartbeat_interval_s=10,
ack_batch={"max_size": 50, "max_delay_ms": 5}, # opt-in high-volume ACK batching
)
worker.on("completed", lambda job, res: print(f"done {job.id}: {res}"))
worker.on("failed", lambda job, err: print(f"failed {job.id}: {err}"))
worker.on("error", lambda err: print(f"worker error: {err}"))
worker.run()
# Graceful shutdown: worker.close() (flush ACKs & wait) or worker.close(timeout=5) (bound wait)

Permanent refusals (bad auth token or validation error) raise out of run() unless an error listener is attached.

Inspect job state, wait for completion, control queues/DLQ, and manage webhooks directly on Queue:

job = queue.get_job(job_id) # None when missing
state = queue.get_state(job_id) # "waiting" | "active" | ...
result = queue.wait_for_job(job_id, timeout_ms=30000)
counts = queue.get_job_counts()
queue.pause()
dropped = queue.drain()
queue.retry_dlq()
# Webhook helpers
wh_id = queue.add_webhook("https://api.example.com/hooks", ["job.completed"], secret="s3cr3t")
queue.set_webhook_enabled(wh_id, False)
queue.remove_webhook(wh_id)

FlowProducer validates the entire graph locally and submits one atomic PUSHF command:

from bunqueue import FlowProducer
flow = FlowProducer()
# Sequential pipeline
flow.add_chain([
{"name": "extract", "queueName": "etl"},
{"name": "transform", "queueName": "etl"},
{"name": "load", "queueName": "etl"},
])
# Parent waits for children
node = flow.add({
"name": "assemble",
"queueName": "orders",
"children": [
{"name": "reserve-stock", "queueName": "orders"},
{"name": "charge-card", "queueName": "orders"},
],
})
# Fan-in: N parallel jobs converge into one
flow.add_bulk_then(parts, {"name": "merge", "queueName": "orders"})

Combine queue, worker, named routes, middleware, retries, circuit breaker, and crons in one object:

from bunqueue import Bunqueue
app = Bunqueue(
"notifications",
routes={
"send-email": lambda job: {"sent": True},
"send-sms": lambda job: {"sent": True},
},
concurrency=10,
retry={"max_attempts": 5, "strategy": "jitter"},
circuit_breaker={"threshold": 5, "reset_timeout": 30000},
)
def timing(job, next_fn):
result = next_fn()
print(f"{job.name} done")
return result
app.use(timing)
app.add("send-email", {"to": "alice@example.com"})
app.cron("daily-digest", "0 9 * * *", {"to": "all"})

Attach on_telemetry to emit connection, auth, command latency, and retry events without exposing tokens or payloads:

queue = Queue("emails", on_telemetry=lambda event: metrics.observe(event))

Typed exceptions distinguish connection drops, command timeouts, server rejections, auth failures, and serialization errors. Large integers outside int32 travel as float64 (pass 64-bit snowflake IDs as strings).