# Throttle requests to a third-party API

> Stay under a third-party API rate limit with pushq. Map the provider's limit to queue settings, relay 429 Retry-After, and share one limit across producers.

Source: https://pushqueue.dev/docs/patterns/throttle-a-third-party-api/

This pattern keeps your calls to a third-party API (a CRM, an email provider, a payment or AI API) under the provider's documented rate limit. You send every call through one pushq queue whose rate limit matches the provider's, and your handler passes the provider's `429` and `Retry-After` back to pushq so the queue slows down when the provider asks it to.

## Match the queue's rate limit to the provider's limit

Say the provider documents "25 requests per second, at most 10 concurrent requests". Create one queue for that provider with a little headroom, then enqueue every call to it:


**TypeScript**

```ts
await pq.upsertQueue("crm-api", {
  rateLimits: {
    maxDispatchesPerSecond: 20,  // provider allows 25/s; keep headroom
    maxBurstSize: 20,
    maxConcurrentDispatches: 10, // provider allows 10 in flight
  },
  retry: { maxAttempts: 20, minBackoffSeconds: 1, maxBackoffSeconds: 600 },
  target: { baseUrl: "https://api.example.com" },
});

await pq.createTask("crm-api", { path: "/hooks/crm-sync", jsonBody: { contactId: 42 } });
```

**Python**

```python
from pushq import RateLimits, Retry, Target

pq.upsert_queue(
    "crm-api",
    rate_limits=RateLimits(
        max_dispatches_per_second=20,   # provider allows 25/s; keep headroom
        max_burst_size=20,
        max_concurrent_dispatches=10,   # provider allows 10 in flight
    ),
    retry=Retry(max_attempts=20, min_backoff_seconds=1, max_backoff_seconds=600),
    target=Target(base_url="https://api.example.com"),
)

pq.create_task("crm-api", path="/hooks/crm-sync", json_body={"contact_id": 42})
```

**Go**

```go
_, err := pq.UpsertQueue(ctx, "crm-api", pushq.QueueConfig{
	RateLimits: &pushq.RateLimits{
		MaxDispatchesPerSecond:  pushq.Float64(20), // provider allows 25/s; keep headroom
		MaxBurstSize:            pushq.Int(20),
		MaxConcurrentDispatches: pushq.Int(10), // provider allows 10 in flight
	},
	Retry: &pushq.Retry{
		MaxAttempts:       pushq.Int(20),
		MinBackoffSeconds: pushq.Float64(1),
		MaxBackoffSeconds: pushq.Float64(600),
	},
	Target: &pushq.Target{BaseURL: "https://api.example.com"},
})
if err != nil {
	return err
}

_, err = pq.CreateTask(ctx, "crm-api", pushq.TaskCreate{
	Path:     "/hooks/crm-sync",
	JSONBody: map[string]any{"contact_id": 42},
})
```

**Java**

```java
pq.upsertQueue("crm-api", QueueConfig.builder()
    .rateLimits(RateLimits.builder()
        .maxDispatchesPerSecond(20)      // provider allows 25/s; keep headroom
        .maxBurstSize(20)
        .maxConcurrentDispatches(10)     // provider allows 10 in flight
        .build())
    .retry(RetryConfig.builder().maxAttempts(20).minBackoffSeconds(1).maxBackoffSeconds(600).build())
    .target(Target.builder().baseUrl("https://api.example.com").build())
    .build());

pq.createTask("crm-api", TaskCreate.builder()
    .path("/hooks/crm-sync")
    .jsonBody(Map.of("contact_id", 42))
    .build());
```

**.NET**

```csharp
await pq.UpsertQueueAsync("crm-api", new QueueConfig
{
    RateLimits = new RateLimits
    {
        MaxDispatchesPerSecond = 20,   // provider allows 25/s; keep headroom
        MaxBurstSize = 20,
        MaxConcurrentDispatches = 10,  // provider allows 10 in flight
    },
    Retry = new RetryConfig { MaxAttempts = 20, MinBackoffSeconds = 1, MaxBackoffSeconds = 600 },
    Target = new Target { BaseUrl = "https://api.example.com" },
});

await pq.CreateTaskAsync("crm-api", new TaskCreate { Path = "/hooks/crm-sync", JsonBody = new { contact_id = 42 } });
```

**curl**

```bash
curl -X PUT https://api.pushqueue.dev/v1/queues/crm-api \
  -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \
  -d '{"rate_limits":{"max_dispatches_per_second":20,"max_burst_size":20,"max_concurrent_dispatches":10},
       "retry":{"max_attempts":20,"min_backoff_seconds":1,"max_backoff_seconds":600},
       "target":{"base_url":"https://api.example.com"}}'

curl -X POST https://api.pushqueue.dev/v1/queues/crm-api/tasks \
  -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \
  -d '{"path":"/hooks/crm-sync","json_body":{"contact_id":42}}'
```

pushq delivers each task to your endpoint (`https://api.example.com/hooks/crm-sync`), and your handler makes the provider call. The examples assume a client named `pq` (see [install and configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/)). The text uses JSON field names; 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 a provider rejects or bans clients that exceed a documented requests-per-second, requests-per-minute or concurrency limit, and the calls can happen in the background.

## Translate a provider rate limit into queue settings

| Provider documents | Queue setting | Example |
| --- | --- | --- |
| N requests per second | `rate_limits.max_dispatches_per_second` = N, or a bit less | 25/s → `20` |
| N requests per minute | `max_dispatches_per_second` = N / 60, and a small `max_burst_size` | 120/min → `2`, burst `0` (auto = 2) |
| One request every N seconds | `max_dispatches_per_second` = 1 / N, `max_burst_size` = 1 | every 5 s → `0.2`, burst `1` |
| At most N requests in flight | `rate_limits.max_concurrent_dispatches` = N | 10 concurrent → `10` |
| A short burst above the steady rate | `rate_limits.max_burst_size` = the burst | burst of 50 → `50` |

Valid ranges: `max_dispatches_per_second` is greater than 0 and at most 10,000 (fractions are fine), `max_burst_size` is 0 to 10,000, and `max_concurrent_dispatches` is 1 to 10,000. A `max_burst_size` of `0` means auto: the rate rounded up, between 1 and 500.

:::caution[A full burst plus a minute of refill can exceed a per-minute cap]
The rate limit is a token bucket: up to `max_burst_size` tasks can go out at once, then tokens refill at `max_dispatches_per_second`. With 120/min configured as 2 per second and a burst of 120, an idle queue could send 120 tasks immediately and another 120 over the next minute. For per-minute limits keep the burst small (auto, or 1).
:::

Concurrency matters as much as rate when the provider is slow. At 20 dispatches per second and 3-second responses, 60 requests would be in flight; `max_concurrent_dispatches: 10` caps that at 10, which in turn caps the real rate at about 3 per second. Set both.

## Relay 429 and Retry-After from the provider

When the provider says "slow down", answer pushq with `429 Too Many Requests` (or `503`) and a `Retry-After` header. pushq then delays that task and briefly stops dispatching the whole queue.


**TypeScript**

```ts
app.post("/hooks/crm-sync", express.json(), async (req, res) => {
  const r = await fetch("https://api.crm.example.com/v1/contacts", {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.CRM_TOKEN}`, "Content-Type": "application/json" },
    body: JSON.stringify(req.body),
  });
  if (r.status === 429 || r.status === 503) {
    // Pass the provider's back-off on to pushq.
    res.set("Retry-After", r.headers.get("Retry-After") ?? "10");
    return res.sendStatus(429);
  }
  res.sendStatus(r.ok ? 204 : 502);
});
```

**Python**

```python
import os
import httpx
from fastapi import FastAPI, Request, Response

app = FastAPI()
crm = httpx.AsyncClient(base_url="https://api.crm.example.com",
                        headers={"Authorization": f"Bearer {os.environ['CRM_TOKEN']}"})

@app.post("/hooks/crm-sync")
async def crm_sync(request: Request) -> Response:
    r = await crm.post("/v1/contacts", content=await request.body(),
                       headers={"Content-Type": "application/json"})
    if r.status_code in (429, 503):
        # Pass the provider's back-off on to pushq.
        return Response(status_code=429,
                        headers={"Retry-After": r.headers.get("Retry-After", "10")})
    return Response(status_code=204 if r.is_success else 502)
```

**Go**

```go
func handleCRMSync(w http.ResponseWriter, r *http.Request) {
	req, _ := http.NewRequestWithContext(r.Context(), "POST", "https://api.crm.example.com/v1/contacts", r.Body)
	req.Header.Set("Authorization", "Bearer "+os.Getenv("CRM_TOKEN"))
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}
	defer resp.Body.Close()
	if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusServiceUnavailable {
		retryAfter := resp.Header.Get("Retry-After")
		if retryAfter == "" {
			retryAfter = "10"
		}
		// Pass the provider's back-off on to pushq.
		w.Header().Set("Retry-After", retryAfter)
		w.WriteHeader(http.StatusTooManyRequests)
		return
	}
	if resp.StatusCode >= 300 {
		w.WriteHeader(http.StatusBadGateway)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}
```

**Java**

```java
@RestController
public class CrmSync {
    private final HttpClient http = HttpClient.newHttpClient();

    @PostMapping("/hooks/crm-sync")
    public ResponseEntity<Void> sync(@RequestBody byte[] payload) throws Exception {
        HttpRequest req = HttpRequest.newBuilder(URI.create("https://api.crm.example.com/v1/contacts"))
            .header("Authorization", "Bearer " + System.getenv("CRM_TOKEN"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofByteArray(payload))
            .build();
        HttpResponse<Void> resp = http.send(req, HttpResponse.BodyHandlers.discarding());
        int status = resp.statusCode();
        if (status == 429 || status == 503) {
            // Pass the provider's back-off on to pushq.
            String retryAfter = resp.headers().firstValue("Retry-After").orElse("10");
            return ResponseEntity.status(429).header("Retry-After", retryAfter).build();
        }
        return ResponseEntity.status(status < 300 ? 204 : 502).build();
    }
}
```

**.NET**

```csharp
// "crm" HttpClient registered at startup with BaseAddress and the Authorization header.
app.MapPost("/hooks/crm-sync", async (HttpRequest req, IHttpClientFactory factory) =>
{
    var crm = factory.CreateClient("crm");
    using var body = new StreamContent(req.Body);
    body.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    using var resp = await crm.PostAsync("/v1/contacts", body);
    if ((int)resp.StatusCode is 429 or 503)
    {
        // Pass the provider's back-off on to pushq.
        req.HttpContext.Response.Headers["Retry-After"] = resp.Headers.RetryAfter?.ToString() ?? "10";
        return Results.StatusCode(429);
    }
    return resp.IsSuccessStatusCode ? Results.NoContent() : Results.StatusCode(502);
});
```

These handlers are plain web code, so there is no curl tab. In production, also [verify the webhook signature](https://pushqueue.dev/docs/concepts/delivery/#verify-webhook-signatures-in-your-handler) before calling the provider, and make the handler [idempotent](https://pushqueue.dev/docs/patterns/idempotent-handlers/): a task can be delivered more than once.

The fallback of `"10"` seconds applies when the provider sends a 429 without `Retry-After`. Without the header, pushq treats a 429 as an ordinary failure: normal backoff and no queue cool-down.

## How the queue slows down after a 429

pushq's dispatcher enforces the limit on the server, at delivery time:

1. **Token bucket.** Each queue has a bucket that holds up to `max_burst_size` tokens and refills at `max_dispatches_per_second`. A task is claimed for delivery only when a token is available.
2. **Concurrency cap.** No new task is claimed while the queue has `max_concurrent_dispatches` requests in flight.
3. **Retries go through the same limits.** A retry is a pending task like any other, so it uses a token and a concurrency slot. Retries can't push you over the provider's limit.
4. **429 or 503 with `Retry-After`.** When your endpoint answers `429` or `503` with a `Retry-After` header (seconds or an HTTP date):
   - that task's next attempt is scheduled `Retry-After` from now instead of after its normal backoff, capped at the queue's `retry.max_backoff_seconds`;
   - the whole queue stops claiming new tasks for `Retry-After`, capped at **30 seconds**. Requests already in flight finish normally.

So a single 429 pauses the queue briefly and pushes the throttled task back by as much as the provider asked. See [Retry-After and the queue cool-down](https://pushqueue.dev/docs/concepts/retries/#retry-after-and-the-queue-cool-down) for the retry details.

:::caution[Every 429 counts as an attempt]
A `429` is a failed attempt and counts toward `retry.max_attempts` (and `max_retry_duration_seconds`). If a provider throttles you for a long time, tasks can run out of attempts and fail. Give provider queues a generous `max_attempts` (or `-1` for unlimited with a `max_retry_duration_seconds`), and a [dead-letter queue](https://pushqueue.dev/docs/concepts/dead-letter-queues/) to catch the rest.
:::

:::caution[max_backoff_seconds caps Retry-After]
If the provider sends `Retry-After: 3600` and the queue's `max_backoff_seconds` is 300, the task retries after 300 seconds and probably gets throttled again. Set `max_backoff_seconds` at least as high as the longest `Retry-After` you expect.
:::

## Share one rate limit across many producers

The limit belongs to the queue, not to the code that enqueues. Ten services, a cron job and a backfill script can all enqueue into `crm-api` at once; pushq still dispatches at most 20 per second with 10 in flight. You don't need a distributed lock or a shared Redis counter.

To make that hold:

- **Route every call to the provider through the queue.** Any code path that calls the provider directly uses up the same provider quota without pushq seeing it.
- **Use one queue per provider credential.** Provider limits are usually per API key or per account. If each of your customers connects their own provider account, give each one a queue (see [per-tenant queues](https://pushqueue.dev/docs/patterns/per-tenant-queues/)).
- **Split by limit, not by caller.** If the provider limits endpoints separately (for example, search versus writes), use one queue per limit: `crm-api/search` and `crm-api/writes`.

:::danger[Run now bypasses the rate limit]
`POST /v1/queues/{queue}/tasks/{task_id}:run` dispatches a pending task immediately, ignoring the queue's rate limit, `max_concurrent_dispatches` and paused state. Don't use it in bulk on a provider queue.
:::

## Call the provider directly from pushq

If the provider call needs no logic of your own, a task can target the provider's URL directly: set `url` to the absolute URL and pass the provider's auth header in the task's `headers` (or once in the queue's `target.headers`). pushq then sees the provider's own `429` and `Retry-After`.

The trade-off is that the credential is stored with the task or queue and is returned by the API (task `headers` in the full view, queue `target.headers` on every read), and any non-2xx answer, including permanent errors like `400`, is retried. A handler of your own keeps the secret in your service and lets you [stop retrying](https://pushqueue.dev/docs/patterns/stop-retrying/) errors that will never succeed.

## Pitfalls

- **Rate set at exactly the provider's limit.** Clock skew and the provider's own window boundaries can still trip it. Leave 10 to 20 percent headroom.
- **Ignoring concurrency.** A rate limit alone doesn't stop slow responses from piling up in flight.
- **Calls outside the queue.** Synchronous calls from your web app share the provider quota with the queue.
- **Short `max_backoff_seconds`.** It caps how long a throttled task waits, regardless of `Retry-After`.
- **Watching the backlog.** If the provider limit is lower than your enqueue rate, the queue grows. Check `oldest_due_age_seconds` and `errors_last_1m` from the [queue stats](https://pushqueue.dev/docs/concepts/queues/) to see whether you are falling behind.

## Read more

- [Rate limits: dispatch rate, burst size and concurrency](https://pushqueue.dev/docs/guides/rate-limits/)
- [Retries, backoff and Retry-After](https://pushqueue.dev/docs/concepts/retries/)
- [Per-tenant queues and rate limits](https://pushqueue.dev/docs/patterns/per-tenant-queues/)
- [Idempotent task handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/)
- [Stop retrying permanent errors](https://pushqueue.dev/docs/patterns/stop-retrying/)
