Retry Strategies That Don’t Make Things Worse

Cover for “Retry Strategies That Don’t Make Things Worse”: bar chart of retries multiplying from 3 to 243 across five layers, plus backoff with jitter

6 min read

From the client’s side, a retry looks free: one more request, a second chance. From the server’s side it is extra load arriving at exactly the moment the server is struggling. A good retry policy decides which failures deserve another attempt, how long to wait, and when to stop asking.

Key takeaways

  • Retry only transient failures: timeouts, connection resets and 5xx errors that suggest a temporary problem.
  • Never retry a refusal automatically. A 401 or 403 is a reason to stop and review, not to try again.
  • When the server sends Retry-After with a 429 or 503, treat it as the minimum wait.
  • Back off exponentially, add jitter, and cap both attempts and total elapsed time.
  • Retry in one place. Retries at several layers multiply: five layers of three attempts can mean 243 requests.

Why retries make things worse

Marc Brooker’s article on timeouts, retries and backoff in Amazon’s Builders’ Library (December 2019) calls retries “selfish”: a client that retries claims more of the server’s time to improve its own chances. That is harmless when failures are rare and independent. It is harmful when failures are caused by overload, because every retry adds to the load that caused the failure.

The damage compounds when several layers retry. A collector often has a job scheduler, a fetch library and an HTTP client, and each may have its own retry setting. If each makes up to three attempts, the worst case is multiplicative, not additive.

Retries multiply as they stack

Worst-case requests reaching the bottom of the stack for one user request, when each layer makes up to three attempts

0×50×100×150×200×250×1 layer3×2 layers9×3 layers27×4 layers81×5 layers243×
Calculation: attempts per layer raised to the number of layers (3n). The five-layer case is the example in Amazon’s Builders’ Library. Graphic: JsonEngine.
Data behind the chart
Layers that retryWorst-case requests
1 layer3
2 layers9
3 layers27
4 layers81
5 layers243

Most scraping stacks have at least two retrying layers without anyone deciding so. Scrapy’s retry middleware is on by default, for example, and an orchestrator that re-runs failed jobs adds another layer on top. Pick one layer to own retries and switch the others off.

Step one: classify the outcome

A retry policy starts with classification, not with a delay formula. HTTP status codes carry meaning defined in RFC 9110 (June 2022) and, for 429, RFC 6585. Network exceptions such as timeouts and connection resets come without a status at all.

Classify the outcome before deciding to retry

Five outcome classes and the action each one gets in our collectors

Responseor exceptionValid 2xx/304store, then validate contentTimeout, reset, 500/502/504back off with jitter, capped429 or 503wait for Retry-After, slow the domain401, 403, other refusalsstop the domain queue, review404 or 410record as removed, no retry
Status meanings from RFC 9110 and RFC 6585; the actions are JsonEngine’s operating policy, not a standard. Graphic: JsonEngine.
OutcomeWhat it usually meansRetry?Wait
Connect or read timeoutNetwork or server slow; nothing returnedYes, boundedExponential backoff with jitter
500, 502, 504Server or upstream error, often temporaryYes, boundedExponential backoff with jitter
503Temporarily unable to handle the requestYes, boundedRetry-After if present, otherwise backoff
429Too many requests from this clientYes, after waitingRetry-After if present; also lower the domain’s rate
401, 403Authentication needed, or the server refusesNoPause the domain and review
404, 410Not found; 410 means gone, likely permanentlyNoRecord as removed
200 with an error pageTransport worked, content did notNot as a retryTreat as a parse failure and investigate

Status meanings from RFC 9110 and RFC 6585. The retry column is our policy. Some 403 responses are temporary, but treating them as retryable by default is how a collector ends up hammering a site that has asked it to stop.

Step two: honor Retry-After

Retry-After is the server telling you how long to wait. RFC 9110 defines two forms: a number of seconds (Retry-After: 120) or an HTTP date (Retry-After: Fri, 30 Oct 2026 18:00:00 GMT). RFC 6585 allows it on 429 responses, and RFC 9110 describes its use with 503.

Treat the value as a floor. If your own backoff says 4 seconds and the header says 120, wait 120. If the header is malformed or the date is in the past, fall back to your normal backoff rather than retrying immediately. And when a 429 arrives, slow the whole domain down, not just the one URL: the server is talking about your request rate, not about a single page.

Step three: back off exponentially, with jitter

Exponential backoff doubles the wait after each failure: 1 second, then 2, 4, 8, up to a cap. It gives a struggling server progressively more room. On its own it has a flaw: clients that failed together retry together, in synchronized waves.

Jitter fixes that by randomizing each wait. With “full jitter”, the wait is a random value between zero and the exponential delay. The Builders’ Library article recommends jitter for exactly this reason: it spreads retries over time instead of piling them onto the same instants.

Jitter spreads retries out instead of synchronizing them

Simulated retry instants for 24 clients that failed at the same moment: base delay 1 s, doubling, four attempts

0s2s4s6s8s10s12s14s16sNo jitterFull jitterSeconds after the shared failure
Seeded simulation (random.seed(7)), illustrative only. Full jitter = a random wait between zero and the exponential delay, as described by Amazon’s Builders’ Library. Graphic: JsonEngine.

Jitter is about spreading load. It is not a way to disguise a collector or to look like many different visitors, and it should never be used that way.

Step four: put limits on everything

Every retry loop needs three caps:

  • Attempts per request. Three to five total attempts is typical. Scrapy’s default is two retries after the first request, three requests in all.
  • Elapsed time per request. A cap on the total time spent, including waits, so a request does not keep a worker busy for an hour.
  • A retry budget per domain. If more than a small share of a domain’s recent requests are retries, stop retrying and slow down. The Builders’ Library describes a token bucket for this: retries spend tokens, and when the bucket is empty, retries stop.

Add a fourth rule at the domain level: if refusals or 429s keep coming, pause the whole domain queue and have a person look. Repeated refusal is information, and the right response to it is a decision, not a loop.

A compact implementation

The function below fetches one URL with a timeout, retries only transient failures, honors Retry-After, applies full jitter and gives up on refusals. The Requests documentation notes that without a timeout, code “may hang for minutes or more”, so the timeout is not optional.

Python
import random, time
from email.utils import parsedate_to_datetime
from datetime import datetime, timezone
import requests

RETRY_STATUS = {500, 502, 503, 504, 429}
STOP_STATUS = {401, 403}

class StopDomain(Exception):
    """Refusal: pause this domain and review."""

def retry_after_seconds(resp):
    value = resp.headers.get("Retry-After")
    if not value:
        return None
    if value.strip().isdigit():
        return int(value)
    try:
        when = parsedate_to_datetime(value)
        return max(0, (when - datetime.now(timezone.utc)).total_seconds())
    except (TypeError, ValueError):
        return None  # malformed: fall back to backoff

def fetch(session, url, attempts=4, base=1.0, cap=60.0, max_elapsed=300):
    start = time.monotonic()
    for attempt in range(attempts):
        try:
            resp = session.get(url, timeout=(5, 30))
        except (requests.ConnectionError, requests.Timeout):
            resp = None
        if resp is not None:
            if resp.status_code in STOP_STATUS:
                raise StopDomain(f"{resp.status_code} on {url}")
            if resp.status_code not in RETRY_STATUS:
                return resp  # 2xx, 3xx, 404, 410: no retry
        if attempt == attempts - 1:
            break
        wait = random.uniform(0, min(cap, base * 2 ** attempt))  # full jitter
        floor = retry_after_seconds(resp) if resp is not None else None
        if floor is not None:
            wait = max(wait, floor)
        if time.monotonic() - start + wait > max_elapsed:
            break
        time.sleep(wait)
    return resp

In production the domain-level pieces sit around this function: a rate limiter per host, a retry budget, and a handler for StopDomain that pauses the queue and alerts someone.

What retries are not for

Retries handle temporary faults within access you already have. They are not a way to get past a refusal. If a site answers with 401 or 403, or keeps rate-limiting a polite request rate, the next step is to look for an official API or feed, contact the site, or drop the source. See web scraping vs official APIs for how we make that call.

What to log

A retry you cannot see is a retry you cannot tune. For every request, store the URL, the attempt number, the outcome class, the status code, the wait applied and whether the wait came from Retry-After. Over a week this answers the useful questions: which domains need a slower base rate, whether a cap is too tight, and how much of your traffic is retries. If retries are more than a few percent of requests to a domain, the base rate is probably too high.

Quick answers

How many times should a scraper retry a failed request?

For transient failures, three to five total attempts with exponential backoff is a common range. Also cap total elapsed time and keep a per-domain retry budget, so retries stop when a whole site is struggling.

Should I retry a 403 error?

Not automatically. A 403 means the server understood the request and refuses it. Pause requests to that domain and review whether the data is available through an API, a feed or permission.

What is jitter in exponential backoff?

Jitter randomizes each wait. With full jitter the delay is a random value between zero and the exponential backoff delay, which stops clients that failed together from retrying in synchronized waves.

Is Retry-After in seconds or a date?

Either. RFC 9110 allows a number of seconds or an HTTP date. Parse both, treat the result as a minimum wait, and fall back to normal backoff if the value is malformed.

Does Scrapy retry by default?

Yes. The retry middleware is enabled by default and retries a set of 5xx codes, 408 and 429, with two retries after the initial request. Make sure no other layer in your stack also retries.

Need product data without running the retry logic yourself?

We operate e-commerce collectors with per-domain rate limits, retry budgets and stop rules, and deliver validated data on a schedule. See price monitoring or tell us what you need.