DEV Community

t.labo
t.labo

Posted on Originally published at tlaboratory.net

Pagination, 429 and Backoff in Python Scraping

Series: Web Scraping lecture 3/6 (intermediate). This one is for you if your scraper works on one page and now has to walk through fifty, without getting blocked and without hurting the site. By the end you will follow "next" links with clear stop conditions, handle 429 Too Many Requests the way the server asks, and know from measurements why adding threads did not help.

A typical case: someone on your team wants a price-monitoring sheet or an internal dashboard fed from a catalogue that spans many pages. The first script fetches page 1 perfectly, then the loop version either never stops, or stops on page 6 with HTTP Error 429, or "succeeds" with half the products missing. All three happened in this lecture, on a practice shop we run on our own machine, and the fixes are short.

Everything here ran with Python 3.9.6 (standard library only), PHP 8.5.6 (php -S) and curl 8.7.1 on an Apple Silicon Mac (M1 Pro), against 127.0.0.1 only. Paths are shortened to ~/demo/.

The rules before the code

Pagination and concurrency are exactly where a scraper turns from "a script" into "load on someone else's server". So the ground rules from lecture 1 apply with more force here:

  • Prefer an official API or data export when the site offers one. It is faster for you and cheaper for them.
  • Read robots.txt and the terms of service and respect them. If the terms forbid automated access, do not scrape; check the site's terms and your local law, and ask the owner when in doubt.
  • Identify your bot honestly. Our User-Agent is tlab-practice-bot/0.1 (+https://example.com/bot-contact): a name and a place to contact you. We do not pretend to be a browser.
  • Slow down when told to. A 429 or 503 is a request, not an obstacle. This lecture never tries to get around a limit; it only learns to live inside one.
  • Personal data (names, e-mails, reviews tied to people) needs a legal basis wherever you are. Product names and prices are what we collect here.

That is why every request below goes to a shop we wrote ourselves.

The practice shop: 5 requests per second

Save this as ~/demo/shop.php. It serves 23 products on 5 list pages, a detail page per product, a robots.txt with Crawl-delay: 1, and a rate limit: more than 5 requests in the same second get 429 with Retry-After: 1. Each page also sleeps 50 ms to act like a real backend.

<?php
// Practice shop, lecture 3 part. Loopback only:
//   PHP_CLI_SERVER_WORKERS=4 php -S 127.0.0.1:18166 shop.php
const PER_PAGE = 5;   // products per list page
const LIMIT    = 5;   // requests allowed per second (whole site)
const WORK_MS  = 50;  // pretend each page costs 50 ms to render

$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if ($path === '/robots.txt') {
    header('Content-Type: text/plain');
    echo "User-agent: *\nDisallow: /cart\nCrawl-delay: 1\n";
    return true;
}
function over_limit(string $file): bool {      // fixed 1-second window, shared by workers
    $fp = fopen($file, 'c+');
    flock($fp, LOCK_EX);
    [$sec, $n] = array_map('intval', explode(' ', trim(stream_get_contents($fp)) ?: '0 0'));
    $now = time();
    $n = ($sec === $now) ? $n + 1 : 1;
    ftruncate($fp, 0); rewind($fp); fwrite($fp, "$now $n");
    flock($fp, LOCK_UN); fclose($fp);
    return $n > LIMIT;
}
if (over_limit(__DIR__ . '/rate.txt')) {
    http_response_code(429);
    header('Retry-After: 1');
    echo "Too Many Requests: max " . LIMIT . " per second\n";
    return true;
}
$names = ['Desk lamp','USB-C cable','Notebook A5','Mechanical pencil','Mug','Tote bag','Sticky notes',
          'Phone stand','Desk mat','Cable clips','Water bottle','Bookends','Highlighter set','Laptop sleeve',
          'Coaster set','Ruler 30cm','Eraser','Paper clips','Monitor riser','Pen case','Calendar 2027',
          'Clipboard','Stapler'];
$products = [];
foreach ($names as $i => $n) {
    $products[$i + 1] = ['name' => $n, 'price' => 300 + (($i * 397) % 2700), 'stock' => ($i % 4) ? 'in' : 'out'];
}
usleep(WORK_MS * 1000);
header('Content-Type: text/html; charset=utf-8');
if ($path === '/products') {
    $pages = (int)ceil(count($products) / PER_PAGE);
    $p = max(1, (int)($_GET['page'] ?? 1));
    if ($p > $pages) { http_response_code(404); echo "<p>No such page</p>\n"; return true; }
    echo "<h1>Products (page $p of $pages)</h1>\n<ul class=\"products\">\n";
    foreach (array_slice($products, ($p - 1) * PER_PAGE, PER_PAGE, true) as $id => $x) {
        echo "<li><a href=\"/product/$id\">{$x['name']}</a> <span class=\"price\">{$x['price']}</span></li>\n";
    }
    echo "</ul>\n";
    if ($p < $pages) echo '<a rel="next" href="https://tlaboratory.net/products?page=' . ($p + 1) . "\">Next</a>\n";
    return true;
}
if (preg_match('#^/product/(\d+)$#', $path, $m) && isset($products[(int)$m[1]])) {
    $x = $products[(int)$m[1]];
    echo "<h1>{$x['name']}</h1><p class=\"price\">{$x['price']}</p><p class=\"stock\">{$x['stock']}</p>\n";
    return true;
}
http_response_code(404);
echo "<p>Not found</p>\n";
return true;
Enter fullscreen mode Exit fullscreen mode

PHP_CLI_SERVER_WORKERS=4 makes the built-in server run 4 worker processes (supported on macOS and Linux, not on Windows), so it can answer requests in parallel; the flock keeps the counter honest across them. Seven quick requests from curl show the limit:

$ cd ~/demo && PHP_CLI_SERVER_WORKERS=4 php -S 127.0.0.1:18166 shop.php &
$ for i in 1 2 3 4 5 6 7; do curl -s -o /dev/null -w "%{http_code} " http://127.0.0.1:18166/product/$i; done
200 200 200 200 200 429 429
$ curl -si http://127.0.0.1:18166/product/1 | head -7
HTTP/1.1 429 Too Many Requests
Host: 127.0.0.1:18166
Date: Sat, 14 Nov 2026 23:20:25 GMT
Connection: close
X-Powered-By: PHP/8.5.6
Retry-After: 1
Content-type: text/plain;charset=UTF-8
Enter fullscreen mode Exit fullscreen mode

A fixed window limiter like this one counts requests per calendar second. Real sites use many schemes (sliding windows, token buckets, per-IP or per-account quotas), and most do not tell you which. You can only observe the status codes and headers they send.

Following "next" links, and when to stop

There are two ways to walk a paginated list. The tempting one is a counter, ?page=1, ?page=2, … until something breaks (counter.py):

import time
import urllib.request
page = 1
while True:
    url = f"http://127.0.0.1:18166/products?page={page}"
    html = urllib.request.urlopen(url, timeout=10).read()
    print(page, len(html))
    page += 1
    time.sleep(0.25)
Enter fullscreen mode Exit fullscreen mode
$ python3 counter.py
1 573
2 573
3 587
4 576
5 373
Traceback (most recent call last):
  …
urllib.error.HTTPError: HTTP Error 404: Not Found
Enter fullscreen mode Exit fullscreen mode

It "works" here because this shop returns a clean 404 after the last page. Many real sites return 200 with an empty list, repeat the last page forever, or redirect page 999 to page 1. A counter then never stops, or stops for the wrong reason. The sturdier way is to follow the link the site gives you (<a rel="next">) and to write the stop conditions down explicitly. Here is the whole crawler, ~/demo/polite_crawl.py:

"""Follow rel="next" pages politely, retry 429 with Retry-After / backoff. Python 3.9+ stdlib only."""
import random
import sys
import time
import urllib.error
import urllib.request
import urllib.robotparser
from html.parser import HTMLParser
from urllib.parse import urljoin

BASE = "http://127.0.0.1:18166"
UA = "tlab-practice-bot/0.1 (+https://example.com/bot-contact)"
rng = random.Random(42)            # fixed seed: the same jitter on every run
stats = {"requests": 0, "429": 0, "slept": 0.0}


class ListPage(HTMLParser):
    """Collect product links and the rel="next" link."""
    def __init__(self):
        super().__init__()
        self.items, self.next = [], None

    def handle_starttag(self, tag, attrs):
        a = dict(attrs)
        if tag == "a" and a.get("rel") == "next":
            self.next = a.get("href")
        elif tag == "a" and a.get("href", "").startswith("/product/"):
            self.items.append(a["href"])


def nap(sec):
    stats["slept"] += sec
    time.sleep(sec)


def fetch(url, retries=5, base=0.25, cap=4.0, use_retry_after=True):
    """GET url. On 429/503 wait (Retry-After or backoff with full jitter) and retry."""
    for attempt in range(retries + 1):
        req = urllib.request.Request(url, headers={"User-Agent": UA})
        stats["requests"] += 1
        try:
            with urllib.request.urlopen(req, timeout=10) as r:
                return r.read().decode("utf-8")
        except urllib.error.HTTPError as e:
            if e.code not in (429, 503) or attempt == retries:
                raise
            stats["429"] += e.code == 429
            ra = e.headers.get("Retry-After")
            if use_retry_after and ra and ra.isdigit():
                wait = int(ra)                                    # the server told us
            else:
                wait = rng.uniform(0, min(cap, base * 2 ** attempt))  # full jitter
            nap(wait)


def crawl(start, delay=None, max_pages=50, **kw):
    robots = urllib.robotparser.RobotFileParser(urljoin(start, "/robots.txt"))
    robots.read()
    if delay is None:
        delay = robots.crawl_delay(UA) or 1.0
    url, seen, products = start, set(), []
    while url:
        if url in seen:                       # stop condition 1: loop
            print("loop detected at", url); break
        if len(seen) >= max_pages:            # stop condition 2: safety cap
            print("max_pages reached"); break
        if not robots.can_fetch(UA, url):     # stop condition 3: disallowed
            print("robots.txt disallows", url); break
        seen.add(url)
        page = ListPage()
        page.feed(fetch(url, **kw))
        if not page.items:                    # stop condition 4: empty page
            print("empty page", url); break
        products += [urljoin(url, h) for h in page.items]
        url = urljoin(url, page.next) if page.next else None   # stop condition 5: no next
        if url:
            nap(delay)
    return products


if __name__ == "__main__":
    d = float(sys.argv[1]) if len(sys.argv) > 1 else None
    t0 = time.perf_counter()
    found = crawl(BASE + "/products?page=1", delay=d)
    print(f"{len(found)} product URLs, {stats['requests']} requests, {stats['429']} x 429, "
          f"slept {stats['slept']:.2f} s, total {time.perf_counter() - t0:.2f} s")
    print(found[:3], "...")
Enter fullscreen mode Exit fullscreen mode
$ python3 polite_crawl.py
23 product URLs, 5 requests, 0 x 429, slept 4.00 s, total 4.32 s
['http://127.0.0.1:18166/product/1', 'http://127.0.0.1:18166/product/2', 'http://127.0.0.1:18166/product/3'] ...
Enter fullscreen mode Exit fullscreen mode

With no argument it reads Crawl-delay: 1 from robots.txt and waits one second between list pages, so 4 waits for 5 pages. urljoin turns the relative href into a full URL (see lecture 2 for why you never glue strings). The five stop conditions are the part to copy into every crawler you write: a loop guard, a hard page cap, robots.txt, "page had no items" and "no next link".

[[fig:scr-page-loop]]

429 Too Many Requests: what the server is telling you

Now the detail pages. The naive loop, naive.py, fetches all 23 as fast as it can:

import urllib.request
UA = "tlab-practice-bot/0.1 (+https://example.com/bot-contact)"
for i in range(1, 24):
    req = urllib.request.Request(f"http://127.0.0.1:18166/product/{i}", headers={"User-Agent": UA})
    html = urllib.request.urlopen(req, timeout=10).read()
    print(i, len(html))
Enter fullscreen mode Exit fullscreen mode
$ python3 naive.py
1 147
2 150
3 151
4 163
5 136
6 145
Traceback (most recent call last):
  File "~/demo/naive.py", line 5, in <module>
    html = urllib.request.urlopen(req, timeout=10).read()
  …
urllib.error.HTTPError: HTTP Error 429: Too Many Requests
Enter fullscreen mode Exit fullscreen mode

Six pages got through only because the burst straddled a second boundary. urlopen raises HTTPError for every 4xx and 5xx response, so the script dies. 429 Too Many Requests (RFC 6585) means "you, specifically, are going too fast". The response may carry a Retry-After header with a number of seconds, or an HTTP date, saying when to come back (RFC 9110 defines the header). 503 Service Unavailable with Retry-After means the same thing for the whole server, for example during maintenance.

fetch() above handles both: it catches HTTPError, re-raises anything that is not 429/503, and otherwise sleeps before the next attempt. Two details matter:

  1. Retry-After first. If the server gave a number, we wait exactly that long. Our code only parses the seconds form; a date form falls through to backoff, which is safe but not exact.
  2. Exponential backoff with jitter when there is no header. Each attempt doubles the ceiling (0.25 s, 0.5 s, 1 s, 2 s, 4 s, capped at 4 s) and we sleep a random time between 0 and that ceiling, the "full jitter" variant. Without jitter, every client that was rejected in the same second retries in the same second again. The RNG is random.Random(42), so the waits are reproducible. These are the first six draws:
ceilings: [0.25, 0.5, 1.0, 2.0, 4.0, 4.0]
waits:    [0.16, 0.013, 0.275, 0.446, 2.946, 2.707]
Enter fullscreen mode Exit fullscreen mode

A fixed seed matters for tests and for comparing runs; in production you would usually let it vary. Flaky timing in tests is its own topic: see flaky tests from time, randomness and concurrency.

Measured: no delay vs fixed delay vs backoff

bench_delay.py crawls the 5 list pages and fetches the 23 detail pages (28 GETs) under five settings, 3 runs each, with a 1.1 s pause before each run so it starts in a fresh window. Times are medians; the lists show the three runs.

no delay, no retry           median   0.37 s | 429s [22, 23, 19] | details ok [1, 0, 4] failed [22, 23, 19] | requests [28, 28, 28]
no delay, Retry-After        median   6.58 s | 429s [5, 5, 4] | details ok [23, 23, 23] failed [0, 0, 0] | requests [33, 33, 32]
no delay, backoff+jitter     median   5.73 s | 429s [15, 15, 15] | details ok [23, 23, 23] failed [0, 0, 0] | requests [43, 43, 43]
fixed 0.2 s, Retry-After     median   7.05 s | 429s [0, 0, 0] | details ok [23, 23, 23] failed [0, 0, 0] | requests [28, 28, 28]
fixed 1.0 s (Crawl-delay)    median  28.66 s | 429s [0, 0, 0] | details ok [23, 23, 23] failed [0, 0, 0] | requests [28, 28, 28]
Enter fullscreen mode Exit fullscreen mode

[[fig:scr-page-strategy-time]]

How to read it:

  • No delay, no retry is the fastest and the worst: it collected 0 to 4 of 23 products. If it had logged errors and moved on silently, your dashboard would show a "complete" run with most rows missing.
  • Retry-After and backoff both got everything. Backoff was 0.85 s faster here, because its random guesses were often shorter than the full second Retry-After asks for. But it sent 43 requests instead of 33, and 15 of them were rejected. On a real site, each rejection still cost the server a request.
  • A fixed 0.2 s delay (1 / 5 per second) produced zero 429s and exactly 28 requests. It cost half a second more than the retry storm. That is the polite steady state.
  • Crawl-delay: 1 is four times slower. On a site you do not own, it is the number you use. We only went faster here because we wrote the limit ourselves.

One trap we hit along the way: urllib.robotparser only accepts whole numbers for Crawl-delay. On both Python 3.9.6 and 3.12.14:

'1'   -> crawl_delay() = 1
'0.5' -> crawl_delay() = None
Enter fullscreen mode Exit fullscreen mode

A site that writes Crawl-delay: 0.5 gets None, and a crawler that treats None as "no delay" goes at full speed. That is why crawl() falls back to or 1.0 instead of zero. Crawl-delay is also not part of the robots.txt standard (RFC 9309), so some big crawlers ignore it; that is no reason for you to.

More workers, same speed: a thread pool against a rate limit

The next idea is always "use threads". Threads are fine for network-bound work in Python, since the GIL is released while waiting on sockets (more in threads, processes and asyncio). bench_pool.py fetches the 23 detail pages with ThreadPoolExecutor at several pool sizes; every 429 waits for Retry-After and tries again. The last rows add a small limiter shared by all threads:

class Limiter:
    """Shared by all threads: at most `rate` request starts per second."""
    def __init__(self, rate):
        self.gap, self.next, self.lock = 1.0 / rate, 0.0, threading.Lock()

    def wait(self):
        with self.lock:
            now = time.monotonic()
            t = max(now, self.next)
            self.next = t + self.gap
        time.sleep(max(0.0, t - now))
Enter fullscreen mode Exit fullscreen mode
 1 workers                 median  4.28 s | 429s [3, 3, 3] | requests [26, 26, 26]
 2 workers                 median  4.66 s | 429s [7, 6, 8] | requests [30, 29, 31]
 4 workers                 median  4.40 s | 429s [15, 15, 15] | requests [38, 38, 38]
 8 workers                 median  4.30 s | 429s [27, 19, 27] | requests [50, 42, 50]
16 workers                 median  4.32 s | 429s [40, 40, 40] | requests [63, 63, 63]
 1 workers + limiter 5/s   median  4.47 s | 429s [0, 0, 0] | requests [23, 23, 23]
 4 workers + limiter 5/s   median  4.47 s | 429s [0, 0, 0] | requests [23, 23, 23]
 8 workers + limiter 5/s   median  4.47 s | 429s [0, 0, 0] | requests [23, 23, 23]
Enter fullscreen mode Exit fullscreen mode

[[fig:scr-page-workers-429]]

Total time did not move: 23 pages at 5 per second is about 4.6 s, whatever you do. Sixteen threads simply sent 63 requests to get 23 pages. The limiter got the same speed with zero rejections. When a site rate-limits you, the limit decides your speed, and concurrency only decides how many requests get wasted. Concurrency helps only when the bottleneck is your own waiting (slow responses and no limit); even then, keep the pool small, 2 to 4, and keep a shared limiter in front of it.

Seen from the server: one client, 166 pages in a minute

Everything above was measured against a practice shop. Here is the same problem from the other side, on a real server we run: old PHP pages that show lottery statistics, where every page view opens a database connection and runs several queries. The hosting account allows at most 20 new database connections per second, shared by everything on it. On 16 November 2026 the host's limit log recorded:

[16-Nov-2026 02:24:37 UTC] MySQL connection limit reached: 28 new connections in one second
  (limit 20 per second), 8 refused in the last 5 seconds.
Enter fullscreen mode Exit fullscreen mode

Our own connection log for that minute (it stores a daily-rotated hash of the IP, not the IP) showed one client requesting 166 pages within one minute, peaking at 24 requests in a single second, and 857 connections over ten minutes. It sent an ordinary browser User-Agent, so robots.txt rules and our bot filters did not apply to it, and we cannot tell who it was. For comparison, the whole site normally makes 500-700 connections per hour, about 0.2 per second.

The 8 refused connections in that second were not necessarily the scraper's. Any real visitor or app user who arrived in that second got an error page instead of the results. That is the cost of a scraper without a delay: it is paid by other people.

With the fixed 1-second delay measured earlier in this lecture, the same 166 pages would have taken under three minutes and never exceeded 1 request per second, which nobody would have noticed. On our side we added a 60-second cache to the busiest JSON endpoints, so identical requests in a burst now cost one database connection, and moved the old pages off that server.

The opposite case happened in our own jobs. A results feed we fetch from another site timed out on every run for at least a week in November 2026. The job logs the timeout, does not retry in a loop, and publishes the last good data it cached. When the source comes back, the next run picks it up. A retry loop with no limit would have added load to a server that was already not answering.

Common mistakes → what actually happens → fix

Mistake What actually happened Fix
Page counter until an error Stopped on 404 here; on other sites it never stops or loops Follow rel="next", keep a seen set and max_pages
No try/except around urlopen HTTPError: HTTP Error 429 killed the run at item 6 Catch HTTPError, retry only 429/503, re-raise others
Catch everything and continue "Finished" with 0 to 4 of 23 products Count failures; fail the run when any are missing
Retry immediately, no wait More 429s, more load on the server Wait for Retry-After, else backoff with jitter
Treat crawl_delay() None as 0 Crawl-delay: 0.5 parsed as None, full speed Default to a safe delay (1 s)
More threads for speed 16 threads: same 4.3 s, 40 rejected requests Shared limiter; pool of 2 to 4 at most

Decision table: which waiting strategy?

Situation Use Why
robots.txt has Crawl-delay That delay, at least The site's own stated wish
Documented API quota (e.g. 60/min) A shared limiter just under it Zero 429s, predictable time
429 or 503 with Retry-After Wait exactly Retry-After The server knows its window
429 without Retry-After Exponential backoff with jitter, cap and max retries Spreads retries out; gives up eventually
Repeated 429s even when slow Stop and look at the terms or the API You are probably not welcome at this volume
Your own site, no limit Small pool (2 to 4) Overlaps waiting without flooding

Honest limits and version notes

  • All numbers come from one machine (Apple M1 Pro), loopback only, PHP 8.5.6's built-in server with 4 workers and a 50 ms artificial delay. Over the internet, latency adds to every request; the shape (limit = ceiling) stays the same.
  • Timing near a window edge is noisy. A second pool run against the exact file shown above gave the same picture with some spread: 4.3 to 5.4 s for every pool size, 3 to 4 rejections with one worker, 27 to 40 with sixteen, and 4.46 s with zero rejections behind the limiter.
  • The shop's fixed-window limiter is one of many designs. Sliding windows and token buckets behave differently near the window edge, so your own numbers on a real site will differ.
  • Checked on Python 3.9.6 and, for robotparser, also 3.12.14. RobotFileParser.crawl_delay() exists since Python 3.6. ThreadPoolExecutor since 3.2. Nothing here needs a third-party package.
  • requests with urllib3.util.Retry can do backoff and Retry-After for you (respect_retry_after_header), and Scrapy has an AutoThrottle extension. We describe them but did not run them here; the stdlib version shows what they do inside.
  • Japan, Korea, the EU and the US treat scraping, databases and personal data differently. This lecture is not legal advice: check the site's terms and your local law.

Exercises

  1. fetch() only understands Retry-After: 1. Extend it to also accept the HTTP-date form (Retry-After: Sat, 14 Nov 2026 23:20:26 GMT).
  2. Change the shop's LIMIT to 3 and predict how long the "4 workers + limiter 3/s" run takes for 23 pages before you run it.

Answers

  1. Use email.utils.parsedate_to_datetime(ra) from the standard library, compare it with datetime.now(timezone.utc), and clamp the result: wait = max(0, min(60, (when - now).total_seconds())). Keep the backoff path for headers you cannot parse, and cap the wait so a bad header cannot stall you for an hour.
  2. The limiter spaces request starts 1/3 s apart and the first one starts immediately, so 22 gaps × 0.333 s ≈ 7.33 s, plus about 50 ms for the last page to render. We ran it: 7.40 s in all 3 runs, 0 rejections, 23 requests. (The same arithmetic explains the 4.47 s of the 5/s limiter above: 22 × 0.2 + 0.05.) If you see 429s, the limiter's rate is higher than the server's, or another client shares the same limit.

What's next


Originally published at tlaboratory.net. Every output in this post was copied from a real terminal run.

Top comments (0)