Throttle requests to 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
Section titled “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:
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 } });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})_, 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},})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());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 -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). 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
Section titled “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.
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
Section titled “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.
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);});import osimport httpxfrom 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)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)}@RestControllerpublic 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(); }}// "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 before calling the provider, and make the handler idempotent: 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
Section titled “How the queue slows down after a 429”pushq’s dispatcher enforces the limit on the server, at delivery time:
- Token bucket. Each queue has a bucket that holds up to
max_burst_sizetokens and refills atmax_dispatches_per_second. A task is claimed for delivery only when a token is available. - Concurrency cap. No new task is claimed while the queue has
max_concurrent_dispatchesrequests in flight. - 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.
- 429 or 503 with
Retry-After. When your endpoint answers429or503with aRetry-Afterheader (seconds or an HTTP date):- that task’s next attempt is scheduled
Retry-Afterfrom now instead of after its normal backoff, capped at the queue’sretry.max_backoff_seconds; - the whole queue stops claiming new tasks for
Retry-After, capped at 30 seconds. Requests already in flight finish normally.
- that task’s next attempt is scheduled
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 for the retry details.
Share one rate limit across many producers
Section titled “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).
- Split by limit, not by caller. If the provider limits endpoints separately (for example, search versus writes), use one queue per limit:
crm-api/searchandcrm-api/writes.
Call the provider directly from pushq
Section titled “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 errors that will never succeed.
Pitfalls
Section titled “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 ofRetry-After. - Watching the backlog. If the provider limit is lower than your enqueue rate, the queue grows. Check
oldest_due_age_secondsanderrors_last_1mfrom the queue stats to see whether you are falling behind.