Per-tenant queues and rate limits
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
Section titled “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.
import { Pushq, PushqError } from "pushq";
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); }}import osfrom 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)// 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)}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);}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); }}# 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). 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
Section titled “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_dispatchesrequests 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. - 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/acmeis a queue calledacmein the foldertenants. 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/emailsandtenants/acme/webhooksgive 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). On the hosted service, the Free plan allows up to 1,000 queues and Pay as you go has no queue limit (see pricing).
Upsert replaces the whole queue config
Section titled “Upsert replaces the whole queue config”Pick one of two safe approaches and stick to it:
- 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. - Create once, then patch. Create the queue with
POST /v1/queues(createQueue) and treatalready_existsas success. Change single settings later withPATCH, and never callPUTfor 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
Section titled “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.
await pq.patchQueue("tenants/acme", { rateLimits: { maxDispatchesPerSecond: 20, maxConcurrentDispatches: 10 },});from pushq import RateLimits
pq.patch_queue("tenants/acme", rate_limits=RateLimits(max_dispatches_per_second=20, max_concurrent_dispatches=10))_, err := pq.PatchQueue(ctx, "tenants/acme", pushq.QueueConfig{ RateLimits: &pushq.RateLimits{ MaxDispatchesPerSecond: pushq.Float64(20), MaxConcurrentDispatches: pushq.Int(10), },}, "") // "" = leave the queue state unchangedpq.patchQueue("tenants/acme", QueuePatch.builder() .rateLimits(RateLimits.builder().maxDispatchesPerSecond(20).maxConcurrentDispatches(10).build()) .build());await pq.PatchQueueAsync("tenants/acme", new QueuePatch{ RateLimits = new RateLimits { MaxDispatchesPerSecond = 20, MaxConcurrentDispatches = 10 },});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
Section titled “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).
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);token = Nonewhile 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: breaktoken := ""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}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());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 "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.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
Section titled “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.
await pq.pauseQueue("tenants/acme");const stats = await pq.queueStats("tenants/acme");console.log(stats.pending, stats.oldestDueAgeSeconds);// laterawait pq.resumeQueue("tenants/acme");pq.pause_queue("tenants/acme")stats = pq.queue_stats("tenants/acme")print(stats.pending, stats.oldest_due_age_seconds)# laterpq.resume_queue("tenants/acme")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")pq.pauseQueue("tenants/acme");QueueStats s = pq.queueStats("tenants/acme");System.out.println(s.getPending() + " " + s.getOldestDueAgeSeconds());// laterpq.resumeQueue("tenants/acme");await pq.PauseQueueAsync("tenants/acme");var stats = await pq.GetQueueStatsAsync("tenants/acme");Console.WriteLine($"{stats.Pending} {stats.OldestDueAgeSeconds}");// laterawait pq.ResumeQueueAsync("tenants/acme");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. Resume also re-enables a queue that was set to disabled.
Delete or purge a tenant’s queue
Section titled “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.
await pq.purgeQueue("tenants/acme"); // drop every task, keep the queueawait pq.deleteQueue("tenants/acme"); // remove the queue and its tasks (admin key)pq.purge_queue("tenants/acme") # drop every task, keep the queuepq.delete_queue("tenants/acme") # remove the queue and its tasks (admin key)_, err := pq.PurgeQueue(ctx, "tenants/acme") // drop every task, keep the queueerr = pq.DeleteQueue(ctx, "tenants/acme") // remove the queue and its tasks (admin key)pq.purgeQueue("tenants/acme"); // drop every task, keep the queuepq.deleteQueue("tenants/acme"); // remove the queue and its tasks (admin key)await pq.PurgeQueueAsync("tenants/acme"); // drop every task, keep the queueawait pq.DeleteQueueAsync("tenants/acme"); // remove the queue and its tasks (admin key)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
Section titled “Pitfalls”- Mixing
PUTandPATCHon the same queue. A later upsert with a default config undoes earlier patches. See 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_foundfallback above only upserts once per tenant. - Deleting a queue a producer still uses. The next enqueue gets
not_foundand 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.