# Rate limits and concurrency

> Rate limit HTTP tasks with pushq: dispatch rate, burst size and concurrency per queue, Retry-After back-pressure, and recipes for APIs and tenants.

Source: https://pushqueue.dev/docs/guides/rate-limits/

Every pushq queue has three rate limits that decide how fast its tasks are delivered: a dispatch rate, a burst size and a concurrency cap. They protect the endpoint receiving the tasks, whether that's your own service or a third-party API with a quota. This guide explains how the limits work together and gives recipes for rate limiting an API, per-tenant limits and incidents.

The examples assume a client named `pq` (see [Install & configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/)). Tables use JSON field names; SDKs use their language's casing (`maxDispatchesPerSecond`, `max_dispatches_per_second`, `MaxDispatchesPerSecond`).

## Queue rate limit settings

| Parameter | Type | Default | Description |
|---|---|---|---|
| `rate_limits.max_dispatches_per_second` | number | `500` | How many deliveries may start per second, on average. Greater than 0, at most 10000; fractions allowed. |
| `rate_limits.max_burst_size` | integer | `0` (auto) | How many deliveries may start at once after the queue has been idle. 0 to 10000; `0` means `max_dispatches_per_second` rounded up, between 1 and 500. |
| `rate_limits.max_concurrent_dispatches` | integer | `1000` | How many deliveries may be in flight at the same time. 1 to 10000. |

A task is delivered only when all of these hold:

1. The queue is `running` and the task's schedule time has passed.
2. A rate token is available (`max_dispatches_per_second` and `max_burst_size`).
3. Fewer than `max_concurrent_dispatches` of the queue's requests are in flight.
4. The queue isn't cooling down after a [`Retry-After`](#back-pressure-with-retry-after) response.
5. The server has a free delivery slot (see [Server-wide concurrency](#server-wide-concurrency)).

Retries go through the same limits as first attempts. Only [`:run`](https://pushqueue.dev/docs/concepts/tasks/#run-a-task-now) bypasses them.

### Dispatch rate and burst size (token bucket)

Each queue has a bucket that holds up to `max_burst_size` tokens and refills at `max_dispatches_per_second` tokens per second. Starting a delivery takes one token.

- After the queue has been idle, the bucket is full, so up to `max_burst_size` tasks start at once. After that, deliveries are spaced out at the refill rate.
- With the auto burst, a queue limited to 10 per second can start 10 tasks at once, then continues at 10 per second.
- With `max_burst_size: 1`, deliveries are evenly spaced: at 10 per second, one every 100 ms.
- Fractional rates work for slow trickles: `0.2` is one delivery every 5 seconds.

Use an explicit small burst when the receiver counts requests in short windows and a sudden spike would trip its limit even though your average is fine.

### Max concurrent dispatches

`max_concurrent_dispatches` caps the requests in flight for the queue. When the cap is reached, the next delivery waits until one finishes, however many tokens are available. It protects endpoints whose capacity is limited by workers, connections or database load rather than by requests per second.

### How rate and concurrency limits interact

The effective throughput is the lower of the rate limit and what concurrency allows:

```text
throughput ≈ min(max_dispatches_per_second, max_concurrent_dispatches / average response time)
```

For example, with `max_dispatches_per_second: 100` and `max_concurrent_dispatches: 5`, an endpoint that takes 500 ms per request gets at most 5 / 0.5 s = 10 deliveries per second. The concurrency cap is the binding limit, and the rate limit only matters if the endpoint speeds up. Slow responses therefore lower throughput automatically, which is usually what you want.

### Server-wide concurrency

On top of the per-queue limits, the server caps the total number of deliveries in flight across all queues. On a self-hosted server this is `dispatcher.global_concurrency` (environment variable `PUSHQ_GLOBAL_CONCURRENCY`), default 512. When every slot is busy, queues wait for a free slot, so a per-queue `max_concurrent_dispatches` above this value has no extra effect. See [server configuration](https://pushqueue.dev/docs/self-hosting/configuration/).

## Back-pressure with Retry-After

Your endpoint can slow pushq down without any configuration change. Answer `429 Too Many Requests` or `503 Service Unavailable` with a `Retry-After` header (seconds, or an HTTP date):

- the task is retried after that delay (capped at its `max_backoff_seconds`) instead of the normal backoff;
- the whole queue starts no new deliveries for that delay, up to 30 seconds.

Without the header, a 429 or 503 is an ordinary failure with normal backoff and no cool-down. A `Retry-After` response still counts as a failed attempt toward `max_attempts`. Details are in [Retries](https://pushqueue.dev/docs/concepts/retries/#retry-after-and-the-queue-cool-down).

This handler sheds load when it is too busy:


**TypeScript**

```ts
app.post("/hooks/sync", async (req, res) => {
  if (inFlight >= MAX_IN_FLIGHT) {
    res.set("Retry-After", "10").sendStatus(429);
    return;
  }
  // ... do the work ...
  res.sendStatus(204);
});
```

**Python**

```python
from fastapi import Response

@app.post("/hooks/sync")
async def sync(request: Request):
    if in_flight >= MAX_IN_FLIGHT:
        return Response(status_code=429, headers={"Retry-After": "10"})
    # ... do the work ...
    return Response(status_code=204)
```

**Go**

```go
func handleSync(w http.ResponseWriter, r *http.Request) {
	if inFlight.Load() >= maxInFlight {
		w.Header().Set("Retry-After", "10")
		w.WriteHeader(http.StatusTooManyRequests)
		return
	}
	// ... do the work ...
	w.WriteHeader(http.StatusNoContent)
}
```

**Java**

```java
@PostMapping("/hooks/sync")
public ResponseEntity<Void> sync(@RequestBody byte[] payload) {
    if (inFlight.get() >= MAX_IN_FLIGHT) {
        return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).header("Retry-After", "10").build();
    }
    // ... do the work ...
    return ResponseEntity.noContent().build();
}
```

**.NET**

```csharp
app.MapPost("/hooks/sync", (HttpResponse res) =>
{
    if (inFlight >= MaxInFlight)
    {
        res.Headers.RetryAfter = "10";
        return Results.StatusCode(StatusCodes.Status429TooManyRequests);
    }
    // ... do the work ...
    return Results.NoContent();
});
```

These are your endpoint's handlers, so there is no curl version.

## Rate limiting recipes

### Rate limit a third-party API

Say a provider allows 10 requests per second and 5 concurrent connections, and you call it from your own handler for each task. Stay a little under the limits, and spread requests evenly so a burst after an idle period doesn't trip a per-second window:


**TypeScript**

```ts
await pq.upsertQueue("crm-sync", {
  rateLimits: { maxDispatchesPerSecond: 8, maxBurstSize: 1, maxConcurrentDispatches: 5 },
  target: { baseUrl: "https://worker.example.com" },
});
```

**Python**

```python
from pushq import RateLimits, Target

pq.upsert_queue(
    "crm-sync",
    rate_limits=RateLimits(max_dispatches_per_second=8, max_burst_size=1, max_concurrent_dispatches=5),
    target=Target(base_url="https://worker.example.com"),
)
```

**Go**

```go
_, err := pq.UpsertQueue(ctx, "crm-sync", pushq.QueueConfig{
	RateLimits: &pushq.RateLimits{
		MaxDispatchesPerSecond:  pushq.Float64(8),
		MaxBurstSize:            pushq.Int(1),
		MaxConcurrentDispatches: pushq.Int(5),
	},
	Target: &pushq.Target{BaseURL: "https://worker.example.com"},
})
```

**Java**

```java
pq.upsertQueue("crm-sync", QueueConfig.builder()
    .rateLimits(RateLimits.builder().maxDispatchesPerSecond(8).maxBurstSize(1).maxConcurrentDispatches(5).build())
    .target(Target.builder().baseUrl("https://worker.example.com").build())
    .build());
```

**.NET**

```csharp
await pq.UpsertQueueAsync("crm-sync", new QueueConfig
{
    RateLimits = new RateLimits { MaxDispatchesPerSecond = 8, MaxBurstSize = 1, MaxConcurrentDispatches = 5 },
    Target = new Target { BaseUrl = "https://worker.example.com" },
});
```

**curl**

```bash
curl -X PUT https://api.pushqueue.dev/v1/queues/crm-sync \
  -H "Authorization: Bearer $PUSHQ_API_KEY" \
  -d '{
    "rate_limits": {"max_dispatches_per_second": 8, "max_burst_size": 1, "max_concurrent_dispatches": 5},
    "target": {"base_url": "https://worker.example.com"}
  }'
```

If the provider returns `429`, pass it through from your handler with the provider's `Retry-After` so pushq [backs off](#back-pressure-with-retry-after). Use one queue per provider limit: if two kinds of work share the same API key, put them in the same queue so they share the budget. The [throttle a third-party API pattern](https://pushqueue.dev/docs/patterns/throttle-a-third-party-api/) has a complete example.

### Per-tenant rate limits with one queue per tenant

When each customer has their own quota (or you want one noisy customer not to delay the others), give each tenant its own queue in a `tenants/` [folder](https://pushqueue.dev/docs/concepts/queues/#queue-folders). Queues are independent, so each gets its own rate limit and backlog. Because PUT is an idempotent upsert, you can call it right before every enqueue; the queue is created the first time and left unchanged after that.


**TypeScript**

```ts
const LIMITS = { free: 1, pro: 20 } as const;

async function enqueueForTenant(tenantId: string, plan: keyof typeof LIMITS, payload: unknown) {
  const queue = `tenants/${tenantId}`; // tenantId must be lowercase [a-z0-9-]
  await pq.upsertQueue(queue, {
    rateLimits: { maxDispatchesPerSecond: LIMITS[plan], maxConcurrentDispatches: 5 },
    target: { baseUrl: "https://api.example.com" },
  });
  await pq.createTask(queue, { path: "/hooks/tenant-sync", jsonBody: payload });
}
```

**Python**

```python
LIMITS = {"free": 1, "pro": 20}

def enqueue_for_tenant(tenant_id: str, plan: str, payload: dict) -> None:
    queue = f"tenants/{tenant_id}"  # tenant_id must be lowercase [a-z0-9-]
    pq.upsert_queue(
        queue,
        rate_limits=RateLimits(max_dispatches_per_second=LIMITS[plan], max_concurrent_dispatches=5),
        target=Target(base_url="https://api.example.com"),
    )
    pq.create_task(queue, path="/hooks/tenant-sync", json_body=payload)
```

**Go**

```go
var limits = map[string]float64{"free": 1, "pro": 20}

func enqueueForTenant(ctx context.Context, tenantID, plan string, payload any) error {
	queue := "tenants/" + tenantID // tenantID must be lowercase [a-z0-9-]
	_, err := pq.UpsertQueue(ctx, queue, pushq.QueueConfig{
		RateLimits: &pushq.RateLimits{
			MaxDispatchesPerSecond:  pushq.Float64(limits[plan]),
			MaxConcurrentDispatches: pushq.Int(5),
		},
		Target: &pushq.Target{BaseURL: "https://api.example.com"},
	})
	if err != nil {
		return err
	}
	_, err = pq.CreateTask(ctx, queue, pushq.TaskCreate{Path: "/hooks/tenant-sync", JSONBody: payload})
	return err
}
```

**Java**

```java
static final Map<String, Double> LIMITS = Map.of("free", 1.0, "pro", 20.0);

void enqueueForTenant(String tenantId, String plan, Object payload) {
    String queue = "tenants/" + tenantId; // tenantId must be lowercase [a-z0-9-]
    pq.upsertQueue(queue, QueueConfig.builder()
        .rateLimits(RateLimits.builder().maxDispatchesPerSecond(LIMITS.get(plan)).maxConcurrentDispatches(5).build())
        .target(Target.builder().baseUrl("https://api.example.com").build())
        .build());
    pq.createTask(queue, TaskCreate.builder().path("/hooks/tenant-sync").jsonBody(payload).build());
}
```

**.NET**

```csharp
static readonly Dictionary<string, double> Limits = new() { ["free"] = 1, ["pro"] = 20 };

async Task EnqueueForTenantAsync(string tenantId, string plan, object payload)
{
    var queue = $"tenants/{tenantId}"; // tenantId must be lowercase [a-z0-9-]
    await pq.UpsertQueueAsync(queue, new QueueConfig
    {
        RateLimits = new RateLimits { MaxDispatchesPerSecond = Limits[plan], MaxConcurrentDispatches = 5 },
        Target = new Target { BaseUrl = "https://api.example.com" },
    });
    await pq.CreateTaskAsync(queue, new TaskCreate { Path = "/hooks/tenant-sync", JsonBody = payload });
}
```

**curl**

```bash
curl -X PUT https://api.pushqueue.dev/v1/queues/tenants%2Facme \
  -H "Authorization: Bearer $PUSHQ_API_KEY" \
  -d '{"rate_limits": {"max_dispatches_per_second": 20, "max_concurrent_dispatches": 5}, "target": {"base_url": "https://api.example.com"}}'

curl -X POST https://api.pushqueue.dev/v1/queues/tenants%2Facme/tasks \
  -H "Authorization: Bearer $PUSHQ_API_KEY" \
  -d '{"path": "/hooks/tenant-sync", "json_body": {"account": "acme"}}'
```

Things to know (the [per-tenant queues pattern](https://pushqueue.dev/docs/patterns/per-tenant-queues/) covers this in more depth):

- Queue names allow only lowercase letters, digits and hyphens in each segment, so map tenant IDs to that form (for example, lowercase a UUID).
- The PUT sets the whole configuration each time, so a plan change takes effect on the tenant's next enqueue. A paused tenant queue stays paused, because PUT never changes the state.
- List or monitor all tenant queues with `name_prefix=tenants/` (this needs an admin API key) and check each one's [stats](https://pushqueue.dev/docs/concepts/queues/#queue-stats-and-monitoring).
- On the hosted service, the Free plan allows up to 1,000 queues and Pay as you go is unlimited; see [pricing](https://pushqueue.dev/pricing).

When you only need per-tenant visibility, not separate limits, one shared queue with task IDs like `acme-...` also works: `id_prefix=acme-` filters both the task list and the stats.

### Change rate limits at runtime

PATCH changes one limit and leaves the rest of the configuration alone. The new limit applies to the next delivery, including tasks already waiting in the queue.


**TypeScript**

```ts
await pq.patchQueue("crm-sync", { rateLimits: { maxDispatchesPerSecond: 20 } });
```

**Python**

```python
pq.patch_queue("crm-sync", rate_limits=RateLimits(max_dispatches_per_second=20))
```

**Go**

```go
_, err := pq.PatchQueue(ctx, "crm-sync", pushq.QueueConfig{
	RateLimits: &pushq.RateLimits{MaxDispatchesPerSecond: pushq.Float64(20)},
}, "")
```

**Java**

```java
pq.patchQueue("crm-sync", QueuePatch.builder()
    .rateLimits(RateLimits.builder().maxDispatchesPerSecond(20).build())
    .build());
```

**.NET**

```csharp
await pq.PatchQueueAsync("crm-sync", new QueuePatch
{
    RateLimits = new RateLimits { MaxDispatchesPerSecond = 20 },
});
```

**curl**

```bash
curl -X PATCH https://api.pushqueue.dev/v1/queues/crm-sync \
  -H "Authorization: Bearer $PUSHQ_API_KEY" \
  -d '{"rate_limits": {"max_dispatches_per_second": 20}}'
```

Use this when a provider raises your quota, or to drain a large backlog faster overnight. Prefer PATCH over PUT here: a PUT with only `rate_limits` would reset the queue's retry settings and clear its target.

### Slow down or pause during an incident

When the receiving service is struggling, first slow the queue down. Lowering concurrency is usually the most direct relief, because it caps the load regardless of how slow responses get:


**TypeScript**

```ts
await pq.patchQueue("crm-sync", { rateLimits: { maxDispatchesPerSecond: 1, maxConcurrentDispatches: 1 } });
```

**Python**

```python
pq.patch_queue("crm-sync", rate_limits=RateLimits(max_dispatches_per_second=1, max_concurrent_dispatches=1))
```

**Go**

```go
_, err := pq.PatchQueue(ctx, "crm-sync", pushq.QueueConfig{
	RateLimits: &pushq.RateLimits{MaxDispatchesPerSecond: pushq.Float64(1), MaxConcurrentDispatches: pushq.Int(1)},
}, "")
```

**Java**

```java
pq.patchQueue("crm-sync", QueuePatch.builder()
    .rateLimits(RateLimits.builder().maxDispatchesPerSecond(1).maxConcurrentDispatches(1).build())
    .build());
```

**.NET**

```csharp
await pq.PatchQueueAsync("crm-sync", new QueuePatch
{
    RateLimits = new RateLimits { MaxDispatchesPerSecond = 1, MaxConcurrentDispatches = 1 },
});
```

**curl**

```bash
curl -X PATCH https://api.pushqueue.dev/v1/queues/crm-sync \
  -H "Authorization: Bearer $PUSHQ_API_KEY" \
  -d '{"rate_limits": {"max_dispatches_per_second": 1, "max_concurrent_dispatches": 1}}'
```

If the service is down, pause the queue instead. New tasks are still accepted and wait, and no retries are used up while paused. Requests already in flight finish normally.


**TypeScript**

```ts
await pq.pauseQueue("crm-sync");
// ... after the fix ...
await pq.runTask("crm-sync", "welcome-user-42"); // optional: test one task while still paused
await pq.resumeQueue("crm-sync");
```

**Python**

```python
pq.pause_queue("crm-sync")
# ... after the fix ...
pq.run_task("crm-sync", "welcome-user-42")  # optional: test one task while still paused
pq.resume_queue("crm-sync")
```

**Go**

```go
_, err := pq.PauseQueue(ctx, "crm-sync")
// ... after the fix ...
_, err = pq.RunTask(ctx, "crm-sync", "welcome-user-42") // optional: test one task while still paused
_, err = pq.ResumeQueue(ctx, "crm-sync")
```

**Java**

```java
pq.pauseQueue("crm-sync");
// ... after the fix ...
pq.runTask("crm-sync", "welcome-user-42"); // optional: test one task while still paused
pq.resumeQueue("crm-sync");
```

**.NET**

```csharp
await pq.PauseQueueAsync("crm-sync");
// ... after the fix ...
await pq.RunTaskAsync("crm-sync", "welcome-user-42"); // optional: test one task while still paused
await pq.ResumeQueueAsync("crm-sync");
```

**curl**

```bash
curl -X POST https://api.pushqueue.dev/v1/queues/crm-sync:pause -H "Authorization: Bearer $PUSHQ_API_KEY"
curl -X POST https://api.pushqueue.dev/v1/queues/crm-sync/tasks/welcome-user-42:run -H "Authorization: Bearer $PUSHQ_API_KEY"
curl -X POST https://api.pushqueue.dev/v1/queues/crm-sync:resume -H "Authorization: Bearer $PUSHQ_API_KEY"
```

On resume, the backlog drains at the queue's limits, starting with a burst of up to `max_burst_size`. If the service is fragile right after recovery, keep the lowered limits for a while and raise them with PATCH once it is stable. Watch `oldest_due_age_seconds` in the queue's [stats](https://pushqueue.dev/docs/concepts/queues/#queue-stats-and-monitoring) to see the backlog shrink.

### Limit concurrency for a fragile endpoint

For an endpoint that can only handle one request at a time, such as a legacy system or a job that locks a shared resource, set `max_concurrent_dispatches: 1`. Each delivery starts only after the previous one has finished.


**TypeScript**

```ts
await pq.upsertQueue("legacy-erp", {
  rateLimits: { maxConcurrentDispatches: 1 },
  retry: { minBackoffSeconds: 5, maxBackoffSeconds: 600 },
  target: { baseUrl: "https://erp.example.com" },
});
```

**Python**

```python
pq.upsert_queue(
    "legacy-erp",
    rate_limits=RateLimits(max_concurrent_dispatches=1),
    retry=Retry(min_backoff_seconds=5, max_backoff_seconds=600),
    target=Target(base_url="https://erp.example.com"),
)
```

**Go**

```go
_, err := pq.UpsertQueue(ctx, "legacy-erp", pushq.QueueConfig{
	RateLimits: &pushq.RateLimits{MaxConcurrentDispatches: pushq.Int(1)},
	Retry:      &pushq.Retry{MinBackoffSeconds: pushq.Float64(5), MaxBackoffSeconds: pushq.Float64(600)},
	Target:     &pushq.Target{BaseURL: "https://erp.example.com"},
})
```

**Java**

```java
pq.upsertQueue("legacy-erp", QueueConfig.builder()
    .rateLimits(RateLimits.builder().maxConcurrentDispatches(1).build())
    .retry(RetryConfig.builder().minBackoffSeconds(5).maxBackoffSeconds(600).build())
    .target(Target.builder().baseUrl("https://erp.example.com").build())
    .build());
```

**.NET**

```csharp
await pq.UpsertQueueAsync("legacy-erp", new QueueConfig
{
    RateLimits = new RateLimits { MaxConcurrentDispatches = 1 },
    Retry = new RetryConfig { MinBackoffSeconds = 5, MaxBackoffSeconds = 600 },
    Target = new Target { BaseUrl = "https://erp.example.com" },
});
```

**curl**

```bash
curl -X PUT https://api.pushqueue.dev/v1/queues/legacy-erp \
  -H "Authorization: Bearer $PUSHQ_API_KEY" \
  -d '{
    "rate_limits": {"max_concurrent_dispatches": 1},
    "retry": {"min_backoff_seconds": 5, "max_backoff_seconds": 600},
    "target": {"base_url": "https://erp.example.com"}
  }'
```

The longer `min_backoff_seconds` keeps a failing endpoint from being hit again within a fraction of a second. Keep the handler's response time well under `dispatch_deadline_seconds`: with one slot, a hanging request blocks the whole queue until it times out.

:::note
A concurrency of 1 means one request at a time, not strict ordering. Due tasks are generally picked in schedule-time order, but a failed task is rescheduled for later and the tasks behind it go ahead. Don't rely on pushq for ordering; have the handler cope with tasks arriving out of order.
:::

## How to choose rate limit values

- **Start from the receiver's real limit.** For a third-party API, use its documented rate and concurrency, about 80 percent of each, to leave room for other callers and clock drift between its window and yours.
- **Size concurrency from latency.** To sustain *R* deliveries per second against an endpoint that takes *L* seconds per request, you need about *R* × *L* concurrent slots. 50 per second at 200 ms needs about 10; give it some headroom.
- **Use the burst to absorb or avoid spikes.** Leave it on auto when the receiver handles short spikes well. Set it to 1 when the receiver enforces per-second windows strictly.
- **Remember retries share the budget.** When the endpoint fails, retries consume tokens and slots too. Keep `min_backoff_seconds` reasonable so a broken endpoint doesn't spend the whole rate on retries.
- **Watch the stats.** A rising `oldest_due_age_seconds` means the limits are lower than the incoming rate; a rising `errors_last_1m` means the receiver is struggling and the limits may be too high.

## Read more

- [Throttle a third-party API](https://pushqueue.dev/docs/patterns/throttle-a-third-party-api/): a complete worked example.
- [Per-tenant queues](https://pushqueue.dev/docs/patterns/per-tenant-queues/): isolate customers with one queue each.
- [Retry backoff and max attempts](https://pushqueue.dev/docs/concepts/retries/): Retry-After and the queue cool-down in detail.
- [Queues and queue configuration](https://pushqueue.dev/docs/concepts/queues/): every queue setting and the stats API.
- [Going to production](https://pushqueue.dev/docs/guides/going-to-production/): limits and monitoring checklist.
