Crawling across requests | rust-crawler | Spatie       

 SPATIE  

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

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Rust-crawler](https://spatie.be/docs/rust-crawler/v1)  Advanced-usage  Crawling across requests

 Version   v1      

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

  Crawling across requests    
- [ 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)

 Crawling across requests
========================

###  On this page 

1. [ Initial request ](#content-initial-request)
2. [ Subsequent requests ](#content-subsequent-requests)
3. [ Budgets and progress ](#content-budgets-and-progress)
4. [ Checkpoint leases ](#content-checkpoint-leases)
5. [ Output is not a checkpoint ](#content-output-is-not-a-checkpoint)

Use a `SqliteStore` checkpoint to split a crawl into executions. This works for CLI batches, background workers, or an application that starts a batch from an HTTP request. The crate does not provide an HTTP server.

Unlike PHP queue serialization, the SQLite store updates the frontier as work completes. There is no separate serialization step after each batch.

Initial request
-----------------------------------------------------------------------------------------------------

Choose a checkpoint path and seed that identify one crawl. `max_pages` limits the current execution; `max_pages_total` and `time_limit_total` constrain the same crawl across executions.

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

#[tokio::main]
async fn main() -> Result {
    let mut crawl = Crawler::builder("https://example.com")?
        .max_pages(10)
        .max_pages_total(1_000)
        .time_limit_total(Duration::from_secs(3_600))
        .store(SqliteStore::open("crawl.sqlite")?)
        .build()?
        .crawl();

    while let Some(event) = crawl.next().await {
        match event {
            CrawlEvent::Page { page, .. } => println!("{}", page.url),
            CrawlEvent::Finished { reason, error, .. } => {
                eprintln!("{reason:?}: {error:?}");
            }
            _ => {}
        }
    }
    Ok(())
}
```

Keep consuming through the end of the stream, not just until the first page or the `Finished` event. The scheduler must finish and release the checkpoint before another execution opens it. If your request is about to time out, request cancellation early and keep draining. See [graceful shutdown](graceful-shutdown).

Subsequent requests
-----------------------------------------------------------------------------------------------------------------

Reopen the same file, use the same seed, and supply the intended configuration again. Running this example repeatedly takes further batches of up to ten URL jobs.

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

#[tokio::main]
async fn main() -> Result {
    let mut crawl = Crawler::builder("https://example.com")?
        .max_pages(10)
        .max_pages_total(1_000)
        .time_limit_total(Duration::from_secs(3_600))
        .store(SqliteStore::open("crawl.sqlite")?)
        .build()?
        .crawl();

    while let Some(event) = crawl.next().await {
        if let CrawlEvent::Finished { reason, progress, error } = event {
            eprintln!(
                "{reason:?}, {} queued, {} attempts total, error: {error:?}",
                progress.queued, progress.attempted,
            );
        }
    }
    Ok(())
}
```

Startup returns in-flight claims to the queue. Completed, failed, skipped, and mapped URLs remain terminal; they are not automatically retried on resume. Newly supplied scope and depth policies apply to queued work. A URL refused on resume becomes a terminal skip.

Configuration is not stored. Reapply headers, authentication, scope, extractors, renderers, and limits yourself. A checkpoint with a different seed is rejected. Use a new checkpoint for a fresh crawl or to fetch terminal URLs again.

Budgets and progress
--------------------------------------------------------------------------------------------------------------------

`max_pages` and `time_limit` are per-execution limits. Their `_total` counterparts subtract persisted attempts or elapsed time from the configured total. The tighter remaining limit wins. Repeating a total of 1,000 does not grant another 1,000 attempts on every resume.

An attempt is one URL job, not one retry. The store records it before its first fetch, so interrupted attempts still consume the total budget. Scope/depth/robots refusals and mapped targets do not consume fetch attempts. Discovery and terminal counts are cumulative; retries and malformed-reference counts describe the current execution.

Elapsed time includes initialization and event-stream backpressure. It is persisted during scheduler cleanup, including normal completion and handled cancellation. A hard process crash can lose elapsed time from the interrupted execution. Persisted attempts are not refunded. Total elapsed time is therefore not a crash-proof wall-clock deadline or a billing limit.

Checkpoint leases
-----------------------------------------------------------------------------------------------------------

`SqliteStore::open` takes an exclusive OS lease using a companion `.lock` file. Another open of the same checkpoint fails while the store is alive, including before a crawl starts or after it finishes if your application retains a shared store reference. You must also ensure only one scheduler uses an existing store instance. `shared_store` does not enforce that requirement; sharing one instance bypasses the separate-open protection.

Do not delete a lock file to bypass an active lease. Keep the database, WAL, and related files together. Stop the scheduler and release all store references before moving or reopening a checkpoint. A stale filename is not itself an active OS lease; a crashed process releases the lease.

Output is not a checkpoint
--------------------------------------------------------------------------------------------------------------------------------------

The store atomically commits completion and discoveries **before** emitting the page/failure/mapping event. A crash after that commit can leave a terminal URL whose event never reached your output. An interrupted fetch can also run again after recovery.

Neither the event stream nor `on_event` provides exactly-once output, output acknowledgements, or a durable page archive. Appending JSONL is not an atomic transaction with the frontier. Persist results separately. If your application needs atomic completion and result storage, design a storage protocol for that requirement rather than treating emitted events as an acknowledged queue. See the [custom store contract](using-a-custom-crawl-queue).

 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)
