Geonode logo
Geonode Team

Geonode Team

Updated: October 23, 2026

Published: October 23, 2026

Scraper API Error Handling and Retries: Status Codes, Idempotency and Why Failed Requests Shouldn't Cost You

A retry loop is the easiest thing in a scraper to write badly. This guide separates the two questions every retry has to answer - is another attempt worth it, and is it safe - then builds a reference retry policy in Python and Node.js with the tests that keep the rules honest.

A retry loop is the easiest thing in a scraper to write badly. The naive version wraps every call in for attempt in range(3) and sleeps a second between tries, and it works right up until the day the API is slow instead of broken. Then it hammers a struggling service, turns one timed-out job submission into three real jobs, and writes your API key into the log line that was supposed to help you debug it.

This guide covers the decisions that make the difference: which status codes you fix in the request and which you wait out, how to read the retryable flag the API already gives you, exponential backoff with full jitter under both an attempt cap and a wall-clock budget, and the distinction that causes the most damage when it is missed — retrying a read is safe, re-sending a job submission after a timeout is not. There is a reference retry policy in Python and Node.js at the end, with the test suite that proves the rules hold.

The two questions every retry has to answer

Most retry code asks one question: did this fail in a way that might go away? That question is necessary and it is not sufficient. There is a second one, and skipping it is what turns a retry loop into a billing incident.

Is another attempt worth it? Would the same call plausibly succeed if you made it again? A 503 says yes. A 401 says no, and no amount of waiting will produce a valid API key.

Is another attempt safe? Could the retry duplicate work the server already did? A job lookup can run a thousand times and still mean the same thing. A job submission that timed out may have been accepted before the connection dropped, and the second attempt creates a second job.

A request that times out shows the two questions coming apart. It is clearly worth retrying, because a timeout is the most transient failure there is. It is only safe to retry if the operation is idempotent. The Scraper API documentation does not currently describe an idempotency key, so "safe" has to come from the shape of the operation itself, not from a header you can send.

Every rule in the rest of this guide follows from keeping those two questions separate.

The status code map

These are the codes the error handling reference lists, with what each one means for your retry logic. The "Safe to re-send" column answers the second question: whether repeating a non-idempotent request, such as a job submission, could duplicate work.

CodeMeaningWorth retryingSafe to re-send
400Invalid requestNo — fix the requestYes, nothing ran
401API key is missing or invalidNo — fix the credentialsYes, nothing ran
402Payment required or insufficient request balanceNo — top up firstYes, nothing ran
404Job, webhook or other resource was not foundNo — check the identifierYes, nothing ran
408Map request timed out during URL discoveryYesMap carries no charge
409Batch or crawl job cannot be cancelled in its current stateNo — re-read the job stateYes, nothing ran
422Validation error or extraction failedDepends — see belowYes, the server answered
429Request throttled or work concurrency limit reachedYes, after a delayYes, refused before any work
500Internal server errorYesNo — state unknown
502Billing service returned an upstream error"Retryable depends on the billing error"No — state unknown
503Service or billing service temporarily unavailableYesNo — state unknown
504Synchronous extraction timed out waiting for the browser workerDocumented as retryableNo — state unknown

Two rows deserve more than a table cell.

422 is not one error. The reference documents it as "Validation error or extraction failed", and those are different problems with different response shapes. Treating every 422 as a malformed request means you will keep retrying a page that genuinely cannot be extracted, or give up on a transient upstream failure because you assumed your payload was wrong. Tell them apart by the body, not the status.

429 is safe to re-send even for a POST. This is the exception that proves the rule. Throttling is a refusal issued before any extraction work starts, so there is no half-finished job on the other side. The same is true of 400, 401 and 402. What makes a retry unsafe is not the severity of the error, it is whether the server might have started work you cannot see.

The schema includes 429 responses, but no public numeric rate limit is specified in the current contract. Treat a 429 as "slow down", not as a number you can design around.

Read the retryable flag before you read the status code

The Scraper API returns two different error shapes, and which one you get depends on where the request failed. Both of the examples below are from the documentation, not from live calls we made.

A validation failure returns the FastAPI-style shape, with no retry hint because none is needed — the request itself is wrong:

{
  "detail": [
    {
      "type": "value_error",
      "loc": ["body", "url"],
      "msg": "Value error, URL must contain a valid hostname.",
      "input": "not-a-url"
    }
  ]
}

An extraction failure returns a different shape, and this one tells you what to do:

{
  "error": {
    "code": "UNPROCESSABLE_CONTENT",
    "message": "The target page could not be extracted.",
    "retryable": false,
    "details": null
  },
  "tokens_charged": 0
}

The documentation is direct about how to use it: "Use the retryable field to decide whether a retry may help. For retryable failures, use exponential backoff and avoid retrying in a tight loop."

When that field is present, it outranks the status code. The server knows things a three-digit number cannot express — whether the target page is permanently unparseable, whether an upstream dependency is merely flapping. A 500 carrying retryable: false means stop, and a 422 carrying retryable: true means try again, whatever your status-code table says.

One detail matters more than it looks. When the flag is absent, that is not the same as retryable: false. "The API did not say" and "the API said no" are different facts, and collapsing them turns every plain 503 into a hard failure. Code it as a three-state value — true, false, or unknown — and fall back to the status map only in the unknown case.

Different endpoints may return different error structures. Parse defensively: look for the shape you recognise, and treat anything else as unknown rather than assuming a field exists.

Exponential backoff with full jitter

Fixed delays are worse than they look. Twenty workers that all hit a 503 and all sleep exactly one second will come back in the same second, and the service that was recovering gets the same spike that knocked it over.

Exponential growth fixes the pressure. Jitter fixes the synchronisation. Together they turn a herd into a spread:

def backoff(attempt, base_delay=0.5, max_delay=8.0):
    # Full jitter: a uniform draw from [0, capped exponential].
    ceiling = min(max_delay, base_delay * (2 ** (attempt - 1)))
    return random.random() * ceiling

That is full jitter — the delay is drawn from the whole interval, so two clients that failed at the same moment almost never return at the same moment. The common alternative, equal jitter, keeps half the delay fixed and randomises the rest; it spreads clients less and is worth the trade only when you need a guaranteed minimum pause between attempts.

The cap matters as much as the growth. Without max_delay, attempt eight sleeps for a minute, and a worker sitting on a dead connection for a minute is usually worse for your pipeline than failing fast and moving on.

Attempt caps are not enough: use a time budget

Almost every retry wrapper has a max_attempts. Far fewer have a wall-clock budget, and the budget is the one that saves you in production.

Here is why an attempt cap alone is not a limit. With four attempts, a half-second base and an eight-second cap, the delays can land at 0.4, 1.8 and 7.6 seconds — call it ten seconds of sleeping plus four request timeouts of fifteen seconds each. That single call can hold a worker for over a minute, and nothing in max_attempts=4 warned you. Multiply by a pool of twenty workers and your throughput collapses while every individual call looks reasonable.

A budget bounds the thing you actually care about:

deadline = time.monotonic() + total_budget
...
if time.monotonic() + delay >= deadline:
    break          # do not sleep past the budget just to wake up and give up

Note what that check does: it refuses to sleep when the sleep would end past the deadline. Sleeping anyway and then discovering you are out of budget wastes the caller's time and pins the worker for nothing. Check before you sleep, not after.

Pick the budget from the caller's tolerance, not from the API. A user waiting on a synchronous extraction gives you a few seconds. A nightly batch job can afford minutes. The same retry policy with two different budgets is usually the right answer, rather than two different retry policies.

Retry-After and what happens when the budget runs out

When a response carries a Retry-After header, honour it instead of your own backoff. The server is telling you when it expects to be ready, and that is better information than a random draw.

Parse it conservatively. The header has two legal forms — a number of seconds, and an HTTP date — and the date form is a trap on a client whose clock may be skewed. Reading a date wrong gives you a delay of minutes or a delay of zero. Take the numeric form, ignore the date form, and fall back to your own backoff when you cannot parse it:

def parse_retry_after(headers):
    for key in headers:
        if key.lower() == "retry-after":
            try:
                seconds = float(str(headers[key]).strip())
            except (TypeError, ValueError):
                return None          # HTTP-date form: fall back to backoff
            return seconds if seconds >= 0 else None
    return None

Also cap it. A Retry-After: 600 is a perfectly valid instruction and a terrible thing to obey inside a request handler. Honour the header up to your remaining budget, and treat anything longer as "not within this call's budget" — fail, and let the job be rescheduled by whatever runs above you.

When the budget runs out, fail loudly and carry the evidence. An exhausted retry is not an error to swallow. Raise it with the attempt log attached — what each attempt returned, why the policy decided to continue, how long it slept — because that log is the only thing that distinguishes "the API was down for ninety seconds" from "we have been retrying a permanent 422 all night". The reference implementation raises RetryExhausted carrying the list of decisions for exactly this reason.

What the caller does with that failure depends on the operation. For a read, re-queue and try later. For a submission that never got a confirmed response, do not re-queue it as a fresh submission — see the next two sections.

Retrying a read is not retrying a submission

This is the distinction worth the whole article.

Reads are idempotent. Job lookup (GET /v1/extract/{job_id}), statistics, webhook lookup and health checks return the same thing however many times you ask. Retry them freely, under backoff and a budget. The pricing reference confirms the economics: job lookup, statistics, webhooks, health checks and Map operations do not extract content and carry no charge, so a retried poll costs you latency and nothing else.

Submissions are not. POST /v1/extract creates work. If you send it and the connection times out, you are left with a question you cannot answer from the client side: did the server receive it? Three outcomes are consistent with the same silence — the request never arrived, it arrived and was rejected, or it arrived, was accepted, and the job is running right now. Re-sending turns the third case into two jobs for one piece of work, and the second one is a successful extraction, which is the kind that gets charged.

So the default must be: do not retry POST on an ambiguous failure. Not because POST is special in HTTP, but because the failure is ambiguous and the operation creates state.

"Ambiguous" has a precise meaning here, and it is narrower than "failed":

  • Ambiguous — a transport timeout, a connection error, or any 5xx. The server may have done the work before the response went missing.
  • Definitive — any deliberate 4xx rejection with a body you could read. The server answered. It did not start work, and the pricing page backs this up: authentication errors, validation errors and requests rejected before extraction are not charged.

That is why the table above marks 429 as safe to re-send and 503 as not, even though both are temporary. The question was never "is this error temporary", it was "might there be a job on the other side that I cannot see".

Making the rule explicit in the API of your retry helper is worth doing, because it forces a decision at every call site instead of letting a default decide silently:

policy.run(lambda: get_job(job_id), idempotent=True)     # read, retry freely
policy.run(lambda: submit(url),     idempotent=False)    # create, stop if ambiguous

Only pass idempotent=True for a submission if you have proven that repeating it cannot create a second unit of work. "The error looked transient" is not that proof.

Preventing duplicate jobs after a timeout

If you cannot safely re-send, what do you do with a submission that timed out?

The clean answer in most APIs is an idempotency key: you generate an identifier, send it with the request, and the server collapses duplicates for you. The Scraper API documentation does not currently describe an idempotency key or request identifier, so that option is not on the table today. Do not design around one, and be sceptical of any retry wrapper that implies it has one.

What works without server-side support is recording your intent before you create anything, so that an ambiguous failure leaves a trace you can reconcile against:

# 1. Record the intent first, with a unique constraint on the target URL
#    plus whatever makes a job distinct for you (run id, batch id, date).
intent_id = db.insert_intent(url=url, run_id=run_id)   # raises on duplicate

# 2. Submit. Store the job id the moment it comes back.
try:
    out = policy.run(lambda: submit(url), idempotent=False)
    db.attach_job_id(intent_id, out.response.body["job_id"])
except DuplicateRisk:
    # 3. The job may exist. Do not submit again — mark it for reconciliation.
    db.mark_unconfirmed(intent_id)

An intent row with no job_id is the signal that something needs checking, and reconciliation is cheap because lookups are free. Three mechanisms resolve those rows, and which you use depends on how you already collect results:

  • The webhook. If you register one, the completion arrives whether or not your submit call got a response. Match it to the unconfirmed intent and you are done. The webhooks and polling guide covers building a receiver that verifies signatures and dedupes deliveries.
  • The unique constraint. The database refuses the second insert before a second request is ever made. This is the cheapest protection and the one most often left out.
  • A sweep. Unconfirmed intents older than your job timeout get re-submitted deliberately, once, by a process that knows it is re-submitting — not silently, inside a retry loop, by code that thinks it is making a first attempt.

The important part is the ordering. Record intent, then submit, then record the result. Code that submits first and writes to the database afterwards has no way to tell a lost response from a request that was never sent.

A reference retry policy in Python

What follows is a retry policy, not an HTTP client and not the official SDK. It takes a transport callable and decides whether to call it again. That split is deliberate: it keeps the policy testable without a network, and it lets you layer the policy onto whatever client you already use.

Before you layer it onto the Python SDK, check what the SDK does on its own. Its retry behaviour is not documented on that page, and stacking an uncontrolled retry loop on top of a client that already retries multiplies attempts rather than adding them — four of yours over three of its own is twelve requests, and every one of them counts against the same concurrency limit. Find out first; wrap second.

import random
import time
from dataclasses import dataclass, field
from typing import Any, Callable, Mapping, Optional


@dataclass(frozen=True)
class Response:
    status: int
    headers: Mapping[str, str] = field(default_factory=dict)
    body: Any = None


class TransportTimeout(Exception):
    # The transport gave up waiting. The server's state is unknown.
    pass


class TransportError(Exception):
    # Connection failed before a complete response arrived. State unknown.
    pass


# Deliberate rejections: the server decided not to do the work, so a re-send
# cannot duplicate anything.
_DEFINITIVE = frozenset({400, 401, 402, 404, 409, 422, 429})
# Outcomes where we cannot tell whether the server did the work.
_AMBIGUOUS_STATUS = frozenset({408, 500, 502, 503, 504})
# Of the above, the ones where another attempt is plausibly useful.
_WORTH_RETRY = frozenset({408, 429, 500, 502, 503, 504})


@dataclass(frozen=True)
class Decision:
    retry: bool
    ambiguous: bool
    reason: str
    retry_after: Optional[float] = None


def _error_retryable(body):
    # Returns True, False, or None for "the API did not say".
    if isinstance(body, Mapping):
        err = body.get("error")
        if isinstance(err, Mapping) and isinstance(err.get("retryable"), bool):
            return err["retryable"]
    return None


def classify(outcome) -> Decision:
    if isinstance(outcome, TransportTimeout):
        return Decision(True, True, "transport timeout, server state unknown")
    if isinstance(outcome, TransportError):
        return Decision(True, True, "transport error, server state unknown")

    status = outcome.status
    if 200 <= status < 300:
        return Decision(False, False, "success")

    flag = _error_retryable(outcome.body)
    ambiguous = status in _AMBIGUOUS_STATUS or status not in _DEFINITIVE
    retry_after = parse_retry_after(outcome.headers)

    if flag is not None:
        # The server answered directly. Trust it over the status code.
        return Decision(flag, ambiguous and flag,
                        "error.retryable=%s" % str(flag).lower(), retry_after)
    if status in _WORTH_RETRY:
        return Decision(True, ambiguous, str(status), retry_after)
    return Decision(False, ambiguous, str(status), retry_after)

The policy itself applies the decision under both limits:

class RetryPolicy:
    def __init__(self, max_attempts=4, total_budget=30.0,
                 base_delay=0.5, max_delay=8.0,
                 sleep=time.sleep, clock=time.monotonic, rng=random.random):
        if max_attempts < 1:
            raise ValueError("max_attempts must be at least 1")
        if total_budget <= 0:
            raise ValueError("total_budget must be positive")
        self.max_attempts, self.total_budget = max_attempts, total_budget
        self.base_delay, self.max_delay = base_delay, max_delay
        self._sleep, self._clock, self._rng = sleep, clock, rng

    def backoff(self, attempt):
        ceiling = min(self.max_delay, self.base_delay * (2 ** max(0, attempt - 1)))
        return self._rng() * ceiling

    def run(self, transport, *, idempotent):
        deadline = self._clock() + self.total_budget
        attempts, slept = [], 0.0

        for attempt in range(1, self.max_attempts + 1):
            try:
                outcome = transport()
            except (TransportTimeout, TransportError) as exc:
                outcome = exc

            decision = classify(outcome)
            attempts.append(decision)

            if not decision.retry:
                if isinstance(outcome, Response) and 200 <= outcome.status < 300:
                    return Outcome(outcome, attempt, slept)
                raise NotRetryable(outcome, decision)

            # Worth retrying is not the same as safe to retry.
            if decision.ambiguous and not idempotent:
                raise DuplicateRisk(outcome, decision, attempts)

            if attempt == self.max_attempts:
                break

            delay = decision.retry_after if decision.retry_after is not None \
                else self.backoff(attempt)
            if self._clock() + delay >= deadline:
                break
            self._sleep(delay)
            slept += delay

        raise RetryExhausted(attempts, attempts[-1])

sleep, clock and rng are constructor arguments so the tests can run instantly and deterministically. That is not test-only decoration — it is the reason the suite below can assert that the policy never sleeps past its budget, which is impossible to check reliably against a real clock.

The transport is yours to supply. Two things it must do: respect a timeout, and release the HTTP response so the connection returns to the pool. A transport that leaks connections turns a retry storm into a resource leak.

import httpx

def make_transport(client, method, url, **kwargs):
    def transport():
        try:
            with client.stream(method, url, **kwargs) as r:
                r.read()                      # drain so the connection is reusable
                try:
                    body = r.json()
                except ValueError:
                    body = None
                return Response(r.status_code, dict(r.headers), body)
        except httpx.TimeoutException as exc:
            raise TransportTimeout(str(exc)) from exc
        except httpx.HTTPError as exc:
            raise TransportError(str(exc)) from exc
    return transport


policy = RetryPolicy(max_attempts=4, total_budget=30.0)

# A read: retry freely.
job = policy.run(make_transport(client, "GET", f"{BASE}/v1/extract/{job_id}",
                                headers=HEADERS, timeout=15.0),
                 idempotent=True)

# A submission: stop on anything ambiguous.
try:
    created = policy.run(make_transport(client, "POST", f"{BASE}/v1/extract",
                                        headers=HEADERS, json=payload, timeout=30.0),
                         idempotent=False)
except DuplicateRisk:
    mark_for_reconciliation(payload["url"])

The same policy in Node.js

Same rules, same structure, delays in seconds so they line up with Retry-After.

export function classify(outcome) {
  if (outcome instanceof TransportTimeout) {
    return { retry: true, ambiguous: true, reason: 'transport timeout', retryAfter: null };
  }
  if (outcome instanceof TransportError) {
    return { retry: true, ambiguous: true, reason: 'transport error', retryAfter: null };
  }

  const { status } = outcome;
  if (status >= 200 && status < 300) {
    return { retry: false, ambiguous: false, reason: 'success', retryAfter: null };
  }

  const flag = errorRetryable(outcome.body);   // true, false, or null
  const ambiguous = AMBIGUOUS_STATUS.has(status) || !DEFINITIVE.has(status);
  const retryAfter = parseRetryAfter(outcome.headers);

  if (flag !== null) {
    return { retry: flag, ambiguous: ambiguous && flag,
             reason: `error.retryable=${flag}`, retryAfter };
  }
  if (WORTH_RETRY.has(status)) return { retry: true, ambiguous, reason: `${status}`, retryAfter };
  return { retry: false, ambiguous, reason: `${status}`, retryAfter };
}

export class RetryPolicy {
  constructor({ maxAttempts = 4, totalBudget = 30, baseDelay = 0.5, maxDelay = 8,
                sleep = (s) => new Promise((r) => setTimeout(r, s * 1000)),
                clock = () => Date.now() / 1000, rng = Math.random } = {}) {
    if (maxAttempts < 1) throw new RangeError('maxAttempts must be at least 1');
    if (totalBudget <= 0) throw new RangeError('totalBudget must be positive');
    Object.assign(this, { maxAttempts, totalBudget, baseDelay, maxDelay, sleep, clock, rng });
  }

  backoff(attempt) {
    const ceiling = Math.min(this.maxDelay, this.baseDelay * 2 ** Math.max(0, attempt - 1));
    return this.rng() * ceiling;
  }

  async run(transport, { idempotent }) {
    if (typeof idempotent !== 'boolean') {
      throw new TypeError('idempotent must be stated explicitly');
    }
    const deadline = this.clock() + this.totalBudget;
    const attempts = [];
    let slept = 0;

    for (let attempt = 1; attempt <= this.maxAttempts; attempt += 1) {
      let outcome;
      try {
        outcome = await transport();
      } catch (err) {
        if (!(err instanceof TransportTimeout) && !(err instanceof TransportError)) throw err;
        outcome = err;
      }

      const decision = classify(outcome);
      attempts.push(decision);

      if (!decision.retry) {
        if (outcome.status >= 200 && outcome.status < 300) {
          return { response: outcome, attempts: attempt, slept };
        }
        throw new NotRetryable(outcome, decision);
      }
      if (decision.ambiguous && !idempotent) {
        throw new DuplicateRisk(outcome, decision, attempts);
      }
      if (attempt === this.maxAttempts) break;

      const delay = decision.retryAfter !== null ? decision.retryAfter : this.backoff(attempt);
      if (this.clock() + delay >= deadline) break;
      await this.sleep(delay);
      slept += delay;
    }
    throw new RetryExhausted(attempts, attempts[attempts.length - 1]);
  }
}

The fetch transport needs the same two properties — a real timeout, and a body that always gets drained so the socket is released:

export function makeTransport(url, init = {}, timeoutMs = 15000) {
  return async () => {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), timeoutMs);
    try {
      const res = await fetch(url, { ...init, signal: controller.signal });
      const text = await res.text();       // drain even on an error status
      let body = null;
      try { body = text ? JSON.parse(text) : null; } catch { body = null; }
      return response(res.status, Object.fromEntries(res.headers), body);
    } catch (err) {
      if (err.name === 'AbortError') throw new TransportTimeout(`timed out after ${timeoutMs} ms`);
      throw new TransportError(err.message);
    } finally {
      clearTimeout(timer);
    }
  };
}

fetch has no built-in request timeout, so without the AbortController a hung connection waits forever and your budget never applies. And the text() call is not optional: skip it on an error path and the socket stays checked out of the pool, which is exactly the wrong thing to do during the retry storm that follows an outage.

The tests that keep the rules honest

The policy is small enough to read, and still has enough branches that a change to one rule quietly breaks another. The suite below injects the clock, the sleep function and the jitter source, so it runs offline in milliseconds and never touches the network or the billing system.

class FakeClock:
    def __init__(self):
        self.now, self.sleeps = 1000.0, []

    def __call__(self):
        return self.now

    def sleep(self, seconds):
        self.sleeps.append(seconds)
        self.now += seconds


class TestDuplicateSafety(unittest.TestCase):

    def test_timeout_on_non_idempotent_call_raises_duplicate_risk(self):
        p, _ = policy()
        t = transport_returning(TransportTimeout(), OK)
        with self.assertRaises(DuplicateRisk):
            p.run(t, idempotent=False)
        self.assertEqual(t.count(), 1, "must not re-send after a timeout")

    def test_429_on_non_idempotent_call_is_still_retried(self):
        # Throttling is a refusal before any work, so re-sending is safe.
        p, _ = policy()
        out = p.run(transport_returning(Response(429), OK), idempotent=False)
        self.assertEqual(out.attempts, 2)


class TestLimits(unittest.TestCase):

    def test_budget_stops_before_sleeping_past_the_deadline(self):
        p, clock = policy(max_attempts=10, total_budget=1.0,
                          base_delay=10.0, max_delay=10.0)
        with self.assertRaises(RetryExhausted):
            p.run(transport_returning(Response(503)), idempotent=True)
        self.assertEqual(clock.sleeps, [], "slept past the budget")

The Node suite mirrors it with node:test:

test('a timeout on a non-idempotent call raises DuplicateRisk', async () => {
  const { policy } = makePolicy();
  const t = transportReturning(new TransportTimeout(), OK);
  await assert.rejects(() => policy.run(t, { idempotent: false }), DuplicateRisk);
  assert.equal(t.count(), 1, 'must not re-send after a timeout');
});

test('422 is not assumed to be validation only', () => {
  assert.equal(classify(VALIDATION_422).retry, false);
  assert.equal(classify(EXTRACTION_422_RETRYABLE).retry, true);
});

Run them with python -m unittest -v test_retry.py and node --test test_retry.mjs. The assertions worth keeping, whatever your implementation looks like: a non-idempotent call is never re-sent after an ambiguous failure, the two 422 shapes reach different decisions, an absent retryable flag is not read as false, and the policy never sleeps past its budget.

Logging retries without leaking your API key

A retry logger is the single most likely place in a scraper for an API key to reach disk. It is the one piece of code whose whole job is to write out request details on a failure path, and failure paths get less review than happy paths.

Redact on the way in, not on the way out:

_SECRET_KEYS = ("x-api-key", "authorization", "api_key", "apikey",
                "token", "secret", "password", "cookie", "set-cookie")

def redact(data):
    if isinstance(data, Mapping):
        return {k: "[redacted]" if str(k).lower() in _SECRET_KEYS else redact(v)
                for k, v in data.items()}
    if isinstance(data, (list, tuple)):
        return [redact(v) for v in data]
    return data

Log the redacted copy and never the original object, because the original tends to get passed to an exception handler later and printed somewhere you did not plan.

What is worth logging on every attempt: the attempt number, the status code or exception type, the error.code when there is one, the decision and its reason, the delay before the next attempt, and a correlation id that ties the attempts together. What is not worth logging: full request bodies, full response bodies, and anything under a key that looks like a credential.

One more habit that pays off during an incident: log the decision, not just the outcome. "attempt 2, 503, retrying in 1.8s, reason=503 Service temporarily unavailable" tells you what the code was thinking. "attempt 2 failed" tells you nothing you could not already guess, and when the policy misbehaves it is the reasoning you need to see.

What actually gets charged

Retry logic and billing meet at exactly one question: does a failed attempt cost anything? For the Geonode Scraper API the pricing reference is explicit.

Charged: "1 request per successfully extracted page" for single extraction, "1 request when the page is successfully extracted" for async, and "1 request for each successfully extracted URL" for batch and crawl. JavaScript rendering, geo-targeting and output format selection do not add a charge.

Not charged: "Failed extractions are not charged. Authentication errors, validation errors, and requests rejected before extraction are not charged either." Job lookup, statistics, webhooks, health checks and Map operations do not extract content and carry no charge.

Two caveats, because this is where confident writing goes wrong.

A client-side timeout is not a statement about billing. It is a statement about your socket. The documented rule is that failed extractions are not charged — but a request that timed out on your end may have succeeded on the server, and a successful extraction is the kind that gets charged. The timeout tells you that you do not know. This is the same uncertainty that makes re-sending unsafe, viewed from the billing side, and it is the reason the two sections belong in the same article.

Field names lag the billing language. Responses still carry tokens_charged, estimated_tokens and tokens_reserved. The documentation is clear about how to read them: "Treat those as request counts for billing." A tokens_charged: 0 in an error response means zero requests charged, not zero of some other unit.

Dollar amounts, plan limits and request volumes change, so this guide does not quote them. Check the Scraper API pricing page for current numbers.

Common mistakes

Retrying a POST because the error looked temporary

The most expensive one, and it reads as reasonable in review. The error being temporary is the answer to the wrong question. Ask instead whether the server might have started work you cannot see — and on a timeout or a 5xx, the honest answer is that you do not know.

Treating a missing retryable flag as false

A validation error carries no retryable field, and neither does a bare 503. Code that reads the flag with a False default turns every transient outage into a permanent failure, and the bug only shows up during an incident, which is the worst time to find it.

An attempt cap with no time budget

max_attempts=5 sounds like a limit and bounds nothing you care about. Five attempts with growing backoff and a thirty-second transport timeout can hold a worker for minutes. Bound wall-clock time, and bound it to what the caller can wait, not to what the API can tolerate.

Stacking retries on a client that already retries

Four attempts of yours wrapped around three of the SDK's is twelve requests against the same concurrency limit, and the 429s that follow look like a server problem. If you wrap a client, find out what it already does and turn one of the two layers off.

A tight loop with no sleep at all

The error handling reference asks for exactly the opposite: "For retryable failures, use exponential backoff and avoid retrying in a tight loop." A loop with no delay converts a brief degradation into a sustained outage, and your own throttling into the reason you stay throttled.

FAQ

What is the best retry strategy for a scraper API?

Exponential backoff with full jitter, under both an attempt cap and a wall-clock budget, with retries limited to failures the API marks retryable or that your status map treats as transient. The part most implementations miss is the safety check: never re-send a request that creates work when the failure was ambiguous, because the job may already exist.

Which HTTP status codes should I retry?

Retry 408, 429, 500, 502, 503 and 504. Do not retry 400, 401, 402, 404 or 409 — those need a change to the request, the credentials or the balance. Treat 422 case by case: it covers both validation errors and failed extractions, and the retryable field in the error body tells you which you have.

Does the Geonode Scraper API support idempotency keys?

The documentation does not currently describe an idempotency key or request identifier. Until it does, prevent duplicate jobs on your side: record the intent with a unique constraint before submitting, store the job id as soon as it returns, and reconcile any intent left without one rather than re-submitting it inside a retry loop.

Do failed requests cost anything?

The pricing reference states that failed extractions are not charged, and that authentication errors, validation errors and requests rejected before extraction are not charged either. Lookups, statistics, webhooks, health checks and Map operations carry no charge. What a client-side timeout costs is unknown by definition — the extraction may have succeeded after your socket gave up, and a successful extraction is charged.

How many times should I retry a scraping request?

Three or four attempts covers the overwhelming majority of transient failures; beyond that you are usually waiting out a real outage, and a queue handles that better than a loop. Set the wall-clock budget from what the caller can wait — a few seconds for an interactive request, minutes for a batch job — and let it, rather than the attempt count, be the limit that actually bites.

Should I retry if the request timed out?

Only if the operation is idempotent. A job lookup, yes. A job submission, no: the server may have accepted it before the connection dropped, and re-sending creates a second job. Mark it unconfirmed and reconcile it against the webhook, the job list, or a deliberate one-time re-submission by a process that knows it is re-submitting.