Skip to content

Keeping It Running

Martin Olveyra edited this page Nov 24, 2026 · 3 revisions

Previous Chapter: The Post-Crawl Data Chain


Introduction

A workflow of independent agents has no coordinator, so it needs two things that a coordinator would otherwise provide: something that keeps every component running, and ways of controlling how fast each one works. This chapter covers both, and the operational practices that keep such a workflow healthy over months of continuous operation.

The keep-alive scheduler

Run to completion components (deliveries, monitors, reducers) are naturally scheduled as ScrapyCloud periodic jobs. For the continuous ones (crawl managers, consumers, deduplicators) the usual tool is a keep-alive scheduler: a small script, itself run as a periodic job (for example, every hour), that lists the running jobs and schedules every component that should be running and isn't:

import logging

from shub_workflow.script import BaseScript

from myproject.scripts.consumer import Consumer
from myproject.scripts.crawlmanager import ENABLED_SPIDERS


class Scheduler(BaseScript):

    @property
    def description(self):
        return "Keep the workflow components alive."

    def running_commands(self, script: str):
        jobs = self.get_jobs(spider=script, state=["pending", "running"], meta=["job_cmd"])
        return {tuple(jdict["job_cmd"][1:]) for jdict in jobs}

    def keep_alive(self, script: str, args_list, units: int = 1):
        running = self.running_commands(script)
        for args in args_list:
            if tuple(args) not in running:
                self.schedule_script([script, *args], units=units)

    def run(self):
        self.keep_alive("py:crawlmanager.py", [[spider] for spider in ENABLED_SPIDERS])
        self.keep_alive("py:consumer.py", [["class:MySiteBaseSpider"]], units=2)
        self.keep_alive("py:deduplicator.py", [[str(slot)] for slot in range(Consumer.parallel_outputs)], units=6)


if __name__ == "__main__":
    from shub_workflow.utils import get_kumo_loglevel

    logging.basicConfig(format="%(asctime)s %(name)s [%(levelname)s]: %(message)s", level=get_kumo_loglevel())
    Scheduler().run()

The scheduler holds no state and knows nothing about the work: the list of components that should run comes from the configuration of the project (the enabled spiders, the number of slots). Enabling a new spider is adding it to ENABLED_SPIDERS; on the next run, the scheduler starts its crawl manager.

A useful consequence: any component can be restarted by just stopping it. A component stopped in order to deploy a new version, to apply a configuration change, or because it misbehaves, is started again by the next run of the scheduler, with the new code. Some components even use this on purpose, stopping other ones (for example, a crawl manager stopping a permanent spider, so that its items are flushed to the consumer).

Continuous and run to completion components

Continuous components run with loop_mode, until they stop. They stop when their work is exhausted (a crawl manager whose slot is empty), when they reach a capacity limit (a deduplicator at MAX_ITEMS), when they fail, or when they reach their max_running_time. Setting a maximal running time on purpose (a day, a week) recycles the continuous components regularly: they release their memory, they pick up any new deploy, and the scheduler starts them again. A random extra time, of up to max_running_time_jitter (default 5%) of max_running_time, is always added to it, so the components started together (say, a set of deduplicator slots) don't all stop, and restart, together again: as the extra time is always positive, successive restarts keep drifting them apart.

Run to completion components process the work available and stop: the deliveries and the reducers (close_on_no_inputs = True), the monitors. Their periodicity is the period of their periodic job.

Self-resuming, role by role

Every component must be able to start from scratch and continue the work of its previous instance. These are the mechanisms each role relies on:

Role What a new instance needs Provided by
Crawl manager not to exceed its running jobs, nor to lose track of the jobs left running acquire_all_jobs = True (see Crawl managers scheduled automatically), with get_owned_jobs() narrowed to its spider
Crawl manager the pending seeds the frontier
Spider nothing its arguments
Consumer which jobs were already consumed the CONSUMED tag of the jobs
File stages which files were already processed the processed files are removed or moved
Deduplicator the ids already seen load_last_outputs() on start
Downloader manager which batches are taken the claim-by-move into the processing folder
Scheduler, monitor nothing —

One instance per role

shub-workflow doesn't prevent two instances of the same component from running at the same time: it is the job of whoever starts them. In this architecture, that is the scheduler, which only starts a component if no job with the same command is pending or running. ScrapyCloud also refuses to schedule a job identical to one that is pending or running, so the same command can't be started twice, even by two concurrent schedulers.

Two instances of the same role would not lose data, as the state is in the storage, but they would break the single writer rule of the frontier (two consumers writing the same slots), and double the number of spider jobs of a crawl manager. So when you start a component by hand, with different arguments than the scheduler uses, make sure the scheduled one is stopped.

Controlling the throughput

The number of spider jobs running for each source is the main control of a workflow. As Per source configuration showed, max_running_jobs can be a property that reads the ScrapyCloud project settings on every loop, so it can be changed at any time without deploying. Setting it to 0 pauses a source: the running jobs finish, and no new ones are scheduled.

Being a property, it can also implement policies. For example, a time of day factor that lowers the load on a site during its busy hours:

from datetime import datetime

HOURLY_FACTOR = {hour: 0.5 for hour in range(14, 22)}   # half load from 14 to 22 UTC


class CrawlManager(GeneratorCrawlManager):
    ...

    @property
    def max_running_jobs(self) -> int:
        base = self.configured_running_jobs()
        if base == 0:
            return 0
        return max(1, int(base * HOURLY_FACTOR.get(datetime.utcnow().hour, 1)))

Back-pressure

Each stage works at its own pace, so the queues between stages can grow without limit when a downstream stage is slower than the upstream one. Back-pressure is the mechanism by which a stage slows down when the queue after it is too long. In a workflow of independent agents it is implemented in the crawl managers, by making max_running_jobs depend on the depth of a downstream queue:

import os
import time


class CrawlManager(GeneratorCrawlManager):
    ...
    queue_folder = "gs://mybucket/download_queue"
    max_queued_batches = 1000

    def __init__(self):
        super().__init__()
        self.last_queue_check = 0.0
        self.queue_is_full = False

    @property
    def max_running_jobs(self) -> int:
        if time.time() - self.last_queue_check > 3600:      # list the queue at most once per hour
            self.last_queue_check = time.time()
            source = self.get_canonical_spidername(self.spider)
            queued = sum(1 for _ in self.fshelper.list_path(os.path.join(self.queue_folder, f"{source}_")))
            self.queue_is_full = queued >= self.max_queued_batches
        if self.queue_is_full:
            return 0
        return super().max_running_jobs

Before adding back-pressure, think about what it protects. Data waiting in a queue is not always data at risk: a batch whose information is already captured can wait for a long time. Where waiting does lose data — for example, seeds waiting in the frontier for a listing that disappears in the meantime — the gate should protect that stage, and its threshold should be derived from measurements (how fast the queue drains, how fast the data decays), not picked arbitrarily.

Reacting to the site

Sites react to the load: they start answering with errors, rate limiting responses (HTTP 429) or bans. A crawl manager can sample the recent finished jobs of its spider — their stats are aggregated in the manager stats (see Aggregated stats in Crawlmanager), and can also be read with get_jobs() — and adapt:

  • lower the number of running jobs, the concurrency of each job (through the job settings), or the seeds per job, when the error rate goes up, and raise them again slowly when it goes down;
  • enter a "jail" state when the ban rate exceeds a threshold — a single job at a time — and leave it only after the rate has been low for a while.

Whatever the policy, log every decision with the rates that motivated it: when the throughput of a source drops, those logs are the first place to look.

Failures

A job that finishes with a failed outcome (see Handling bad outcomes) is retried by the crawl manager if MAX_RETRIES is set, with the same arguments, seeds included. Some outcomes, however, mean that continuing makes no sense, for example when the account of a paid service used by the spiders is suspended. The crawl manager can stop itself on them:

class CrawlManager(GeneratorCrawlManager):
    ...

    def bad_outcome_hook(self, spider, outcome, job_args_override, jobkey):
        if outcome == "account_suspended":     # a custom close reason of the spiders
            self.workflow_loop_enabled = False
        else:
            super().bad_outcome_hook(spider, outcome, job_args_override, jobkey)

Avoid unbounded retries inside the spiders, too. A spider that keeps retrying, for example, a failing login, never finishes, and the items it already extracted never reach the consumer, which only reads finished jobs. The same applies to spiders that are meant to run forever: they must be stopped periodically (by a time limit, or by another component), so that their items flow into the workflow.

Recrawling over time

As explained in A seed runs once, the frontier slots drain, and recrawling requires resetting them. A crawl manager can do it automatically when its slot is empty and more data is needed downstream:

from hcf_backend.utils.hcfpal import HCFPal


class CrawlManager(GeneratorCrawlManager):
    ...

    def set_parameters_gen(self):
        # read_seeds_gen() is the seeds reading generator of Feeding Spiders, self.slot the slot it reads,
        # and queue_is_full the back-pressure flag of the previous section
        slot_was_empty = True
        for params in self.read_seeds_gen():
            slot_was_empty = False
            yield params
        if slot_was_empty and not self.queue_is_full:
            HCFPal(project_id=self.project_id).delete_slots(self.project_settings["FRONTIER_NAME"], [self.slot])
            self.schedule_spider(self.spider)       # a seed job, that crawls from the home page

Other recrawls are periodic by nature, for example a full sweep of some sources every quarter. These are better started by the scheduler, with two precautions. Spread the sweeps over time (for example, start each one only at the hour of the day given by a hash of its name, so that they don't all start at once). And decide whether a sweep is due from the age of its last run, with a threshold a bit shorter than the period (for example, 75 days for a quarterly sweep): a run that started late doesn't then shift all the following ones.

import time
from datetime import datetime

from shub_workflow.issuer import hash_mod

SWEEP_SPIDERS = ("mysite.com_sweep", "othersite.com_sweep")
MIN_AGE_DAYS = 75


class Scheduler(BaseScript):
    ...

    def sweep_is_due(self, spider: str) -> bool:
        if hash_mod(spider, 24) != datetime.utcnow().hour:
            return False
        for jdict in self.get_jobs(spider=spider, state=["finished"], count=1, meta=["finished_time"]):
            return time.time() - jdict["finished_time"] / 1000 > MIN_AGE_DAYS * 86400
        return True

    def run(self):
        ...
        for spider in SWEEP_SPIDERS:
            if self.sweep_is_due(spider):
                self.schedule_spider(spider)

Operating the workflow

A workflow of independent agents is observed through the storage and the stats, not through a central manager. The Monitors chapter describes how to aggregate the stats of all the jobs of a period into reports and alerts. Some practices help in the daily operation:

  • When the output of a source drops, check in this order: are there seeds in its slots (the frontier tool --count)? Is its crawl manager running, and how many jobs is it allowing (its logs)? Are the spider jobs extracting items, or is the site blocking them? A drained slot is the most common cause of a slowly decreasing output.
  • When a spider breaks completely, pause its source first (running jobs to 0): a broken spider fed by a crawl manager burns through thousands of seeds in short jobs that extract nothing.
  • To deploy a new version of a component, deploy and stop it: the scheduler starts the new version.
  • Keep the per source configuration in one place (the crawl manager module, or the project settings), so that the state of each source can be read at a glance.

Next Chapter: Reference Architectures

Clone this wiki locally