# Job Groups, Namespaces and Batching

Partition a bunqueue queue per tenant with fair FIFO job groups, isolate environments with prefixKey or QueueGroup, and tune TCP auto-batching and store-and-forward.

Canonical: https://bunqueue.dev/guide/queue/groups/

---

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.

**In 30 seconds**

- **Job Groups (`group: { id }`):** partition **one queue** into round-robin FIFO lanes with per-group concurrency, rate limits, pause/resume, and `maxSize` backpressure.
- **Namespaces (`prefixKey`, `QueueGroup`):** isolate **separate queues** on one broker by prefixing broker queue keys (dev/staging/prod or domain sets).
- **Client transport:** TCP `autoBatch` folds concurrent `add()` calls into `PUSHB`; `queue.forward()` drains a local queue to a central broker.

*[Interactive doc iso diagram: Keep jobs ordered per tenant group while round-robin prevents starvation - No noisy neighbor: jobs with the same groupId execute strictly in order, while workers cycle fairly across active tenant groups - open the HTML page to view it.]*

- **Job Groups (group: { id })**: Round-robin FIFO lanes inside a single queue with broker-enforced per-tenant concurrency, rate windows, and pending depth caps.
- **prefixKey**: Prefixes broker queue keys (e.g. prod:emails) transparently while keeping Queue.name logical.
- **QueueGroup**: Client organizer that creates prefixed Queue and Worker instances (billing:invoices, billing:payments) with bulk group controls.

## Job Groups (Per-Tenant FIFO and Fairness)

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.

```typescript
// 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

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:

```typescript
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.

### Autoscaling and depth signals

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

```typescript
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.

## Namespacing

### `prefixKey`

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

```typescript
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`

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

```typescript
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 |

## Advanced Client Batching and Forwarding

### TCP `autoBatch`

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.

```typescript
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.

### Store-and-forward (`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](https://bunqueue.dev/guide/iot-edge/) for deployment patterns.

```typescript
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](https://bunqueue.dev/guide/rate-limiting/), or configure consumer concurrency in [Workers](https://bunqueue.dev/guide/worker/).
