-
Notifications
You must be signed in to change notification settings - Fork 636
fix: add per-domain RequestThrottler for 429 backoff #1762
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
MrAliHasan
wants to merge
8
commits into
apify:master
Choose a base branch
from
MrAliHasan:fix/request-throttler-429-backoff
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
64f7247
fix: add per-domain RequestThrottler for 429 backoff (#1437)
MrAliHasan 62ab3b8
refactor: replace RequestThrottler with ThrottlingRequestManager
MrAliHasan 1065e9b
refactor: reimplement `ThrottlingRequestManager` with per-domain sub-…
MrAliHasan 138fd67
test: fix typing and linting checks in ThrottlingRequestManager tests
MrAliHasan abdf51c
feat: Add explicit domain routing and management to the request throt…
MrAliHasan dd99d9d
feat: Implement recreate_purged for ThrottlingRequestManager and refa…
MrAliHasan 497b782
deps: Pin ty to version 0.0.18 and update uv.lock to include Python 3…
MrAliHasan 902f885
fix: Ensure ThrottlingRequestManager.add_request explicitly handles N…
MrAliHasan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
41 changes: 41 additions & 0 deletions
41
docs/guides/code_examples/request_throttling/throttling_example.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import asyncio | ||
|
|
||
| from crawlee.crawlers import BasicCrawler, BasicCrawlingContext | ||
| from crawlee.request_loaders import ThrottlingRequestManager | ||
| from crawlee.storages import RequestQueue | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| # Open the default request queue. | ||
| queue = await RequestQueue.open() | ||
|
|
||
| # Wrap it with ThrottlingRequestManager for specific domains. | ||
| # The throttler uses the same storage backend as the underlying queue. | ||
| throttler = ThrottlingRequestManager( | ||
| queue, | ||
| domains=['api.example.com', 'slow-site.org'], | ||
| ) | ||
|
|
||
| # Pass the throttler as the crawler's request manager. | ||
| crawler = BasicCrawler(request_manager=throttler) | ||
|
|
||
| @crawler.router.default_handler | ||
| async def handler(context: BasicCrawlingContext) -> None: | ||
| context.log.info(f'Processing {context.request.url}') | ||
|
|
||
| # Add requests. Listed domains are routed directly to their | ||
| # throttled sub-queues. Others go to the main queue. | ||
| await throttler.add_requests( | ||
| [ | ||
| 'https://api.example.com/data', | ||
| 'https://api.example.com/users', | ||
| 'https://slow-site.org/page1', | ||
| 'https://fast-site.com/page1', # Not throttled | ||
| ] | ||
| ) | ||
|
|
||
| await crawler.run() | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| asyncio.run(main()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| --- | ||
| id: request-throttling | ||
| title: Request throttling | ||
| description: How to throttle requests per domain using the ThrottlingRequestManager. | ||
| --- | ||
|
|
||
| import ApiLink from '@site/src/components/ApiLink'; | ||
| import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock'; | ||
|
|
||
| import ThrottlingExample from '!!raw-loader!roa-loader!./code_examples/request_throttling/throttling_example.py'; | ||
|
|
||
| When crawling websites that enforce rate limits (HTTP 429) or specify `crawl-delay` in their `robots.txt`, you need a way to throttle requests per domain without blocking unrelated domains. The <ApiLink to="class/ThrottlingRequestManager">`ThrottlingRequestManager`</ApiLink> provides exactly this. | ||
|
|
||
| ## Overview | ||
|
|
||
| The <ApiLink to="class/ThrottlingRequestManager">`ThrottlingRequestManager`</ApiLink> wraps a <ApiLink to="class/RequestQueue">`RequestQueue`</ApiLink> and manages per-domain throttling. You specify which domains to throttle at initialization, and the manager automatically: | ||
|
|
||
| - **Routes requests** for listed domains into dedicated sub-queues at insertion time. | ||
| - **Enforces delays** from HTTP 429 responses (exponential backoff) and `robots.txt` crawl-delay directives. | ||
| - **Schedules fairly** by fetching from the domain that has been waiting the longest. | ||
| - **Sleeps intelligently** when all configured domains are throttled, instead of busy-waiting. | ||
|
|
||
| Requests for domains **not** in the configured list pass through to the main queue without any throttling. | ||
|
|
||
| ## Basic usage | ||
|
|
||
| To use request throttling, create a <ApiLink to="class/ThrottlingRequestManager">`ThrottlingRequestManager`</ApiLink> with the domains you want to throttle and pass it as the `request_manager` to your crawler: | ||
|
|
||
| <RunnableCodeBlock className="language-python" language="python"> | ||
| {ThrottlingExample} | ||
| </RunnableCodeBlock> | ||
|
|
||
| ## How it works | ||
|
|
||
| 1. **Insertion-time routing**: When you add requests via `add_request` or `add_requests`, each request is checked against the configured domain list. Matching requests go directly into a per-domain sub-queue; all others go to the main queue. This eliminates request duplication entirely. | ||
|
|
||
| 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). If the response includes a `Retry-After` header, that value takes priority. | ||
|
|
||
| 3. **Crawl-delay**: If `robots.txt` specifies a `crawl-delay`, the manager enforces a minimum interval between requests to that domain. | ||
|
|
||
| 4. **Fair scheduling**: `fetch_next_request` sorts available sub-queues by how long each domain has been waiting, ensuring no domain is starved. | ||
|
|
||
| :::tip | ||
|
|
||
| The `ThrottlingRequestManager` is an opt-in feature. If you don't pass it to your crawler, requests are processed normally without any per-domain throttling. | ||
|
|
||
| ::: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| """HTTP utility functions for Crawlee.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from datetime import datetime, timedelta, timezone | ||
| from email.utils import parsedate_to_datetime | ||
|
|
||
|
|
||
| def parse_retry_after_header(value: str | None) -> timedelta | None: | ||
| """Parse the Retry-After HTTP header value. | ||
|
|
||
| The header can contain either a number of seconds or an HTTP-date. | ||
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After | ||
|
|
||
| Args: | ||
| value: The raw Retry-After header value. | ||
|
|
||
| Returns: | ||
| A timedelta representing the delay, or None if the header is missing or unparsable. | ||
| """ | ||
| if not value: | ||
| return None | ||
|
|
||
| # Try parsing as integer seconds first. | ||
| try: | ||
| seconds = int(value) | ||
| return timedelta(seconds=seconds) | ||
| except ValueError: | ||
| pass | ||
|
|
||
| # Try parsing as HTTP-date (e.g., "Wed, 21 Oct 2015 07:28:00 GMT"). | ||
|
|
||
| try: | ||
| retry_date = parsedate_to_datetime(value) | ||
| delay = retry_date - datetime.now(retry_date.tzinfo or timezone.utc) | ||
| if delay.total_seconds() > 0: | ||
| return delay | ||
| except (ValueError, TypeError): | ||
| pass | ||
|
|
||
| return None |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.