Job Groups (group: { id })
Round-robin FIFO lanes inside a single queue with broker-enforced per-tenant concurrency, rate windows, and pending depth caps.
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.
Keep jobs ordered per tenant group while round-robin prevents starvation
groupId execute strictly in order, while workers cycle fairly across active tenant groups.Round-robin FIFO lanes inside a single queue with broker-enforced per-tenant concurrency, rate windows, and pending depth caps.
Prefixes broker queue keys (e.g. prod:emails) transparently while keeping Queue.name logical.
Client organizer that creates prefixed Queue and Worker instances (billing:invoices, billing:payments) with bulk group controls.
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 integersawait 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.
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 tenantawait queue.removeGroupRateLimit('tenant-a');await queue.removeGroupConcurrency('tenant-a');await queue.pauseGroup('tenant-a');await queue.isGroupPaused('tenant-a'); // trueawait 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 groupsconst tenantActive = await queue.getGroupActiveCount('tenant-a'); // active in groupconst retryInMs = await queue.getGroupRateLimitTtl('tenant-a', 5); // ms, 0 if room, -2 if noneconst 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.
queue.obliterateAsync() deletes all jobs and all group configuration for that queue.prefixKeyprefixKey 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') directlyJob.queueName carries the full prefixed key ('dev:emails').jobId stays broker-wide (PostgreSQL: namespace-wide), so prefix custom IDs too ('dev:order-123'). prefixKey is naming isolation, not authorization.QueueGroupQueueGroup 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();| Method | Scope | Description |
|---|---|---|
getQueue(name, opts?) / getWorker(name, fn, opts?) | Embedded & TCP | Create a prefixed Queue or Worker in the group |
listQueuesAsync() | Embedded & TCP | List queues created via this instance (plus embedded manager queues when active) |
pauseAllAsync() / resumeAllAsync() | Embedded & TCP | Pause or resume all queues registered on this instance |
drainAllAsync() / obliterateAllAsync() | Embedded & TCP | Drain or obliterate all queues registered on this instance |
listQueues(), pauseAll(), resumeAll(), drainAll(), obliterateAll() | Embedded only | Synchronous in-process equivalents |
autoBatchIn 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: true jobs bypass the batcher and send individually.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).'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).add() validates its own JobOptions before batching so one invalid job never fails unrelated adds.queue.forward())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.