Skip to content
Get started
Get started
Job Groups, Namespaces and Batching
View Markdown
guide · queue

Fair tenants, clean namespaces.

Stop noisy tenants from starving others with broker-enforced job groups, separate environments on one server with prefixes, and batch or forward producer traffic efficiently.

Fair Multi-Tenant FIFO

Keep jobs ordered per tenant group while round-robin prevents starvation

Tenant A (FIFO) Tenant B (FIFO) Tenant C (FIFO) group partition 1 active / group Incoming Jobs tagged by groupId Worker Pool fair round-robin Use prefixKey for soft org isolation; pause or drain any single group on demand
No noisy neighbor: jobs with the same groupId execute strictly in order, while workers cycle fairly across active tenant groups.

Pick the right isolation boundary

Inside one queue

Job Groups (group: { id })

Round-robin FIFO lanes inside a single queue with broker-enforced per-tenant concurrency, rate windows, and pending depth caps.

Best for
Multi-tenant webhooks, per-customer pipelines, and dynamic tenant counts on one Worker pool.
Skip if
Tenants need separate queue metrics, DLQs, or cron registries.
Per-instance prefix

prefixKey

Prefixes broker queue keys (e.g. prod:emails) transparently while keeping Queue.name logical.

Best for
Sharing one server across dev/staging/prod, monorepo services, or parallel test runs.
Skip if
You want one helper to pause, drain, or obliterate several domain queues together.
Multi-queue helper

QueueGroup

Client organizer that creates prefixed Queue and Worker instances (billing:invoices, billing:payments) with bulk group controls.

Best for
Managing related domain queues together (billing, media, notifications).
Skip if
You want per-tenant fairness inside one shared Worker.

Tag jobs in one queue with group: { id } to isolate tenants or destinations. Ready groups rotate round-robin (tenant-a, tenant-b, tenant-a), equal-priority jobs inside a group run FIFO, and ungrouped ready jobs are served ahead of grouped ones.

// Bun: 'bunqueue/client' (+ embedded: true for in-process). Node/Deno: 'bunqueue-client'.
import { Queue, Worker } from 'bunqueue/client';
const queue = new Queue('webhooks');
// Group IDs: non-empty strings (<= 256 chars, no NUL) or safe integers
await queue.add('deliver', { event: 'created' }, { group: { id: 'tenant-a' } });
await queue.add('deliver', { event: 'updated' }, {
group: {
id: 'tenant-a',
priority: 1, // 0 is highest; integers 0..2,097,151 run ascending
maxSize: 10_000, // atomic pending-depth cap (waiting + prioritized + delayed)
},
});

maxSize counts only pending jobs (waiting, prioritized, delayed), not active ones. A full group rejects add(), atomic FlowProducer graphs, and PostgreSQL addBulk() transactions; memory/SQLite addBulk() keeps earlier accepted entries and throws at the rejected one.

Per-group concurrency, rate limits, and overrides

Section titled “Per-group concurrency, rate limits, and overrides”

FIFO controls claim order, not parallelism. Configure shared broker-enforced group defaults on every Worker serving the queue, then override individual noisy tenants at runtime:

const worker = new Worker('webhooks', deliverWebhook, {
concurrency: 50, // total parallel jobs in this process
group: {
concurrency: 2, // max 2 active jobs per group (1 = strict serial)
limit: { max: 20, duration: 1000 }, // 20 starts/sec per group across all workers
},
});
// Per-tenant overrides (take effect only when the Worker sets that default)
await queue.setGroupRateLimit('tenant-a', 5, 1000);
await queue.setGroupConcurrency('tenant-a', 1);
await queue.getGroupRateLimit('tenant-a'); // { max: 5, duration: 1000 }
await queue.getGroupConcurrency('tenant-a'); // 1
// Clear overrides or pause/resume one tenant
await queue.removeGroupRateLimit('tenant-a');
await queue.removeGroupConcurrency('tenant-a');
await queue.pauseGroup('tenant-a');
await queue.isGroupPaused('tenant-a'); // true
await queue.resumeGroup('tenant-a');

Inside a processor, await worker.rateLimitGroup(job, 30_000) applies a manual cooldown and returns the active job to waiting (even without a group.limit default). Immediately return or throw Worker.RateLimitError() so remaining handler code does not run.

Read server-authoritative group depth, active counts, and cooldown TTLs directly from the broker:

const tenantDepth = await queue.getGroupJobsCount('tenant-a'); // pending (O(1) server read)
const totalGroupedDepth = await queue.getGroupsJobsCount(); // pending across all groups
const tenantActive = await queue.getGroupActiveCount('tenant-a'); // active in group
const retryInMs = await queue.getGroupRateLimitTtl('tenant-a', 5); // ms, 0 if room, -2 if none
const jobs = await queue.getGroupJobs('tenant-a', 0, 99); // inclusive end (up to 100)
const byPriority = await queue.getCountsPerPriorityForGroup('tenant-a');

getGroupJobsCount, getGroupsJobsCount, getGroupActiveCount, and getGroupRateLimitTtl query the broker directly. getGroupJobs (inclusive end) and getCountsPerPriorityForGroup fetch pending queue jobs and filter client-side.

Group persistence across SQLite and PostgreSQL
  • SQLite: Persists per-group overrides and pause state across restarts; active fixed windows and manual deadlines reset on restart.
  • PostgreSQL: Persists overrides, pause state, manual deadlines, live fixed-window accounting, admission order, and round-robin position across brokers. Inactive scheduler rows reclaim once jobs, overrides, and active windows expire.
  • Cleanup: queue.obliterateAsync() deletes all jobs and all group configuration for that queue.

prefixKey prepends a namespace to queue membership, locks, counts, crons, pause state, DLQ, and rate limits while keeping Queue.name logical. Pass the same prefixKey to both Queue and Worker.

const devQueue = new Queue('emails', { prefixKey: 'dev:' });
const devWorker = new Worker('emails', processor, { prefixKey: 'dev:' });
// External SDKs without prefixKey: open Queue('dev:emails') directly
  • Job.queueName carries the full prefixed key ('dev:emails').
  • Custom jobId stays broker-wide (PostgreSQL: namespace-wide), so prefix custom IDs too ('dev:order-123'). prefixKey is naming isolation, not authorization.

QueueGroup prefixes related domain queues (billing:invoices, billing:payments) and adds bulk controls over queues created through that instance. External SDKs interoperate by opening the prefixed name directly.

import { QueueGroup } from 'bunqueue/client';
const billing = new QueueGroup('billing');
const invoices = billing.getQueue('invoices'); // broker key: 'billing:invoices'
const payments = billing.getQueue('payments'); // broker key: 'billing:payments'
const worker = billing.getWorker('invoices', async (job) => ({ ok: true }));
const names = await billing.listQueuesAsync(); // ['invoices', 'payments']
await billing.pauseAllAsync();
await billing.resumeAllAsync();
const drained = await billing.drainAllAsync();
await billing.obliterateAllAsync();
MethodScopeDescription
getQueue(name, opts?) / getWorker(name, fn, opts?)Embedded & TCPCreate a prefixed Queue or Worker in the group
listQueuesAsync()Embedded & TCPList queues created via this instance (plus embedded manager queues when active)
pauseAllAsync() / resumeAllAsync()Embedded & TCPPause or resume all queues registered on this instance
drainAllAsync() / obliterateAllAsync()Embedded & TCPDrain or obliterate all queues registered on this instance
listQueues(), pauseAll(), resumeAll(), drainAll(), obliterateAll()Embedded onlySynchronous in-process equivalents

In TCP mode, TypeScript Queue instances fold concurrent add() calls into single PUSHB round trips. Sequential await queue.add(...) flushes immediately; concurrent Promise.all(...) calls share batches automatically.

const queue = new Queue('events', {
autoBatch: {
enabled: true, // default: true
maxSize: 50, // flush at 50 entries (default: 50)
maxDelayMs: 5, // max buffer wait in ms (default: 5)
},
});
  • Durable bypass: durable: true jobs bypass the batcher and send individually.
  • Shutdown & overflow: Call await queue.disconnect() to flush buffered adds; queue.close() stops immediately and rejects buffered adds with AddBatcher stopped. The pending buffer caps at 10,000 entries and drops the oldest 10% on overflow (Add buffer overflow - oldest entries dropped).
autoBatch option coercion rules
  • Constructor fields never throw: 'true'/'false' and 1/0 map to booleans (other invalid values keep batching on with one warning).
  • maxSize < 1 flushes each add, fractions round up, and Infinity/NaN/non-numbers disable size flushes; invalid or negative maxDelayMs flushes immediately (0).
  • Each add() validates its own JobOptions before batching so one invalid job never fails unrelated adds.

Drain a local source queue (such as embedded SQLite on an edge device) into a remote bunqueue server, keeping jobs persisted locally while offline. See IoT & Edge for deployment patterns.

const forwarder = queue.forward({
to: { host: 'queue.example.com', port: 6789, tls: true, token: process.env.BQ_TOKEN },
queue: 'central-events', // optional remote queue (default: same)
concurrency: 4, // parallel forwards (default: 4)
durable: true, // push remotely with durable: true (default: false)
});
forwarder.on('forwarded', ({ id, remoteId, name }) => console.log(id, '->', remoteId));
forwarder.on('error', (err) => console.error(err));
await forwarder.close();

Next steps: Combine group limits with Rate Limiting & Concurrency, or configure consumer concurrency in Workers.