Skip to content

Reference Architectures

Martin Olveyra edited this page Nov 25, 2026 · 4 revisions

Previous Chapter: Keeping It Running


Introduction

The previous chapters described the parts of the independent agents architecture one at a time. This chapter puts them together in five reference architectures, each one distilled from real projects of increasing complexity. They are not templates to copy as they are, but proven combinations of the patterns, with the reasons behind each choice. The figures given (number of jobs, slots, sizes) are only indicative of the scale each design has supported.

Each architecture is described by its problem, a diagram, its components, and the points that make it work. The diagrams follow the same conventions: bands are stages, boxes are jobs (a pile of boxes with "⋮" means many jobs of the same kind), ellipses are storages, and the bulleted box of each band summarizes its role. Wide arrows are the main data flows.

A. Periodic crawl of many independent spiders

The problem. Crawl every day hundreds of independent sites, and deliver a fresh file per site. Each site has its own spider. The sites are unrelated to each other: there is no processing of the items across jobs, and nothing to discover. The list of sites is the list of spiders of the project.

A. Periodic crawl of many independent spiders

Components.

Component Built on Started by Reads Writes
crawl manager GeneratorCrawlManager daily periodic job the spiders of the project and their tags one job per active spider
site spiders Scrapy spiders the crawl manager their own settings one delivered file per spider, directly
broken spiders check BaseScript periodic job the item counts of the last finished jobs of each spider a deactivated tag on the spiders that stopped producing; a notification

How it works. The crawl manager is a generator crawl manager whose generator yields one job per spider of the project, skipping the spiders tagged deactivated in ScrapyCloud:

from shub_workflow.crawl import GeneratorCrawlManager
from shub_workflow.script import SpiderName


class CrawlManager(GeneratorCrawlManager):

    name = "crawl"
    loop_mode = 120
    spider = SpiderName("")  # every set of parameters yielded names its spider
    default_max_jobs = 16
    MAX_RETRIES = 3

    def set_parameters_gen(self):
        project = self.get_project()
        deactivated = {spider["id"] for spider in project.spiders.list() if "deactivated" in spider["tags"]}
        for spidername in self.spider_loader.list():
            if spidername not in deactivated:
                yield {"spider": spidername}

When the generator is exhausted and the last job has finished, the crawl manager finishes too, and the periodic job starts a new one the next day. So adding a site to the crawl is only deploying its spider: there is no list of sites to keep anywhere else. A run is much shorter than the period (a few hours, for around five hundred spiders), so two runs never overlap; if yours could, see Crawl managers scheduled automatically. MAX_RETRIES reschedules the jobs that end with a failed outcome (see Handling bad outcomes).

The maximal number of jobs is deliberately set higher than the number of ScrapyCloud units of the project (16 jobs for 8 units). The extra jobs wait in the ScrapyCloud pending queue, so a unit freed by a finishing spider is taken at once, instead of waiting for the next loop of the crawl manager. With many short jobs, this keeps every unit busy.

The spiders deliver their own file, with a Scrapy feed export enabled only in the production project: this is the simpler variant of the architecture, with no consumer and no data chain. The quality of the items is checked inside each job too, by the spider's own monitors (for example, with Spidermon: a minimal number of items, a drop compared with the previous job, the coverage of each field, the item schema), which alert when a check fails.

What a single job cannot see is a spider that broke for good: sites change their layout, or move to another system, and their spider starts returning nothing, every day. The broken spiders check, a periodic script, reads the last finished jobs of each active spider and, when its last jobs (for example, the last seven) produced no item at all, adds the deactivated tag to the spider and sends a notification (for example, with the Slack mixin in shub_workflow.contrib.slack). From then on the crawl manager skips it, so broken spiders neither take units nor repeat their alerts every day. Once the spider is fixed, removing the tag in the ScrapyCloud UI puts it back into the next daily run. A third or more of the spiders may be deactivated at a given time: the tag is the to-do list of the maintainers.

Key points. The spiders of the project are the list of work, and a spider tag is the switch that takes one out of it; a generator crawl manager that starts and finishes every day; the quality of each job is checked within the job, and the health of each spider across its jobs, by a periodic script. When the items of a site must be deduplicated across runs, or the crawl must feed itself with new seeds, move on to the next architectures.

B. Request-driven batch crawling

The problem. Customers submit crawl requests at any time: each request is a file with a list of sites to crawl, possibly hundreds, with some options for each one. Every request must be crawled as a unit, its results delivered in a folder of its own, and the customer notified when it is completed. Sites are crawled again in later requests, so the history of each site matters too.

B. Request-driven batch crawling

Components.

Component Built on Started by Reads Writes
request poller BaseScript periodic job the requests folder — (starts a request scheduler when there are requests)
request scheduler BaseScript the poller one request file the file moved into processing; a per-request graph manager
per-request graph manager GraphManager the request scheduler — runs the feeder, then the crawl manager; on close, moves the request to completed and notifies
frontier feeder BaseScript the graph manager the request file one frontier entry per site, in a slot named by the request id
crawl manager GeneratorCrawlManager the graph manager the request slot one spider job per site
site spiders Scrapy spiders the crawl manager their arguments the delivered files, directly; a done marker per site
stats collector BaseScript periodic job the stats of finished jobs (consume-once tag) the run history of each site
alerts GraphManager with two scripts weekly periodic job the stats collector results reports and tickets

How it works. The request file is the unit of work, and its name is the request id, which propagates everywhere: the frontier slot, a tag on every job, the delivery folder. The requests folder is a file queue: the scheduler claims a request by moving it into processing, and the graph manager moves it into completed when it finishes. Rescheduling a request is copying its file back into the requests folder; aborting it, cancelling the jobs tagged with its id.

Each request runs in its own short graph manager, because a request is exactly the case graph managers fit: two steps in a strict order (load the request into the frontier, then crawl it), and a lifecycle (started, completed, notified) that belongs to the request as a whole. The frontier feeder deletes the request slot before writing it, so running it again is harmless. The crawl manager drains the slot, deleting each batch after processing it, so a resumed crawl manager continues where the previous one stopped. It schedules one job per site, with up to around a hundred jobs in parallel, and uses deferred jobs to keep at most one job per site at a time, because different requests may contain the same site.

The spiders deliver directly into the request folder, through Scrapy item pipelines: there is no cross-job processing of the items, so there is no consumer and no data chain — the simpler variant of the architecture.

Around the per-request workflows, two independent agents watch all of them. The stats collector reads the stats of every finished spider job, once (it tags the jobs it processed), stores them in a run history per site, and compares each run with the previous ones to detect drops. That history is also an input of the crawl manager: for incremental crawls, it finds there the previous run of a site and passes the spider the list of urls already delivered, so it can skip them. A weekly alerts graph manager classifies the anomalies found by the stats collector, and sends the reports. A watchdog cancels the spiders that run far longer than expected.

Key points. One request id everywhere; the folder is the state of each request; graph managers for what is a sequence, independent agents for what watches everything.

C. Self-replenishing discovery loop

The problem. Discover, continuously and from dozens of sources, all the items (for example, image urls) that the sources publish, and deliver each new one once. The sources are explored through branch seeds — tags, usernames —, and every listing reveals more seeds. There is no end: the crawl runs for years.

C. Self-replenishing discovery loop

Components.

Component Built on Instances Mode
crawl managers AsyncSchedulerCrawlManagerMixin + GeneratorCrawlManager one per spider continuous
spiders Scrapy spiders fed with seeds many jobs per source —
consumer IssuerScriptWithSCJobInput with a class: target one for all the sources continuous
deduplicators IssuerScriptWithFileSystemInput one per slot (10) continuous
keep-alive scheduler BaseScript one, hourly run to completion
monitor BaseMonitor one, daily run to completion

How it works. This is the complete picture of the independent agents chapter, almost literally. Each spider reads one kind of seed and produces items carrying several kinds, so the spiders of a source feed each other through the frontier (cross seeding). A single consumer reads the jobs of all the sources (a class: target matching their base spider class), writes the new seeds, and partitions the items into 10 slots. Ten deduplicators, with bloom filters of around a billion items each, reload years of their own output on start; and their output is the delivery: the customer reads the deduplicated batches from the bucket. A few sources without a natural seed structure have seeder spiders, run as periodic jobs.

The crawl managers adapt to the sites: each one samples the rate of throttling responses (HTTP 429) of the recent jobs of its spider, and adjusts the concurrency, the seeds per job and the number of parallel jobs within configured limits (see Reacting to the site). The monitor counts every day the new items per source directly from the delivered files.

Key points. The smallest complete version of the architecture. When the output of a source falls, the usual cause is a drained slot (see A seed runs once), and the next check is the speed control logs of its crawl manager.

D. Discovery, filtering, download and delivery

The problem. Discover items (for example, videos) from many sources, keep only the ones that match the customer's filters (language, length, keywords), download each selected file, and deliver the files with their metadata, with a monthly volume target. Some sources are huge, and downloads fail often.

D. Discovery, filtering, download and delivery

Components.

Component Built on Instances Mode
crawl managers and spiders as in C one manager per spider continuous
consumers IssuerScriptWithSCJobInput one per source; 5 for the biggest one continuous
filters IssuerScriptWithFileSystemInput one per slot continuous
deduplicators IssuerScriptWithFileSystemInput one per slot continuous
balancer IssuerScriptWithFileSystemInput one continuous
downloader managers GeneratorCrawlManager one per group of sources, in a separate project continuous
downloader spiders Scrapy spiders fed with a batch file many jobs —
delivery IssuerScriptWithSCJobInput one, every 15 minutes run to completion
keep-alive scheduler, monitor BaseScript, BaseMonitor hourly, daily run to completion

How it works. Discovery is the loop of C, with one consumer per source instead of a single one. The biggest source has its slots split in five, each written by its own consumer instance, which takes the jobs whose number modulo five is its own.

The data chain applies the customer filters before the deduplicators, as explained in The stages. The filters are a file in a bucket, not code: when the customer changes them, the scheduler validates the new file, promotes it, and stops the filters and the crawl managers, which come back with the new filters on its next run. A balancer regroups the deduplicated items into batches per source and filter, with a size per source adapted to the cost of its downloads, forming the download queue.

In this example the downloads run in a different ScrapyCloud project, where the downloader managers schedule their jobs with --project-id, as any shub-workflow script can. They claim batches by moving them, one per source in turn, and include two governors: a ban rate jail, which reduces a source to a single job while its error rate is high, and a monthly target, which stops scheduling downloads once the month's volume is reached. The delivery, every 15 minutes, reads the finished downloader jobs, writes one metadata file per job next to the downloaded files, and writes the recoverable failures back into the download queue as retry batches.

Back-pressure runs through the monitor too: when the download queue of a source runs low, a monitor hook either stops a permanently running discovery spider (so that its items are flushed into the workflow), or resets the slot of a source and schedules a seed job. The crawl managers also apply a time of day factor to their number of jobs.

Key points. Configuration that changes often lives in data and is applied by restarting the agents that use it; every queue between stages is visible, so the governors can act on it.

E. Two-tier discovery and extraction

The problem. Build datasets of items (for example, products with all their images) where every item must be extracted from its own page, because the listings only show a summary. The same items appear in many listings, and items keep changing: a new version may have more images than the previous one.

E. Two-tier discovery and extraction

Components.

Component Built on Instances Mode
discovery crawl managers and spiders as in C one manager per spider continuous
discovery consumer IssuerScriptWithSCJobInput that issues nothing one continuous
extraction crawl managers and spiders as in C, fed with leaf seeds one manager per spider continuous
extraction consumer IssuerScriptWithSCJobInput one per kind of dataset continuous
deduplicator IssuerScriptWithFileSystemInput one per kind of dataset continuous
reducer IssuerScriptWithFileSystemInput one, when needed run to completion
downloader managers and spiders GeneratorCrawlManager, Scrapy spiders one manager per kind of dataset continuous
delivery IssuerScriptWithSCJobInput one, periodic run to completion

How it works. This is the two-tier version of the loop. Discovery spiders crawl listings from branch seeds (tags, sitemaps, sellers) and produce two kinds of seeds: branch seeds, which loop back into the discovery slots, and item ids, the leaf seeds, which go to the extraction slots. The discovery consumer only writes seeds: its items are not used for anything else. Extraction spiders read the item ids and extract each item from its page. The leaf slots are never reset: their fingerprint memory is the record of every item ever extracted.

The extraction consumer filters out the items not wanted (excluded keywords, too few images) and builds the item ids; the deduplicator reloads its own output and the downstream folders (download, reducer) on start. When an entity has versions, the item id includes the version (for example, the number of images), so every new version passes the deduplicator, and a reducer keeps only the best version of each entity before the download. The downloader manager claims the batches by moving them, and limits to one job at a time the sources that require a logged in session. The delivery joins each item with the paths of the images actually downloaded for it, one file per downloader job.

Back-pressure acts on discovery: a discovery crawl manager stops scheduling jobs when the download queue of its source holds more than a thousand batches (measured at most once a day), and when its slot is empty and the queue is low, it resets the slot and schedules a seed job. Some sources are swept completely every quarter instead, by the scheduler, at most once a day, at an hour derived from the source name, and only when the previous sweep is old enough.

Key points. Splitting discovery and extraction gives a frontier of items that deduplicates the extraction for free; versioned ids plus a reducer handle items that change; back-pressure protects the stage where waiting loses data.

Choosing a starting point

Your problem Start from
A fixed set of sites, crawled periodically and delivered each one on its own A
Crawls on demand, each one a unit with its own delivery B
Continuous discovery of new items, delivered as they are found C
Items must be selected by customer criteria, and files downloaded D
Items must be extracted from their own pages, or have versions E

The architectures combine: D and E extend the loop of C, and any of them can include a B-like request flow for special crawls, a weekly graph manager for its reports, or the broken spiders check of A when it runs many spiders of its own. And A grows into B when the crawls must be requested on demand instead of run every day.

💡 Claude assistance. shub-workflow ships a Claude Code plugin, shub-workflow-toolkit, whose shub-workflow-architectures skill helps you design the architecture of your own project in an interactive session: it asks about your requirements, proposes an architecture built on the ideas of these chapters, writes a design document, and scaffolds the scripts. Install it as described in the repository README and ask Claude to help you design your project architecture.

The diagrams of this chapter are generated from a model, diagrams/reference_architectures_gen.py in this wiki repository, with the engine of the shub-workflow-diagrams skill.

💡 Claude assistance. shub-workflow ships a Claude Code plugin, shub-workflow-toolkit, whose shub-workflow-diagrams skill teaches Claude how to draw the architecture diagrams of your own project in this same style. Install it as described in the repository README and Claude will be able to assist you.


Next Chapter: Monitors

Clone this wiki locally