# Per-tenant queues and rate limits

> Give every customer its own pushq queue and rate limit with folders like tenants/<id>, create queues on first use, list, pause and delete them.

Source: https://pushqueue.dev/docs/patterns/per-tenant-queues/

This pattern gives each customer (tenant, user, workspace) its own pushq queue with its own rate limit, so one busy customer can't slow everyone else down. You name the queues `tenants/<id>`, create each one the first time that tenant enqueues work, and pause, re-limit or delete one tenant's queue without touching the others.

## Create a queue per tenant on first use

Enqueue into the tenant's queue. If the queue doesn't exist yet the API answers `404 not_found`; create the queue with its full configuration and enqueue again. In the normal case this costs one API call per task.


**TypeScript**

```ts

const pq = new Pushq({ apiKey: process.env.PUSHQ_API_KEY });

// The full config for one tenant: always send all of it (see the caution below).
function tenantConfig(perSecond: number, concurrent: number) {
  return {
    rateLimits: { maxDispatchesPerSecond: perSecond, maxConcurrentDispatches: concurrent },
    retry: { maxAttempts: 10, maxBackoffSeconds: 600 },
    target: { baseUrl: "https://api.example.com" },
  };
}

async function enqueueForTenant(tenantId: string, perSecond: number, concurrent: number, jsonBody: unknown) {
  const queue = `tenants/${tenantId}`;
  const task = { path: "/hooks/sync", jsonBody };
  try {
    return await pq.createTask(queue, task);
  } catch (err) {
    if (!(err instanceof PushqError && err.code === "not_found")) throw err;
    await pq.upsertQueue(queue, tenantConfig(perSecond, concurrent)); // first task for this tenant
    return await pq.createTask(queue, task);
  }
}
```

**Python**

```python
import os
from pushq import Pushq, PushqError, RateLimits, Retry, Target

pq = Pushq(api_key=os.environ["PUSHQ_API_KEY"])

def tenant_config(per_second: float, concurrent: int) -> dict:
    # The full config for one tenant: always send all of it (see the caution below).
    return dict(
        rate_limits=RateLimits(max_dispatches_per_second=per_second,
                               max_concurrent_dispatches=concurrent),
        retry=Retry(max_attempts=10, max_backoff_seconds=600),
        target=Target(base_url="https://api.example.com"),
    )

def enqueue_for_tenant(tenant_id: str, per_second: float, concurrent: int, payload: dict):
    queue = f"tenants/{tenant_id}"
    try:
        return pq.create_task(queue, path="/hooks/sync", json_body=payload)
    except PushqError as e:
        if e.code != "not_found":
            raise
    pq.upsert_queue(queue, **tenant_config(per_second, concurrent))  # first task for this tenant
    return pq.create_task(queue, path="/hooks/sync", json_body=payload)
```

**Go**

```go
// The full config for one tenant: always send all of it (see the caution below).
func tenantConfig(perSecond float64, concurrent int) pushq.QueueConfig {
	return pushq.QueueConfig{
		RateLimits: &pushq.RateLimits{
			MaxDispatchesPerSecond:  pushq.Float64(perSecond),
			MaxConcurrentDispatches: pushq.Int(concurrent),
		},
		Retry:  &pushq.Retry{MaxAttempts: pushq.Int(10), MaxBackoffSeconds: pushq.Float64(600)},
		Target: &pushq.Target{BaseURL: "https://api.example.com"},
	}
}

func enqueueForTenant(ctx context.Context, pq *pushq.Client, tenantID string,
	perSecond float64, concurrent int, payload any) (*pushq.Task, error) {
	queue := "tenants/" + tenantID
	task := pushq.TaskCreate{Path: "/hooks/sync", JSONBody: payload}
	t, err := pq.CreateTask(ctx, queue, task)
	if !pushq.IsCode(err, "not_found") {
		return t, err
	}
	// First task for this tenant: create the queue, then enqueue again.
	if _, err := pq.UpsertQueue(ctx, queue, tenantConfig(perSecond, concurrent)); err != nil {
		return nil, err
	}
	return pq.CreateTask(ctx, queue, task)
}
```

**Java**

```java
import io.pushq.*;
import java.util.Map;

// The full config for one tenant: always send all of it (see the caution below).
static QueueConfig tenantConfig(double perSecond, int concurrent) {
    return QueueConfig.builder()
        .rateLimits(RateLimits.builder()
            .maxDispatchesPerSecond(perSecond)
            .maxConcurrentDispatches(concurrent)
            .build())
        .retry(RetryConfig.builder().maxAttempts(10).maxBackoffSeconds(600).build())
        .target(Target.builder().baseUrl("https://api.example.com").build())
        .build();
}

static Task enqueueForTenant(Pushq pq, String tenantId, double perSecond, int concurrent,
                             Map<String, Object> payload) {
    String queue = "tenants/" + tenantId;
    TaskCreate task = TaskCreate.builder().path("/hooks/sync").jsonBody(payload).build();
    try {
        return pq.createTask(queue, task);
    } catch (PushqException e) {
        if (!"not_found".equals(e.getCode())) throw e;
    }
    pq.upsertQueue(queue, tenantConfig(perSecond, concurrent)); // first task for this tenant
    return pq.createTask(queue, task);
}
```

**.NET**

```csharp
using Pushq;

// The full config for one tenant: always send all of it (see the caution below).
static QueueConfig TenantConfig(double perSecond, int concurrent) => new QueueConfig
{
    RateLimits = new RateLimits { MaxDispatchesPerSecond = perSecond, MaxConcurrentDispatches = concurrent },
    Retry = new RetryConfig { MaxAttempts = 10, MaxBackoffSeconds = 600 },
    Target = new Target { BaseUrl = "https://api.example.com" },
};

static async Task<PushqTask> EnqueueForTenantAsync(PushqClient pq, string tenantId,
    double perSecond, int concurrent, object payload)
{
    var queue = $"tenants/{tenantId}";
    var task = new TaskCreate { Path = "/hooks/sync", JsonBody = payload };
    try
    {
        return await pq.CreateTaskAsync(queue, task);
    }
    catch (PushqException e) when (e.Code == "not_found")
    {
        await pq.UpsertQueueAsync(queue, TenantConfig(perSecond, concurrent)); // first task for this tenant
        return await pq.CreateTaskAsync(queue, task);
    }
}
```

**curl**

```bash
# Enqueue. A 404 with "code": "not_found" means the tenant's queue doesn't exist yet.
# The "/" in the queue name is URL-encoded as %2F.
curl -X POST "https://api.pushqueue.dev/v1/queues/tenants%2Facme/tasks" \
  -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \
  -d '{"path":"/hooks/sync","json_body":{"account":"acme"}}'

# Create the queue with its full config, then send the task again.
curl -X PUT "https://api.pushqueue.dev/v1/queues/tenants%2Facme" \
  -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \
  -d '{"rate_limits":{"max_dispatches_per_second":5,"max_concurrent_dispatches":2},
       "retry":{"max_attempts":10,"max_backoff_seconds":600},
       "target":{"base_url":"https://api.example.com"}}'
```

The examples assume a client named `pq` (see [install and configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/)). JSON field names are used in the text; the SDKs use their language's casing (`maxDispatchesPerSecond` in TypeScript and Java, `max_dispatches_per_second` in Python, `MaxDispatchesPerSecond` in Go and .NET).

Use this when each customer must get a fair share of delivery, when a customer's own downstream system (their webhook endpoint, their API key with a third party) has its own limit, or when you need to stop one customer's work without stopping anyone else's.

If two of your processes hit `not_found` for the same new tenant at the same moment, both upsert the queue. That is safe: `PUT` is idempotent, and with the same config the second call changes nothing.

## Why one queue per tenant isolates customers

- **Each queue has its own token bucket and concurrency cap.** The dispatcher claims tasks from a queue only while that queue has rate-limit tokens and fewer than `max_concurrent_dispatches` requests in flight. A tenant with a million queued tasks is drained at its own rate while other tenants' queues keep dispatching at theirs. See [rate limits](https://pushqueue.dev/docs/guides/rate-limits/).
- **Retries, pause and purge are per queue.** A tenant whose endpoint is failing backs off on its own schedule, and you can pause or empty that tenant's queue alone.
- **Folders are only names.** `tenants/acme` is a queue called `acme` in the folder `tenants`. A folder has no config of its own and exists as long as some queue name uses it, so there is nothing to create up front. Folders can nest: `tenants/acme/emails` and `tenants/acme/webhooks` give one tenant several queues.

On a self-hosted server all queues still share the server's total in-flight capacity (`dispatcher.global_concurrency`, 512 by default; see [self-hosting configuration](https://pushqueue.dev/docs/self-hosting/configuration/)). On the hosted service, the Free plan allows up to 1,000 queues and Pay as you go has no queue limit (see [pricing](https://pushqueue.dev/pricing)).

:::caution[Tenant IDs must be valid queue-name segments]
Each segment of a queue name must match `[a-z0-9][a-z0-9-]*`, and the whole name is at most 200 characters. Uppercase letters, underscores and dots are rejected with `invalid_argument`. Lowercase your tenant IDs (lowercase UUIDs work) or map them to a slug before building the queue name.
:::

## Upsert replaces the whole queue config

:::danger[Omitted fields reset to defaults]
`PUT /v1/queues/{queue}` (`upsertQueue`) replaces the queue's entire configuration. Any field you leave out goes back to its default: the rate limit returns to 500 per second, `target.base_url` and `target.headers` are cleared, and `dead_letter_queue` is removed. Only `target.signing_secret` is kept when omitted. Upsert never changes the queue's state, so it won't resume a paused tenant.
:::

Pick one of two safe approaches and stick to it:

1. **Send the full config every time.** Build it from the tenant's record in your database (plan, limits, endpoint), as `tenantConfig()` does above. Any upsert, from any process, then produces the right config.
2. **Create once, then patch.** Create the queue with `POST /v1/queues` (`createQueue`) and treat `already_exists` as success. Change single settings later with `PATCH`, and never call `PUT` for tenant queues.

What breaks is mixing the two: patching a tenant's limit after a plan upgrade, then letting an enqueue path upsert a default config that silently undoes it.

## Change one tenant's rate limit

When a tenant upgrades or a tenant's endpoint asks you to slow down, patch only the rate limit. `PATCH` leaves every other field as it is.


**TypeScript**

```ts
await pq.patchQueue("tenants/acme", {
  rateLimits: { maxDispatchesPerSecond: 20, maxConcurrentDispatches: 10 },
});
```

**Python**

```python
from pushq import RateLimits

pq.patch_queue("tenants/acme",
               rate_limits=RateLimits(max_dispatches_per_second=20, max_concurrent_dispatches=10))
```

**Go**

```go
_, err := pq.PatchQueue(ctx, "tenants/acme", pushq.QueueConfig{
	RateLimits: &pushq.RateLimits{
		MaxDispatchesPerSecond:  pushq.Float64(20),
		MaxConcurrentDispatches: pushq.Int(10),
	},
}, "") // "" = leave the queue state unchanged
```

**Java**

```java
pq.patchQueue("tenants/acme", QueuePatch.builder()
    .rateLimits(RateLimits.builder().maxDispatchesPerSecond(20).maxConcurrentDispatches(10).build())
    .build());
```

**.NET**

```csharp
await pq.PatchQueueAsync("tenants/acme", new QueuePatch
{
    RateLimits = new RateLimits { MaxDispatchesPerSecond = 20, MaxConcurrentDispatches = 10 },
});
```

**curl**

```bash
curl -X PATCH "https://api.pushqueue.dev/v1/queues/tenants%2Facme" \
  -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \
  -d '{"rate_limits":{"max_dispatches_per_second":20,"max_concurrent_dispatches":10}}'
```

If you follow approach 1 (full config every time), update the tenant's record in your database too, or the next upsert sets the old limit back.

In Python, `patch_queue` is on the sync `Pushq` client only; `AsyncPushq` doesn't have it.

## List all tenant queues in a folder

List queues with `name_prefix` set to the folder, including the trailing slash. Results are ordered by name and paged (100 per page by default, up to 1,000).


**TypeScript**

```ts
let pageToken: string | undefined;
do {
  const page = await pq.listQueues({ namePrefix: "tenants/", pageSize: 1000, pageToken });
  for (const q of page.items) console.log(q.name, q.state, q.rateLimits.maxDispatchesPerSecond);
  pageToken = page.nextPageToken;
} while (pageToken);
```

**Python**

```python
token = None
while True:
    page = pq.list_queues(name_prefix="tenants/", page_size=1000, page_token=token)
    for q in page.items:
        print(q.name, q.state, q.rate_limits.max_dispatches_per_second)
    token = page.next_page_token
    if token is None:
        break
```

**Go**

```go
token := ""
for {
	queues, next, err := pq.ListQueues(ctx, pushq.ListQueuesParams{
		NamePrefix: "tenants/", PageSize: 1000, PageToken: token,
	})
	if err != nil {
		return err
	}
	for _, q := range queues {
		fmt.Println(q.Name, q.State, q.RateLimitsSet.MaxDispatchesPerSecond)
	}
	if next == "" {
		break
	}
	token = next
}
```

**Java**

```java
String token = null;
do {
    ListQueuesParams.Builder p = ListQueuesParams.builder().namePrefix("tenants/").pageSize(1000);
    if (token != null) p.pageToken(token);
    QueuePage page = pq.listQueues(p.build());
    for (Queue q : page.getQueues()) {
        System.out.println(q.getName() + " " + q.getState());
    }
    token = page.getNextPageToken();
} while (token != null && !token.isEmpty());
```

**.NET**

```csharp
string? token = null;
do
{
    var page = await pq.ListQueuesAsync(new ListQueuesOptions { NamePrefix = "tenants/", PageSize = 1000, PageToken = token });
    foreach (var q in page.Items) Console.WriteLine($"{q.Name} {q.State} {q.RateLimits.MaxDispatchesPerSecond}");
    token = page.NextPageToken;
} while (token != null);
```

**curl**

```bash
curl "https://api.pushqueue.dev/v1/queues?name_prefix=tenants/&page_size=1000" \
  -H "Authorization: Bearer $PUSHQ_API_KEY"
# Repeat with &page_token=<next_page_token> until the response has none.
```

:::caution[Listing queues needs an admin key]
Writer API keys get `403 permission_denied` on `GET /v1/queues`. Use an admin key for tooling that lists or deletes tenant queues, and a writer key for the services that only enqueue. See [API keys](https://pushqueue.dev/docs/guides/api-keys/).
:::

`name_prefix` is a plain string prefix: `tenants/acme` also matches `tenants/acme-labs`. Use `tenants/acme/` (with the trailing slash) to list only the queues inside one tenant's folder.

## Pause a noisy tenant's queue

When one tenant floods its queue or its endpoint is down, pause that queue. A paused queue keeps accepting tasks; they wait until you resume it. Every other tenant keeps running.


**TypeScript**

```ts
await pq.pauseQueue("tenants/acme");
const stats = await pq.queueStats("tenants/acme");
console.log(stats.pending, stats.oldestDueAgeSeconds);
// later
await pq.resumeQueue("tenants/acme");
```

**Python**

```python
pq.pause_queue("tenants/acme")
stats = pq.queue_stats("tenants/acme")
print(stats.pending, stats.oldest_due_age_seconds)
# later
pq.resume_queue("tenants/acme")
```

**Go**

```go
if _, err := pq.PauseQueue(ctx, "tenants/acme"); err != nil {
	return err
}
st, err := pq.QueueStats(ctx, "tenants/acme", "")
if err == nil {
	fmt.Println(st.Pending, st.OldestDueAgeSeconds)
}
// later
_, err = pq.ResumeQueue(ctx, "tenants/acme")
```

**Java**

```java
pq.pauseQueue("tenants/acme");
QueueStats s = pq.queueStats("tenants/acme");
System.out.println(s.getPending() + " " + s.getOldestDueAgeSeconds());
// later
pq.resumeQueue("tenants/acme");
```

**.NET**

```csharp
await pq.PauseQueueAsync("tenants/acme");
var stats = await pq.GetQueueStatsAsync("tenants/acme");
Console.WriteLine($"{stats.Pending} {stats.OldestDueAgeSeconds}");
// later
await pq.ResumeQueueAsync("tenants/acme");
```

**curl**

```bash
curl -X POST "https://api.pushqueue.dev/v1/queues/tenants%2Facme:pause" -H "Authorization: Bearer $PUSHQ_API_KEY"
curl "https://api.pushqueue.dev/v1/queues/tenants%2Facme/stats" -H "Authorization: Bearer $PUSHQ_API_KEY"
curl -X POST "https://api.pushqueue.dev/v1/queues/tenants%2Facme:resume" -H "Authorization: Bearer $PUSHQ_API_KEY"
```

Pausing is the right tool when you want to keep the tenant's backlog. To slow a tenant down instead of stopping it, [change its rate limit](#change-one-tenants-rate-limit). Resume also re-enables a queue that was set to `disabled`.

## Delete or purge a tenant's queue

When a customer leaves, delete the queue. Deleting removes the queue and all of its tasks; pending tasks are never delivered. To drop a tenant's backlog but keep the queue and its config, purge it instead.


**TypeScript**

```ts
await pq.purgeQueue("tenants/acme");  // drop every task, keep the queue
await pq.deleteQueue("tenants/acme"); // remove the queue and its tasks (admin key)
```

**Python**

```python
pq.purge_queue("tenants/acme")   # drop every task, keep the queue
pq.delete_queue("tenants/acme")  # remove the queue and its tasks (admin key)
```

**Go**

```go
_, err := pq.PurgeQueue(ctx, "tenants/acme")  // drop every task, keep the queue
err = pq.DeleteQueue(ctx, "tenants/acme")     // remove the queue and its tasks (admin key)
```

**Java**

```java
pq.purgeQueue("tenants/acme");   // drop every task, keep the queue
pq.deleteQueue("tenants/acme");  // remove the queue and its tasks (admin key)
```

**.NET**

```csharp
await pq.PurgeQueueAsync("tenants/acme");   // drop every task, keep the queue
await pq.DeleteQueueAsync("tenants/acme");  // remove the queue and its tasks (admin key)
```

**curl**

```bash
curl -X POST "https://api.pushqueue.dev/v1/queues/tenants%2Facme:purge" -H "Authorization: Bearer $PUSHQ_API_KEY"
curl -X DELETE "https://api.pushqueue.dev/v1/queues/tenants%2Facme" -H "Authorization: Bearer $PUSHQ_API_KEY"
```

To remove a tenant with several queues (`tenants/acme/emails`, `tenants/acme/webhooks`), list `tenants/acme/` and delete each queue. Like listing, deleting a queue needs an admin key.

## Pitfalls

- **Mixing `PUT` and `PATCH` on the same queue.** A later upsert with a default config undoes earlier patches. See [upsert replaces the whole queue config](#upsert-replaces-the-whole-queue-config).
- **Upserting before every enqueue.** It works, but doubles your API calls and makes the full-config rule apply to every code path that enqueues. The `not_found` fallback above only upserts once per tenant.
- **Deleting a queue a producer still uses.** The next enqueue gets `not_found` and the fallback recreates the queue. Stop producers for that tenant first, or pause the queue instead of deleting it.
- **One queue shared by all tenants with a high limit.** A single tenant's burst then fills the queue ahead of everyone else, and you can't pause just that tenant.

## Read more

- [Queues: settings, states and folders](https://pushqueue.dev/docs/concepts/queues/)
- [Rate limits for dispatch rate, burst and concurrency](https://pushqueue.dev/docs/guides/rate-limits/)
- [Throttle requests to a third-party API](https://pushqueue.dev/docs/patterns/throttle-a-third-party-api/)
- [API keys and roles](https://pushqueue.dev/docs/guides/api-keys/)
