How to retry when ClearRun returns 429

Wait the number of seconds in the Retry-After header, then send the same request again. In the SDK, the error has it as err.retryAfter, in seconds, taken from the reply body or the Retry-After header.

Last updated

Applies to version 1.2.0 of @clearrun/sdk and @clearrun/cli.

Steps

  1. With fetch

    async function post(url, body, tries = 3) {
      for (let i = 0; i < tries; i++) {
        const res = await fetch(url, { method: 'POST', headers, body: JSON.stringify(body) });
        if (res.status !== 429) return res;
        const wait = Number(res.headers.get('Retry-After') ?? 60);
        await new Promise((r) => setTimeout(r, wait * 1000));
      }
      throw new Error('Still rate limited');
    }
  2. With the SDK

    for (let i = 0; i < 3; i++) {
      try {
        return await clearrun.score({ responseText });
      } catch (err) {
        if (err.status !== 429) throw err;
        const wait = err.retryAfter ?? 15 * (i + 1);
        await new Promise((r) => setTimeout(r, wait * 1000));
      }
    }

A 429 is not charged

Rate-limited calls are refused before scoring.