Concurrency &amp; throttling | rust-crawler | Spatie       

 SPATIE  

rust-crawler
============

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Rust-crawler](https://spatie.be/docs/rust-crawler/v1)  Configuring-the-crawler  Concurrency &amp; throttling

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/rust-crawler/v1) 

  Concurrency &amp; throttling    
- [ Introduction ](https://spatie.be/docs/rust-crawler/v1/introduction)
- [ Installation &amp; setup ](https://spatie.be/docs/rust-crawler/v1/installation-setup)
- [ Support us ](https://spatie.be/docs/rust-crawler/v1/support-us)
- [ Questions and issues ](https://spatie.be/docs/rust-crawler/v1/questions-issues)
- [ Changelog ](https://spatie.be/docs/rust-crawler/v1/changelog)
- [ About us ](https://spatie.be/docs/rust-crawler/v1/about-us)

Basic usage
-----------

- [ Your first crawl ](https://spatie.be/docs/rust-crawler/v1/basic-usage/starting-your-first-crawl)
- [ Crawl responses ](https://spatie.be/docs/rust-crawler/v1/basic-usage/handling-crawl-responses)
- [ Using observers ](https://spatie.be/docs/rust-crawler/v1/basic-usage/using-observers)
- [ Collecting URLs ](https://spatie.be/docs/rust-crawler/v1/basic-usage/collecting-urls)
- [ Filtering URLs ](https://spatie.be/docs/rust-crawler/v1/basic-usage/filtering-urls)
- [ Testing ](https://spatie.be/docs/rust-crawler/v1/basic-usage/testing)
- [ Tracking progress ](https://spatie.be/docs/rust-crawler/v1/basic-usage/tracking-progress)

Configuring the crawler
-----------------------

- [ Concurrency &amp; throttling ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/crawl-behavior)
- [ Limits ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/setting-crawl-limits)
- [ Extracting resources ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/extracting-resources)
- [ Configuring requests ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/configuring-requests)
- [ Response filtering ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/handling-responses)
- [ Respecting robots.txt ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/respecting-robots-txt)

Advanced usage
--------------

- [ JavaScript rendering ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/rendering-javascript)
- [ Custom link extraction ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/extracting-custom-links)
- [ Custom request handlers ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/custom-request-handlers)
- [ Crawling across requests ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/crawling-across-requests)
- [ Custom crawl queue ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/using-a-custom-crawl-queue)
- [ Graceful shutdown ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/graceful-shutdown)

 Concurrency &amp; throttling
============================

###  On this page 

1. [ Concurrency ](#content-concurrency)
2. [ Request delay ](#content-request-delay)
3. [ Adaptive throttle ](#content-adaptive-throttle)
4. [ Custom throttle ](#content-custom-throttle)
5. [ Default scheme and host scope ](#content-default-scheme-and-host-scope)

Concurrency
-----------------------------------------------------------------------------------------

The default concurrency is 10. This bounds page-processing jobs, including pacing waits, retries, rendering and extraction. Set it to 1 to process URLs sequentially. Results otherwise arrive in completion order, not discovery order.

```
use spatie_crawler::Crawler;

fn sequential_crawler() -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .concurrency(1)
        .build()
}
```

Concurrency must be positive. `event_buffer(8)` is the default bounded event-channel capacity. Slow event consumers apply backpressure to scheduling. Synchronous `on_event` observers run before events enter that channel, so keep them short and nonblocking.

These bounds are not a global memory ceiling. Concurrent response bodies, parsed documents, browser state and queued events all consume memory. The default `MemoryStore` also retains discovered URL identities. Use `SqliteStore` for an on-disk frontier, and set [response and crawl limits](setting-crawl-limits) for your workload.

Request delay
-----------------------------------------------------------------------------------------------

`delay` takes a `Duration`, not milliseconds as an integer. It sets minimum spacing between page request starts per origin. An origin includes the scheme, hostname and port. Different origins have independent pacing. The default delay is zero, and the first request does not wait for this fixed delay.

```
use std::time::Duration;
use spatie_crawler::Crawler;

fn paced_crawler() -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .delay(Duration::from_millis(150))
        .build()
}
```

With robots enabled, `Crawl-delay` can increase the fixed interval. A shorter explicit delay cannot override it. Pacing also runs before each retry. Robots requests themselves are separate, and robots rules and pacing do not run for intermediate HTTP redirect hops. Redirects still pass the transport's URL, network and crawl-policy checks.

Adaptive throttle
-----------------------------------------------------------------------------------------------------------

Attach `AdaptiveThrottle` for latency-aware pacing. It runs in addition to the built-in fixed delay and robots `Crawl-delay`; it does not replace them.

```
use std::time::Duration;
use spatie_crawler::{AdaptiveThrottle, Crawler};

fn adaptive_crawler() -> spatie_crawler::Result {
    let throttle = AdaptiveThrottle::new(
        Duration::from_millis(50),
        Duration::from_secs(5),
    )?
    .with_origin_capacity(512)?;

    Crawler::builder("https://example.com")?
        .delay(Duration::from_millis(100))
        .throttle(throttle)
        .build()
}
```

`AdaptiveThrottle::default()` uses bounds of 50 ms and 5 seconds. Normal observations update the delay to `(current delay + fetch latency) / 2`, clamped to those bounds. HTTP 429 and 5xx responses double the delay instead, with a minimum of 1 ms before clamping. Observations include failed fetches and retries, but not rendering or extraction time.

The throttle serializes starts in each origin's lane and includes an initial delay. Updated observations affect the next wait, not a wait already in progress. It tracks at most 1024 dedicated origins by default. Extra origins share an overflow lane rather than evicting active origin state. `with_origin_capacity` must be positive. Minimum delay must not exceed maximum delay, and the maximum must fit the timer range.

The scheduler separately caps scheduled origins at `max_origins(1024)`. Exceeding that cap fails the crawl; it does not use the throttle's overflow behavior.

Custom throttle
-----------------------------------------------------------------------------------------------------

Implement `Throttle` to add asynchronous pacing. Add `async-trait = "0.1"` and `url = "2"` to your application's dependencies for this example. Do not use blocking thread sleeps in `wait`.

```
use std::time::Duration;
use async_trait::async_trait;
use spatie_crawler::{Crawler, Throttle};
use url::Url;

struct ExtraPause(Duration);

#[async_trait]
impl Throttle for ExtraPause {
    async fn wait(&self, _url: &Url) {
        tokio::time::sleep(self.0).await;
    }

    fn observe(&self, _url: &Url, _status: Option, _elapsed: Duration) {}
}

fn custom_pacing() -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .throttle(ExtraPause(Duration::from_millis(150)))
        .build()
}
```

This simple implementation pauses each job independently. Unlike `AdaptiveThrottle`, it does not coordinate start times across concurrent jobs.

Default scheme and host scope
-----------------------------------------------------------------------------------------------------------------------------------------------

A seed without a scheme defaults to HTTPS. Choose HTTP with `builder_with_scheme`, before configuring the crawler.

```
use spatie_crawler::Crawler;

fn http_crawler() -> spatie_crawler::Result {
    Crawler::builder_with_scheme("example.com", "http")?.build()
}
```

The default scope is the seed's exact hostname, not its origin. Other schemes and ports on that hostname can be in scope. Subdomains and the `www` variant are not included automatically. `include_subdomains(true)`, `match_www(true)`, and `allow_external_links(true)` widen scope without disabling network safeguards. See [configuring requests](configuring-requests) before sending credentials across a wider scope.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
