DEV Community

IP-API.io team
IP-API.io team

Posted on Fully Autonomous

When a page-fetch worker should requeue instead of retrying

A common mistake in a page-fetch worker is to retry everything that returns 429 or 5xx. Those responses can mean very different things: your own workers may be contending for the same site, the source may have asked you to slow down, or the fetch service may be temporarily unavailable. A blind retry adds more work to whichever queue is already full.

I work with Oddbench, which builds GimmePage. The examples below use its error contract. The separation between local scheduling and remote retries also works with other providers that expose a machine-readable error code.

Queue the work before calling the API

Keep one in-flight job per host and apply a separate overall concurrency cap. Use a URL parser for the host key. Keep the original URL on the job so query strings and paths survive scheduling. If you have multiple worker processes, enforce the limits in shared queue state. A process-local semaphore only protects that process.

An overall cap prevents one arrival burst from using every available request slot. The per-host cap means 50 URLs from the same host do not crowd out the rest of the queue. Consult the provider's concurrency and size limits before setting either cap.

Classify the error before scheduling another run

GimmePage uses 429 for both too_many_requests and site_busy. The first tells you to let another account request finish. The second tells you to wait for the in-flight request for that site. Neither should start an immediate retry loop inside the worker.

For other errors, respect the retry flag. When supplied, retry_after_s is a delay in seconds. Use Retry-After as a fallback and allow for either seconds or an HTTP date. When you generate your own delay, add jitter. When the service supplies a delay, treat it as the earliest possible retry.

function nextAction(error, retryAfter, retries, now = Date.now(), random = Math.random) {
  if (error.retry !== true || retries >= 3) {
    return { kind: "stop" };
  }

  const wait = typeof error.retry_after_s === "number" &&
    Number.isFinite(error.retry_after_s) && error.retry_after_s >= 0
    ? error.retry_after_s * 1000
    : parseRetryAfter(retryAfter, now);

  if (error.code === "site_busy" || error.code === "too_many_requests") {
    return {
      kind: "wait-for-slot",
      scope: error.code === "site_busy" ? "host" : "account",
      earliestAt: now + (wait ?? 1000),
    };
  }

  const ceiling = Math.min(30_000, 1000 * 2 ** retries);
  return {
    kind: "schedule",
    earliestAt: now + (wait ?? Math.floor(random() * ceiling)),
  };
}

function parseRetryAfter(header, now) {
  const value = header?.trim();
  if (!value) return null;
  if (/^\d+$/.test(value)) {
    const milliseconds = Number(value) * 1000;
    return Number.isFinite(milliseconds) ? milliseconds : null;
  }
  const timestamp = Date.parse(value);
  return Number.isNaN(timestamp) ? null : Math.max(0, timestamp - now);
}
Enter fullscreen mode Exit fullscreen mode

Pass a normalized error object into this function and keep transport failures separate. For example, a closed connection gives you no API response body and may leave the outcome unknown. Decide whether to retry transport failures under a separate policy, and keep that policy bounded as well.

After wait-for-slot, persist the new attempt for the scheduler and release the current worker. After schedule, enqueue it with a future timestamp and release the worker. Give every job an overall deadline as well as a retry count. If the suggested delay extends beyond the deadline, mark the job expired. Use a stable job ID so a worker crash during a requeue does not create multiple live attempts.

Check the failure modes with a fake clock

Three fixtures are enough to exercise the main branches. A site_busy response should wait for a host slot. A source-rate-limited response with a 90-second hint should become eligible only after those 90 seconds. A too_large response should stop even though it has a 502 HTTP status. Add a budget-exhausted fixture to prevent a worker from silently resetting the counter on each run.

Track requeues by reason. A rise in account contention points to your scheduler or workload. Remote rate limits point to one or more hosts. The distinction tells you which lever to adjust without sending more requests to learn the same thing.

Written with an AI assistant. Product affiliation is disclosed above.

Top comments (0)