Skip to content

Feeding Spiders

Martin Olveyra edited this page Oct 29, 2026 · 7 revisions

Previous Chapter: Independent Agents and Role Separation


Introduction

In the independent agents architecture the spiders know nothing about the crawl frontier: a crawl manager reads the seeds from the frontier and passes them to each spider job as an argument (see Who reads and who writes the frontier). This chapter describes both sides of that exchange — what the spider expects, and how the crawl manager provides it — and the decisions it involves: how to name the frontier slots, how many seeds to give to each job, and what happens to the seeds of a job that fails. It also covers the other way of feeding spiders: with a pointer to a batch file.

We continue with the running example of Seeds instead of urls: a site where articles are listed by tag and by author. There are two spiders, one that crawls tag listings and one that crawls author pages, and two frontier slots, one for each kind of seed.

The spider side: receiving seeds

A spider fed by a crawl manager receives a list of seeds, JSON encoded, in a single argument, and builds its start requests from them:

import json

from scrapy import Request, Spider


class MySiteBaseSpider(Spider):

    canonical_name = "mysite.com"   # the source, shared by all the spiders of the site

    # the kind of seeds this spider reads (it determines the frontier slot)
    seeds_source = ""
    # the item fields from where the consumer harvests new seeds
    seeds_fields = ("tags", "authors")

    def __init__(self, seeds="[]", *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.seeds = json.loads(seeds)

    def start_requests(self):
        for seed in self.seeds:
            yield self.make_seed_request(seed)

    def make_seed_request(self, seed: str) -> Request:
        raise NotImplementedError


class MySiteTagsSpider(MySiteBaseSpider):

    name = "mysite.com_tags"
    seeds_source = "tags"

    def make_seed_request(self, seed: str) -> Request:
        return Request(f"https://mysite.com/tag/{seed}", callback=self.parse_listing)

    def parse_listing(self, response):
        ...  # yield the articles, each one with its tags and authors, and follow the next pages


class MySiteAuthorsSpider(MySiteBaseSpider):

    name = "mysite.com_authors"
    seeds_source = "authors"

    def make_seed_request(self, seed: str) -> Request:
        return Request(f"https://mysite.com/author/{seed}", callback=self.parse_listing)

    def parse_listing(self, response):
        ...

Nothing in the spider refers to the frontier, the crawl manager or the workflow. It can be developed and tested as any other spider, by passing some seeds from the command line:

$ scrapy crawl mysite.com_tags -a seeds='["python", "scraping"]'

The two class attributes seeds_source and seeds_fields are not used by the spider itself: they are metadata for the workflow. The crawl manager uses seeds_source to know from which slot to read the seeds for this spider, and the consumer uses seeds_fields to know which fields of the items carry new seeds, as we will see in the next chapter. Keeping them in the spider class puts all the knowledge about a source in a single place. A base class can validate them for every spider at import time (for example, in __init_subclass__()), so that a misconfigured spider breaks every scrapy command immediately, instead of failing silently in production.

Slot naming

A simple and robust convention is one slot per source and kind of seed: <canonical name>_<seed field>. In our example, mysite.com_tags and mysite.com_authors. Both the crawl manager (reading) and the consumer (writing) compute the slot name with the same function, which is usually defined in a module shared by the project scripts:

def get_slotname(canonical_name: str, seeds_field: str) -> str:
    return f"{canonical_name}_{seeds_field}"

As the slot depends on the canonical name of the spider, and not on its name, all the spiders of the same source share the same slots. A source can have a new spider (for example, a new version) that reads the same seeds as the old one, without migrating the frontier.

The crawl manager side: reading seeds

The crawl manager is a GeneratorCrawlManager whose generator reads the seeds of the target spider from its slot, groups them into chunks, and yields one job per chunk. It runs one instance per spider, with the spider as command line argument:

import json
import logging

from hcf_backend.manager import HCFManager
from shub_workflow.crawl import GeneratorCrawlManager

from myproject.utils import get_slotname

LOGGER = logging.getLogger(__name__)


class CrawlManager(GeneratorCrawlManager):

    name = "crawlmanager"
    loop_mode = 60
    default_max_jobs = 4
    # scheduled automatically: adopt the jobs of the previous instance (see Keeping It Running)
    acquire_all_jobs = True
    dont_acquire_finished_jobs = True

    seeds_per_job = 100

    def __init__(self):
        super().__init__()
        self.hcf = HCFManager(self.project_settings["FRONTIER_NAME"], project_id=self.project_id)

    def get_owned_jobs(self, project_id=None, **kwargs):
        # own every job of the target spider, whoever scheduled it (see below)
        yield from self.get_jobs(project_id, spider=self.spider, **kwargs)

    def set_parameters_gen(self):
        spidercls = self.spider_loader.load(self.spider)
        canonical_name = self.get_canonical_spidername(self.spider)
        slot = get_slotname(canonical_name, spidercls.seeds_source)
        while True:
            seeds = []
            for batch in self.hcf.read(slot, self.seeds_per_job * self.max_running_jobs):
                seeds.extend(fp for fp, _ in batch["requests"])
                self.hcf.delete(slot, [batch["id"]])
            if not seeds:
                LOGGER.info(f"No more seeds in slot {slot}.")
                break
            for i in range(0, len(seeds), self.seeds_per_job):
                yield {"seeds": json.dumps(seeds[i: i + self.seeds_per_job])}

A few details are worth noticing:

  • The generator is consumed lazily: on each loop the crawl manager only takes from it as many jobs as free running slots it has. So the frontier is read a little at a time, as the jobs can be scheduled, and the amount read on each turn (seeds_per_job * max_running_jobs) is roughly what fills the running jobs once.
  • When the slot is empty, the generator ends. The crawl manager then waits for its running jobs to finish, and closes. This is not a problem, but a feature: it will be started again later (see Keeping It Running), and by then the consumer will have written new seeds.
  • get_owned_jobs() is overridden to change which jobs the manager considers its own. By default, a manager owns the jobs it scheduled itself, matched by its flow id and its name (PARENT_NAME). The override widens that to all the jobs of the target spider, whoever scheduled them: a previous instance of the manager, but also a seed job started by hand, so they all count against the running jobs limit. At the same time it keeps the instances apart: all of them share the name crawlmanager, so with acquire_all_jobs = True alone (ownership by name), each instance would adopt the spider jobs of all the others.
  • The seeds are deleted from the frontier as soon as they are read. We come back to this decision below.
  • For many jobs per loop, the AsyncSchedulerCrawlManagerMixin (see Scheduling jobs concurrently) makes scheduling faster, with no change in the generator.

Per source configuration

Different sources need different settings: seeds per job, running jobs, units. The recommended approach is a single dictionary at the top of the crawl manager module, with an entry per enabled spider whose value holds all the parameters of that spider. It also serves as the list of enabled spiders. Prefer it over one dictionary per parameter (a SEEDS_PER_JOB dict, a RUNNING_JOBS dict, ...): each spider's configuration stays in one place, and typing the entries with a TypedDict lets mypy catch a misspelled key:

from typing import Dict, Optional, TypedDict


class SpiderConfig(TypedDict, total=False):
    RUNNING_JOBS: Optional[int]  # None or absent: read from the ScrapyCloud project settings
    SEEDS_PER_JOB: int  # default 1
    SC_UNITS: int  # default 1


ENABLED_SPIDERS: Dict[str, SpiderConfig] = {
    "mysite.com_tags": {"SEEDS_PER_JOB": 10, "RUNNING_JOBS": 4},
    "mysite.com_authors": {"SEEDS_PER_JOB": 100, "RUNNING_JOBS": None, "SC_UNITS": 2},
}


class CrawlManager(GeneratorCrawlManager):
    ...

    @property
    def seeds_per_job(self) -> int:
        return ENABLED_SPIDERS[self.spider].get("SEEDS_PER_JOB", 1)

    @property
    def max_running_jobs(self) -> int:
        running_jobs = ENABLED_SPIDERS[self.spider].get("RUNNING_JOBS")
        if running_jobs is None:
            # read it from the ScrapyCloud project settings, so it can be changed without a deploy
            settings = self.get_sc_project_settings()
            running_jobs = int(settings.get(f"{self.spider.upper()}_RUNNING_JOBS", 1))
        return running_jobs

Values that change often — the number of running jobs is the typical one — are better read from the ScrapyCloud project settings, as above: they can be changed from the dashboard, and the running manager picks the new value on its next loop, with no deploy at all. Setting it to 0 pauses a source. As max_running_jobs is a property, it can also implement more elaborate policies, which are described in Keeping It Running.

The ready-made seeds crawl manager

shub-workflow ships the crawl manager described in the previous sections, ready to subclass: HCFSeedsCrawlManager, in shub_workflow.utils.hcf (it requires the with-hcf-backend extra). It reads the slot of the target spider, deleting the batches as it reads them, schedules one job per chunk of seeds, ends when the slot is empty, owns all the jobs of its target spider (acquire_all_jobs plus the get_owned_jobs() override shown above), and takes the running jobs, seeds per job and units of each spider from an ENABLED_SPIDERS dictionary of SeedsSpiderConfig entries, as in the previous section:

from shub_workflow.script import SpiderName
from shub_workflow.utils.hcf import HCFSeedsCrawlManager


class CrawlManager(HCFSeedsCrawlManager):

    name = "crawlmanager"
    loop_mode = 60
    ENABLED_SPIDERS = {
        SpiderName("mysite.com_tags"): {"SEEDS_PER_JOB": 10, "RUNNING_JOBS": 4},
        SpiderName("mysite.com_authors"): {"SEEDS_PER_JOB": 100, "RUNNING_JOBS": None, "SC_UNITS": 2},
    }


if __name__ == "__main__":
    CrawlManager().run()

Starting it for a spider that is not in ENABLED_SPIDERS is an error. The rest of its behavior is set with class attributes and hooks:

Attribute / hook Default Purpose
frontier_name the FRONTIER_NAME project setting the frontier to read
seeds_argument "seeds" the spider argument that receives the json list of seeds
SLOT_SPLITS {} number of slots of a split source, by canonical name (see below)
fatal_outcomes () close reasons of the spider jobs that stop the crawl (i.e. a suspended account)
get_base_slotname(spider) <canonical name>_<seeds_source>, or the canonical name if the spider has no seeds_source the slot of the given spider, following the naming above. It is computed for every enabled spider (see below), so an override must use the spider argument
filter_out_seed(seed, qdata) keep every seed drop seeds read from the frontier (i.e. by their qdata)
requested_seeds() SEEDS_PER_JOB * max_running_jobs how many seeds to read each time
process_seeds(seeds) unchanged transform the seeds before they are chunked into jobs
build_schedule_args(seeds) {seeds_argument: <json>, "units": SC_UNITS} the scheduling arguments of each job (add spider arguments, job settings, tags)
on_empty_frontier() log called when the frontier of the spider is empty, before the generator ends (i.e. reset the slot and schedule a seed job)

Each enabled spider must have its own slots. Two crawl managers reading the same slot would both schedule the seeds they read, as reading a slot doesn't remove its batches until they are deleted. So, on start, the crawl manager checks the slots of every enabled spider, and refuses to start (with an argument error) if a slot of its spider is also a slot of another one. Only the managers of the spiders involved fail, so the rest of the sources keep running. The usual cause is a spider variant that misses its own seeds_source and so inherits the one of the spider it derives from. Spiders that are not in ENABLED_SPIDERS, such as periodic seeders that run with their own seeds, may share slots.

max_running_jobs is also a property you can override, to add policies such as the back-pressure described in Keeping It Running. It reads the frontier only, so it fits with any consumer that writes the slots with the same naming.

When a source is too big for a single consumer, its slot can be split (see One writer per slot). Set SLOT_SPLITS = {"mysite.com": 5} and the crawl manager reads the slots mysite.com_tags, mysite.com_tags_1, ..., mysite.com_tags_4 in rotation: each read starts with the slot that follows the last one read, and an empty slot is skipped, so the generator only ends when all of them are empty.

💡 Claude assistance. shub-workflow ships a Claude Code plugin, shub-workflow-toolkit, whose shub-workflow-hcf skill teaches Claude how to read and write seeds in a crawl frontier, including this crawl manager. Install it as described in the repository README and Claude will be able to assist you.

How many seeds per job

The number of seeds per job determines the duration of the jobs, and it is the first parameter to tune for a new source. Both extremes are harmful:

  • Too short jobs waste resources in job startup, flood the project with jobs, and, if the spider is broken, burn through thousands of seeds in minutes without extracting anything. A rule of thumb is that a job should last at least several minutes.
  • Too long jobs delay everything downstream. The consumer only reads finished jobs, so the items of a job, and the new seeds they carry, reach the workflow only when the job finishes. The monitors also only see the stats of finished jobs. And a long job that fails loses more work.

A spider whose seeds lead to very different amounts of work (a tag with ten articles, a tag with ten thousand) can cap its own duration with a Scrapy close setting, like CLOSESPIDER_ITEMCOUNT or CLOSESPIDER_TIMEOUT, passed in the job settings. Notice, however, that the unvisited part of a seed is then lost.

The seeds of a failed job

In the crawl manager above, the seeds are deleted from the frontier when they are read, before their job even starts. If the job then fails, its seeds are not in the frontier anymore. And because of the fingerprint memory of the frontier, the consumer cannot simply write them again: the slot would discard them as already seen.

This is a deliberate trade-off. Deleting on read keeps the crawl manager simple and stateless: there is no need to track which seeds are in which job, and no risk of scheduling the same seeds twice after a restart. In return, a failed job loses its seeds. In a self-feeding crawl, where every seed is discovered from many listings, the loss of a small fraction of seeds is often irrelevant. When it is not, the seeds are still in the arguments of the failed job, and there are several ways to recover them:

  • Retry the job. GeneratorCrawlManager retries failed jobs with the same arguments, seeds included, when MAX_RETRIES is set (see Retries). This is the simplest option when failures are transient.
  • Write them into a retry slot. In bad_outcome_hook(), write the seeds of the failed job into a separate slot (for example, <slot>_retry) that the generator reads before the main one. A different slot has its own fingerprint memory, so the seeds are accepted.

Both rely on the hooks of the crawl manager, so they only recover the failures that a crawl manager sees. A job that is still running when its manager is replaced by a new instance is adopted by the new one (job acquisition), which then sees its outcome. But a job that finishes while no manager is running is not seen at all, if the manager doesn't acquire finished jobs.

Bootstrapping a crawl

A self-feeding crawl needs some initial seeds. There are several ways to put them in the frontier:

  • By hand, with the frontier tool (see Inspecting and handling a frontier by hand): frontier_tool.py mysite.com_tags -a python -a scraping.
  • With a seed job: the same spider, run once with some seeds passed by command line, or with a mode in which it starts from the home page. Its items carry seeds, and the consumer writes them into the frontier as for any other job. This is also the way to restart a crawl after deleting its slot.
  • With a seeder spider, a spider that runs periodically and whose only purpose is to discover seeds, for example from a sitemap or from a "what's new" page.
  • With seeds generated outside the crawl, for example a range of numeric ids, added with a custom command of the frontier tool. If no spider harvests that kind of seed (its field is not in any seeds_fields), the slot is never replenished: it is a fixed list of work that drains once.

Feeding spiders with batch files

Seeds in a spider argument fit when each seed is short and leads to a lot of work. When each job needs a large amount of input — thousands of urls to download, records to enrich —, the input is better passed as a batch file: the crawl manager passes the path of a file in S3 or GCS, and the spider reads its input from it. The typical case is a downloader spider, which downloads the media files of the items that went through the processing chain.

Batch files come from a folder that works as a queue, like the output folder of an issuer. The crawl manager claims a file by moving it into a processing folder before scheduling the job that will read it:

import os

from shub_workflow.crawl import GeneratorCrawlManager


class DownloaderCrawlManager(GeneratorCrawlManager):

    name = "downloader_crawlmanager"
    loop_mode = 60
    default_max_jobs = 8
    spider = "downloader"
    acquire_all_jobs = True
    dont_acquire_finished_jobs = True

    input_folder = "gs://mybucket/download_queue"
    processing_folder = "gs://mybucket/downloading"

    def set_parameters_gen(self):
        for fname in self.fshelper.list_path(os.path.join(self.input_folder, "")):
            dest = os.path.join(self.processing_folder, os.path.basename(fname))
            self.fshelper.mv_file(fname, dest)    # the move is the claim
            yield {"input_batch_file": dest}

The move is what prevents the same file from being scheduled twice, even after a restart: once moved, the file is not in the input folder anymore. A batch claimed by a job that later fails stays in the processing folder, from where it can be moved back to the queue. And, as warned in Deferring jobs, a job that claims its input must not be deferred after the claim: decide whether a job can be scheduled before moving the file.

When a single downloader manager serves many sources, taking the batches in the order they are listed would let the source with the biggest backlog monopolize the downloads. Rotating over the sources, one batch per source per turn, gives each one an even share:

from itertools import cycle

ENABLED_SOURCES = ("mysite.com", "othersite.com")


class DownloaderCrawlManager(GeneratorCrawlManager):
    ...

    def set_parameters_gen(self):
        exhausted = set()
        for source in cycle(ENABLED_SOURCES):
            if len(exhausted) == len(ENABLED_SOURCES):
                break
            for fname in self.fshelper.list_path(os.path.join(self.input_folder, f"{source}_")):
                dest = os.path.join(self.processing_folder, os.path.basename(fname))
                self.fshelper.mv_file(fname, dest)
                yield {"input_batch_file": dest}
                exhausted.discard(source)
                break
            else:
                exhausted.add(source)

The batch files start with the source name, as the issuers write them (see Batches, slots and filenames), so the listing by prefix selects the batches of one source.

Url frontiers: batch files built from the frontier

Seeds don't always fit. Sometimes the units of work are urls that can't be reduced to a short key: urls found in pages, urls coming from an external list, urls of very heterogeneous sites. Even then, the frontier is worth having: it deduplicates every url, with memory, and it keeps the pending work safe between jobs. But a spider argument can't carry the thousands of urls a job needs, and letting the spiders read the frontier would bring back the problems the independent agents architecture avoids (see Who reads and who writes the frontier).

The solution is to let the crawl manager do what the spider can't: read the urls from the frontier, write them into a batch file, and pass the spider the path of the file. The rest of the workflow doesn't change: the spider puts the new urls it finds in its items, and the consumer writes them into the frontier.

 frontier ──read──► crawl manager ──writes──► pending/ ──claim──► processing/ ──► spider job
 (urls slot)          │ deletes the batches                         (input_batch_file)  │
     ▲                │ once the file is written                                        │ items with
     │                └─ schedules the job with the file path                           │ new urls
     └──────────────────────────── consumer ◄───────────────────────────────────────────┘

The frontier. The fingerprint of each request is the url itself (if you prefer shorter fingerprints, use a hash of the canonical url as fingerprint, and put the url in the qdata). The slot works exactly as with seeds: one slot per source and kind (for example, mysite.com_urls), a single writer (the consumer), and each url crawled once per slot.

The crawl manager. It converts the frontier into batch files just in time, one at a time, and feeds the spiders with them as in Feeding spiders with batch files. The files go first into a pending folder, and they are claimed into a processing folder when their job is scheduled. This two-step design is what makes the manager safe to stop at any moment:

import gzip
import json
import os
import tempfile
from datetime import datetime

from hcf_backend.manager import HCFManager
from shub_workflow.crawl import GeneratorCrawlManager

from myproject.utils import get_slotname


class UrlsCrawlManager(GeneratorCrawlManager):

    name = "urls_crawlmanager"
    loop_mode = 60
    default_max_jobs = 10
    acquire_all_jobs = True
    dont_acquire_finished_jobs = True

    urls_per_job = 5000
    batches_folder = "gs://mybucket/url_batches"

    def __init__(self):
        super().__init__()
        self.hcf = HCFManager(self.project_settings["FRONTIER_NAME"], project_id=self.project_id)
        self.pending_folder = os.path.join(self.batches_folder, "pending", self.spider)
        self.processing_folder = os.path.join(self.batches_folder, "processing", self.spider)

    def get_owned_jobs(self, project_id=None, **kwargs):
        yield from self.get_jobs(project_id, spider=self.spider, **kwargs)

    def set_parameters_gen(self):
        while True:
            pending = list(self.fshelper.list_path(os.path.join(self.pending_folder, "")))
            if not pending and not self.frontier_to_batch_file():
                break                                     # no pending files and an empty slot: done
            for fname in pending:
                dest = os.path.join(self.processing_folder, os.path.basename(fname))
                self.fshelper.mv_file(fname, dest)        # the claim
                yield {"input_batch_file": dest}

    def frontier_to_batch_file(self) -> bool:
        slot = get_slotname(self.get_canonical_spidername(self.spider), "urls")
        urls, batch_ids = [], []
        for batch in self.hcf.read(slot, self.urls_per_job):
            urls.extend((qdata or {}).get("url", fp) for fp, qdata in batch["requests"])
            batch_ids.append(batch["id"])
        if not urls:
            return False
        name = f"{datetime.utcnow().strftime('%Y%m%dT%H%M%S.%f')}.jl.gz"
        local = os.path.join(tempfile.mkdtemp(), name)
        with gzip.open(local, "wt") as f:
            for url in urls:
                f.write(json.dumps({"url": url}) + "\n")
        self.fshelper.mv_file(local, os.path.join(self.pending_folder, name))
        self.hcf.delete(slot, batch_ids)                  # only once the file is safely written
        return True

The order of the operations is what gives the guarantees:

  • The frontier batches are deleted after the batch file is written. If the manager stops in between, the same urls are written again into another file by the next instance: they may be crawled twice, but never lost. The duplicated items are absorbed by the deduplication downstream, as for any other at-least-once stage.
  • A file written but not yet scheduled stays in the pending folder, and the next instance schedules it before reading the frontier again. Nothing is orphaned.
  • Only one file is built ahead of the jobs, so the frontier is not drained into files faster than the spiders consume them.

The spider reads its urls from the file:

import gzip
import json

from scrapy import Request, Spider
from shub_workflow.utils.futils import download_file


class MySiteUrlsSpider(Spider):

    name = "mysite.com_urls"
    canonical_name = "mysite.com"

    def __init__(self, input_batch_file=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.input_batch_file = input_batch_file

    def start_requests(self):
        download_file(self.input_batch_file, "batch.jl.gz")
        with gzip.open("batch.jl.gz", "rt") as f:
            for line in f:
                yield Request(json.loads(line)["url"], callback=self.parse)

    def parse(self, response):
        ...  # yield the items; put the new urls to crawl in an item field (e.g. "urls"), for the consumer

The spider needs read access to the bucket (credentials in its environment), and it remains easy to test: a local file path works as well as a bucket path.

The files of finished jobs. A file in the processing folder belongs to a scheduled job. When the job finishes well, the file can be removed, for example from finished_ok_hook(), which receives the job arguments (job_args_override["spider_args"]["input_batch_file"]). When the job fails, bad_outcome_hook() can move the file back into the pending folder, so its urls are crawled again by another job. This is an advantage over seeds passed in arguments: the work of a failed job is not lost, and there is no conflict with the fingerprint memory of the frontier, because the urls are not written into it again. Files left in the processing folder by jobs whose outcome no manager saw can be moved back to pending by hand, or by a sweep at start.

Costs. Compared with seeds, this pattern adds a storage round trip per job and a folder of files to manage. It also moves much more data through the frontier: every url is written, and read, once, which can make the consumer writes the bottleneck (see Writing without blocking the consumer and split slots). Prefer seeds whenever the site offers a short key for its work, and use url batches when it doesn't.


Next Chapter: Closing the Loop

Clone this wiki locally