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. [ Checkpoint guarantees ](#content-checkpoint-guarantees)

You can use `max_pages` to break up long running crawls across multiple requests or worker jobs. This is useful in serverless environments or when you want to avoid timeouts. See [setting crawl limits](../configuring-the-crawler/setting-crawl-limits) for all available options.

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

To start crawling across different requests, create a `SqliteStore` and pass it to the crawler. The store saves queued URLs and their processing state as the crawl progresses, without a separate serialization step:

```
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 reading until the stream ends before reopening the checkpoint. If your request is about to time out, [cancel early and let cleanup finish](graceful-shutdown).

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

For following requests, reopen the same database and pass it to the crawler:

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

This processes another batch of up to ten URLs, up to 1,000 attempts and one hour across executions. Use the same seed and reapply your configuration: the database stores crawl state, not headers, filters or renderer settings. A different seed is rejected. Use a new database for a fresh crawl.

Checkpoint guarantees
-----------------------------------------------------------------------------------------------------------------------

### Recovery and limits

On startup, unfinished claims return to the queue. Completed, failed, skipped and mapped URLs stay terminal and are not fetched again. New scope and depth settings apply to queued work; URLs refused on resume become terminal skips.

Attempt counts are saved before fetching, so interrupted attempts still consume the total page limit. Elapsed time includes initialization and output backpressure, but is saved during cleanup. A crash can lose elapsed time from the interrupted execution; it does not refund attempts. See [limits](../configuring-the-crawler/setting-crawl-limits) for what counts toward each limit.

### Exclusive access

Use only one scheduler per store, including stores passed through `shared_store`. `SqliteStore::open` takes an exclusive OS lease through a companion `.lock` file, but sharing an already open store does not prevent concurrent schedulers.

Release all store references before reopening or moving a checkpoint. Keep the database, WAL and related files together. Do not delete a lock file to bypass a live lease. Crashed processes release their OS leases automatically.

### Saving output

A checkpoint saves URL state, not page bodies or acknowledged output. Completion and new discoveries commit before the page, failure or mapping event is emitted. A crash between that commit and delivery can leave a completed URL with no saved result. Interrupted fetches can run again after recovery.

Neither the event stream, observers nor appending JSONL guarantees exactly-once output. Save results separately. If you need completion and result storage to commit atomically, you'll need a storage protocol that covers both; implementing a [custom store](using-a-custom-crawl-queue) alone does not provide it.

 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)
