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. [ Throttling ](#content-throttling)
4. [ Default scheme ](#content-default-scheme)
5. [ Host scope ](#content-host-scope)

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

To improve the speed of the crawl, the package concurrently processes 10 URLs by default. You can change this number using the `concurrency` method.

```
use spatie_crawler::Crawler;

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

Concurrency must be positive. Set it to 1 to crawl URLs one by one. It bounds page-processing jobs, including pacing waits, retries, rendering and extraction. Results otherwise arrive in completion order, not discovery order.

`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
-----------------------------------------------------------------------------------------------

By default, there is no delay between requests. In some cases you might get rate limited when crawling too aggressively. You can add a pause between request starts using the `delay` method. It accepts a `Duration` and applies per origin, not across the whole crawl.

```
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()
}
```

An origin includes the scheme, hostname and port. Different origins have independent pacing. The first request does not wait for this fixed delay.

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. See [network safety](configuring-requests#network-safety) for redirect-hop checks.

Throttling
--------------------------------------------------------------------------------------

For more control over request pacing, you can use a throttle. A throttle implements `Throttle` and runs in addition to `delay` and robots `Crawl-delay`; it does not replace them.

### Adaptive throttle

The `AdaptiveThrottle` adjusts the delay based on how fast the server responds. When the server is slow, the crawler backs off. When it speeds up, the delay decreases. You can configure minimum and maximum bounds.

```
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.

Starts are coordinated per origin, including an initial delay. New observations affect the next wait. By default, 1024 origins have dedicated pacing state; extra origins share a lane. `with_origin_capacity` changes this positive capacity. Invalid delay bounds are rejected.

The crawler separately limits scheduled origins with `max_origins(1024)`. Exceeding it fails the crawl.

### Custom throttle

You can create your own throttle by implementing `Throttle`. 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
--------------------------------------------------------------------------------------------------

By default, URLs without a scheme are prefixed with `https`. You can change this using `builder_with_scheme`.

```
use spatie_crawler::Crawler;

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

Host scope
--------------------------------------------------------------------------------------

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 [network safety](configuring-requests#network-safety) 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)
