Skip to content

Commit 4a4fd8f

Browse files
authored
fix(throttling-manager): Use the longest robots.txt crawl-delay (#2520)
### Description When one domain gets crawl-delays from several robots.txt files, `ThrottlingRequestManager` now keeps the longest one instead of the first. Several files cover one domain for a site and its subdomains under `throttle_by='registrable_domain'`, and for HTTP and HTTPS of one host. A robots.txt re-fetch still can't speed a domain up, it can only slow it down. The same change for Crawlee JS is tracked in apify/crawlee#4491, with a fix proposed in apify/crawlee#4493. ### Issues - Follow-up: #2507 *✍️ Drafted by Claude Code*
1 parent b390f63 commit 4a4fd8f

4 files changed

Lines changed: 26 additions & 12 deletions

File tree

‎docs/03_concepts/19_request_throttling.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ To use request throttling, create a <ApiLink to="class/ThrottlingRequestManager"
3838

3939
2. **429 backoff**: When the crawler detects an HTTP 429 response, the `ThrottlingRequestManager` records an exponential backoff delay for that domain (starting at 2s, doubling up to 60s). Requests already in flight when the limit was hit are treated as a single rate-limit event, so the delay doubles once per backoff window rather than once per 429. Once the domain goes a full extra window without rate-limiting, the next 429 starts the backoff over at the initial delay. If the response includes a `Retry-After` header with a positive delay, that value takes priority.
4040

41-
3. **Crawl-delay**: If `robots.txt` specifies a `crawl-delay`, the manager enforces a minimum interval between requests to that domain. To space out the requests to every listed domain, set `min_crawl_delay`. A longer `crawl-delay` from `robots.txt` still takes precedence.
41+
3. **Crawl-delay**: If `robots.txt` specifies a `crawl-delay`, the manager enforces a minimum interval between requests to that domain. When several `robots.txt` files cover one domain, such as HTTP and HTTPS of one host or the hosts of a site with `throttle_by='registrable_domain'`, the longest crawl-delay applies. To space out the requests to every listed domain, set `min_crawl_delay`. A longer `crawl-delay` from `robots.txt` still takes precedence.
4242

4343
4. **Fair scheduling**: `fetch_next_request` sorts available sub-managers by how long each domain has been waiting, ensuring no domain is starved.
4444

‎docs/06_upgrading/upgrading_to_v2.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -504,6 +504,8 @@ If you have a custom request manager, implement `record_pacing_signal`. Return `
504504

505505
`ThrottlingRequestManager` now rejects a `base_delay` or `max_delay` that isn't positive, so a zero `base_delay` no longer works as a way to honor only `Retry-After`.
506506

507+
A domain's crawl-delay now follows the longest `MinIntervalSignal` it gets. In v1, `set_crawl_delay` kept the first value and ignored later ones.
508+
507509
A `RequestThrottledError` you raise yourself now starts the domain's backoff, and the request is deferred if the request manager paces its domain. In v1, it was an ordinary error unless you had called `record_domain_delay` first. A deferred request never fails, so raise the error only when the server has refused the request. In `AdaptivePlaywrightCrawler`, such an error from the static run now defers the request instead of falling back to the browser.
508510

509511
## `ThrottlingRequestManager.inner` is optional

‎src/crawlee/request_loaders/_throttling_request_manager.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -462,8 +462,9 @@ def record_pacing_signal(self, signal: PacingSignal) -> bool:
462462
463463
A `RateLimitedSignal` backs the domain off for the signal's `wait` if it's positive, and exponentially from
464464
`base_delay` otherwise. Only the first refusal of a burst advances the backoff. A `MinIntervalSignal` becomes
465-
the domain's crawl-delay, unless `min_crawl_delay` is longer. The first one wins, so a robots.txt re-fetch can't
466-
change the dispatch cadence mid-crawl.
465+
the domain's crawl-delay, unless the domain already has a longer one or `min_crawl_delay` is longer. So the
466+
strictest robots.txt among the origins a domain covers sets the pace, and a robots.txt re-fetch can't speed up
467+
the dispatch cadence.
467468
468469
Returns:
469470
`True` if the URL's domain is in `domains`, so the manager paces it by the signal. `False` if the domain
@@ -571,12 +572,12 @@ def _record_rate_limit(self, url: str, wait: timedelta | None) -> bool:
571572
return True
572573

573574
def _record_declared_interval(self, url: str, interval: timedelta) -> bool:
574-
"""Record a declared minimum interval as the crawl-delay of the URL's domain, unless it already has one."""
575+
"""Record a declared minimum interval as the crawl-delay of the URL's domain, unless it has a longer one."""
575576
state = self._get_domain_state(url)
576577
if state is None:
577578
return False
578579

579-
if state.crawl_delay is None:
580+
if state.crawl_delay is None or interval > state.crawl_delay:
580581
state.crawl_delay = interval
581582
logger.debug('Set crawl-delay for domain "%s" to %.1fs', state.domain, interval.total_seconds())
582583

‎tests/unit/test_throttling_request_manager.py‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -528,19 +528,30 @@ async def test_crawl_delay_integration(manager: ThrottlingRequestManager[Request
528528
assert state.crawl_delay == timedelta(seconds=5)
529529

530530

531-
async def test_min_interval_keeps_first_value(manager: ThrottlingRequestManager[RequestQueue]) -> None:
532-
"""A later min-interval signal is accepted but doesn't change the crawl-delay."""
531+
@pytest.mark.parametrize(
532+
('later', 'expected'),
533+
[
534+
pytest.param(timedelta(seconds=9), timedelta(seconds=9), id='longer-raises'),
535+
pytest.param(timedelta(seconds=2), timedelta(seconds=5), id='shorter-ignored'),
536+
],
537+
)
538+
async def test_min_interval_keeps_longest_value(
539+
manager: ThrottlingRequestManager[RequestQueue],
540+
later: timedelta,
541+
expected: timedelta,
542+
) -> None:
543+
"""A later min-interval signal is accepted and can raise the crawl-delay, but never lowers it."""
533544
url = f'https://{THROTTLED_DOMAIN}/page1'
534545
manager.record_pacing_signal(MinIntervalSignal(url, interval=timedelta(seconds=5), scope='hostname'))
535546

536-
accepted = manager.record_pacing_signal(MinIntervalSignal(url, interval=timedelta(seconds=9), scope='hostname'))
547+
accepted = manager.record_pacing_signal(MinIntervalSignal(url, interval=later, scope='hostname'))
537548

538549
assert accepted is True
539-
assert manager._domain_states[THROTTLED_DOMAIN].crawl_delay == timedelta(seconds=5)
550+
assert manager._domain_states[THROTTLED_DOMAIN].crawl_delay == expected
540551

541552

542-
async def test_site_keeps_first_crawl_delay(site_manager: ThrottlingRequestManager[RequestQueue]) -> None:
543-
"""With `registrable_domain`, the first crawl-delay from any host of a site paces the whole site."""
553+
async def test_site_keeps_longest_crawl_delay(site_manager: ThrottlingRequestManager[RequestQueue]) -> None:
554+
"""With `registrable_domain`, the longest crawl-delay among the hosts of a site paces the whole site."""
544555
site_manager.record_pacing_signal(
545556
MinIntervalSignal('https://www.example.com/page1', interval=timedelta(seconds=5), scope='hostname')
546557
)
@@ -550,7 +561,7 @@ async def test_site_keeps_first_crawl_delay(site_manager: ThrottlingRequestManag
550561
)
551562

552563
assert accepted is True
553-
assert site_manager._domain_states['example.com'].crawl_delay == timedelta(seconds=5)
564+
assert site_manager._domain_states['example.com'].crawl_delay == timedelta(seconds=9)
554565

555566

556567
async def test_min_interval_refused_unconfigured(manager: ThrottlingRequestManager[RequestQueue]) -> None:

0 commit comments

Comments
 (0)