Skip to content

Rate limits and safe retries

The UserLoop API's rate limit, what a 429 looks like, how Idempotency-Key makes a retried write safe, and a retry routine you can copy.

Each API key can make about 120 requests a minute. Over that, the API answers 429 with how long to wait. Retrying is safe for reads, and for writes when you send an Idempotency-Key: a write sent twice with the same key happens once.

The rate limit

The limit is per API key: about 120 requests a minute. Every response states it in a header:

RateLimit-Policy: 120;w=60

That is 120 requests in a window of 60 seconds. The count is approximate, and UserLoop doesn’t report how many requests you have left: there is no RateLimit-Remaining header. Plan to stay well under it, and handle 429 when you don’t.

  • Each key has its own limit. Two apps with a key each don’t slow each other down. An organisation can have up to 25 active keys.
  • Requests with keys UserLoop doesn’t know are limited by address, to about 30 a minute. Valid keys never count against it, so one server can use any number of valid keys.
  • Some actions have a lower limit of their own, which the 429’s detail names. For example, a webhook endpoint takes 5 test events a minute.

When you’re over the limit

The API answers 429 with a Retry-After header in seconds:

HTTP/2 429
Content-Type: application/problem+json
Retry-After: 60
UserLoop-Request-Id: req_9Tn4XcB2vL7mQ0aK
RateLimit-Policy: 120;w=60
{
  "type": "https://app.userloop.io/api/v1/problems/rate_limited",
  "title": "Rate limited",
  "status": 429,
  "detail": "Too many requests with this key. Try again in a minute.",
  "instance": "req_9Tn4XcB2vL7mQ0aK",
  "code": "rate_limited",
  "retry_after": 60
}

Wait at least the Retry-After time before you send that key’s next request. The same number is in the body as retry_after.

Two other answers also carry Retry-After:

Status and code Retry-After What it means
429 rate_limited 60 Too many requests with this key, or too many of one action.
503 unavailable 30 A service UserLoop depends on can’t be reached just now.
409 idempotency_in_progress 1 A request with the same Idempotency-Key is still running. Retry to get its result.

Make a write safe to retry

Retrying a read does no harm. Retrying a write can: if a POST timed out, you can’t tell whether UserLoop created the thing. Send an Idempotency-Key header on the write, and use the same key on every retry of it. UserLoop runs the request once and answers every repeat with the first result.

curl -s -X POST https://app.userloop.io/api/v1/exports \
  -H "Authorization: Bearer ulk_live_…" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 8f14e45f-ceea-467a-9575-3b8e1c5a2d6b" \
  -d '{"range": "30d"}'

The first time, the export is queued and you get 202:

{
  "id": "kn7d2x9c4v1b8m5q3w6e0r7t2y4u8i1o",
  "status": "queued",
  "recipients": 0,
  "delivered_by": "download once ready (nobody is emailed)"
}

Send the same request with the same key again and you get the same 202 and the same body, with one more header, and no second export:

Idempotent-Replayed: true

How it works:

  • Which requests: every POST, PATCH and DELETE. On GET the header is ignored.

  • The key: any 1 to 255 printable ASCII characters. A UUID for each new write works well. Anything else gets 400 invalid_request.

  • How long it is kept: 24 hours, for each API key. Another API key with the same Idempotency-Key is a different request.

  • The same key with a different request (another method, path or body) gets 422 idempotency_key_reused. Use a new key for a new request.

  • While the first request is still running, a repeat gets 409 idempotency_in_progress with Retry-After: 1. Retry and you get its result once it finishes.

  • Most errors are kept too. An error such as a 404 or a 409 conflict is replayed as it was, so fix the request and send it with a new key. Only 429, 500 and 503 aren’t kept: a retry with the same key runs the request again.

  • Large answers: when the first answer was over 64 KB, a replay has the same status but only this body. Read the resource to see where it stands.

    {
      "replayed": true,
      "body_stored": false,
      "detail": "The first response to this request was larger than 64 KB, so only its status was kept. Read the resource to see its current state."
    }
  • Webhook signing secrets are returned only to the first request. A replay of POST /webhooks or POST /webhooks/{webhook_id}/roll-secret has "secret": null and a note; roll the secret again if you lost it.

The request ID

Every response, successful or not, has a UserLoop-Request-Id header such as req_7Hq2LmZ0aB4cD9eF. An error repeats it as instance in the body. Log it with every failed request, and quote it if you contact UserLoop support: it identifies that one request.

A retry routine

This routine retries what is safe to retry and nothing else:

  • no answer at all (a network error or a timeout), for any method, because a write carries the same Idempotency-Key on every attempt;
  • 429 and 503, after Retry-After;
  • 409 idempotency_in_progress, after Retry-After;
  • 500 on a GET only. A write that got 500 may have been done in part, and isn’t kept for replay, so read the resource before you try it again.

Every other error is returned straight away: sending the same request again would get the same answer.

Save as userloop.mjs (Node 18 or later), and set USERLOOP_API_KEY to your key (ulk_live_…).

import { randomUUID } from "node:crypto";

const BASE = "https://app.userloop.io/api/v1";
const KEY = process.env.USERLOOP_API_KEY;
const MAX_ATTEMPTS = 5;

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// Retry-After when the API sent it, else 1, 2, 4, 8 seconds with jitter.
function delayMs(res, attempt) {
  const seconds = Number(res?.headers.get("Retry-After"));
  if (seconds > 0) return seconds * 1000;
  return 2 ** (attempt - 1) * 1000 * (0.5 + Math.random() / 2);
}

export async function userloop(method, path, body) {
  const headers = { Authorization: `Bearer ${KEY}` };
  // One key for every attempt of this write, so it happens once however often it is sent.
  if (method !== "GET") headers["Idempotency-Key"] = randomUUID();
  if (body !== undefined) headers["Content-Type"] = "application/json";

  for (let attempt = 1; ; attempt++) {
    let res;
    try {
      res = await fetch(BASE + path, {
        method,
        headers,
        body: body === undefined ? undefined : JSON.stringify(body),
        signal: AbortSignal.timeout(30_000),
      });
    } catch (error) {
      if (attempt === MAX_ATTEMPTS) throw error;
      await sleep(delayMs(null, attempt));
      continue;
    }

    const text = await res.text();
    const data = text ? JSON.parse(text) : null;
    if (res.ok) return data;

    const retry =
      res.status === 429 ||
      res.status === 503 ||
      data?.code === "idempotency_in_progress" ||
      (res.status === 500 && method === "GET");
    if (!retry || attempt === MAX_ATTEMPTS) {
      const requestId = res.headers.get("UserLoop-Request-Id");
      throw new Error(`${res.status} ${data?.code} (${requestId}): ${data?.detail}`);
    }
    await sleep(delayMs(res, attempt));
  }
}

// Example: list live surveys, then request a CSV export of the last 30 days.
const surveys = await userloop("GET", "/surveys?status=active");
console.log(`${surveys.data.length} live surveys`);
const exported = await userloop("POST", "/exports", { range: "30d" });
console.log(`Export ${exported.id} is ${exported.status}`);

Run node userloop.mjs. You should see the number of live surveys, then a line such as Export kn7d2x9c4v1b8m5q3w6e0r7t2y4u8i1o is queued. The export needs a key with Manage reports (reports:write).

If several workers share one key, they share its limit: slow them all down when one gets 429, rather than letting each retry on its own.

Type to search…

↑↓ navigate↵ selectEsc close