Repository navigation
Issuers
Previous Chapter: Crawl Managers
- Introduction
- A first issuer: consuming spider jobs
- Batches, slots and filenames
- Chaining stages: reading batch files
- Deduplication: short lived and persistent
- Per job processing
- Continuous and run to completion issuers
- Delivery is a configuration
Crawl managers put spiders to work. But the items extracted by the spiders usually need to go through further processing before they reach their final destination: being deduplicated across many jobs, filtered, transformed, split, merged, and finally delivered. In shub-workflow, the component that performs this kind of processing is the issuer.
An issuer reads a massive input — the items of finished spider jobs, or batch files in a folder —,
processes the items one by one, and writes a massive output as batch files. Chaining issuers, each one
reading the output of the previous one, builds the whole post-crawl processing pipeline: consumers, filters,
deduplicators, balancers and delivery scripts are all issuers. The base class is IssuerScript, in
shub_workflow/issuer/__init__.py,
and it is a loop script (see Workflow Fundamentals).
This chapter is an example-led introduction. For the complete reference of the issuer classes, their attributes and hooks, see Appendix G: Issuer Classes.
💡 Claude assistance. shub-workflow ships a Claude Code plugin,
shub-workflow-toolkit, whoseshub-workflow-issuersskill teaches Claude how to build, configure and debug issuers — consumers, deduplicators, filters, balancers and delivery scripts — and how to read the stats they report. Install it as described in the repository README and Claude will be able to assist you.
Let's suppose a spider mysite.com that extracts articles, each one with fields url, title, author and
tags. Its jobs are scheduled by a crawl manager, as we saw in the previous chapter. The first stage that reads
the spider items is typically called a consumer, and it is built on IssuerScriptWithSCJobInput, the issuer
whose input are finished ScrapyCloud spider jobs:
import logging
from shub_workflow.issuer import IssuerScriptWithSCJobInput, IssuerItem, ItemId
class Article(IssuerItem):
url: str
title: str
author: str
tags: list
class Consumer(IssuerScriptWithSCJobInput[Article]):
loop_mode = 120
output_folder = "gs://mybucket/consumer"
default_filesize = 10_000 # items per output batch file
@property
def description(self):
return "Consume mysite.com articles."
def build_item_id(self, item: Article) -> ItemId:
return ItemId(item["url"])
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())
Consumer().run()The only method you must implement is build_item_id(): the identity of an item, used for deduplication and for
routing it to an output slot. The script requires a positional argument, the target, which selects the spiders
whose jobs it reads:
$ python consumer.py spider:mysite.com
The target can be spider:<name> (a single spider), canonical:<name> (all the spiders sharing a canonical
name) or class:<ClassName> (all the spiders of the project that subclass the given class — a single consumer
for many sources).
On each loop, the consumer reads the finished jobs of the target that lack the tag CONSUMED=True, processes
their items, and, once all the items of a job have been written to the output, tags the job as consumed. That is
the consume-once tag
pattern: the consumer holds no state of its own about its inputs, so it can be stopped and restarted at any time
and it will continue with the jobs not yet consumed. Each item gets the fields id, source (the canonical name
of the spider that produced it) and input_source (the job key it was read from).
The output of an issuer are gzipped JSON lines batch files, each one with up to default_filesize items,
written to output_folder. Their default names have the form:
<output slot>_<source>_<YYYYmmddTHHMMSS.ffffff>[_<input slot>].jl.gz
The output folder and this naming standard are the whole contract between an issuer and the stage that comes
after it: the next stage only needs to know where to read, and which prefix selects its share. The standard is
that a name starts with a source (or slot) designation, followed by the timestamp. Some features, like the
persistent deduplication explained below, rely on it, so keep it when you customize the names
(compute_destination_filename()). Notice that an issuer with a single output slot and
separate_output_by_source = False has neither designation by default: give it an output_slot.
Output slots allow the next stage to be parallelized. With parallel_outputs = N each item is routed to slot
hash_mod(id, N), so N downstream instances can each own one slot. As the slot is computed from the item id,
the same item always lands in the same slot, which is what makes possible to deduplicate in parallel:
┌──► 0_mysite.com_20261020T101500.123456.jl.gz ──► stage instance 0
spider jobs ──► consumer ──► hash ──┼──► 1_mysite.com_20261020T101500.234567.jl.gz ──► stage instance 1
└──► 2_mysite.com_20261020T101500.345678.jl.gz ──► stage instance 2
class Consumer(IssuerScriptWithSCJobInput[Article]):
...
parallel_outputs = 3By default the output is also separated by source (one batch per slot and source). Set
separate_output_by_source = False to pack all sources of a slot together.
The stages after the consumer read batch files instead of jobs, with IssuerScriptWithFileSystemInput. Its
input_folder is the output_folder of the previous stage, and its input_slot selects the files of a single
slot (the ones whose name starts with <input_slot>_). Processed input files are removed, or moved to
processed_folder if set. Here the stage receives its slot by command line, so the same script runs as one job
per slot:
from shub_workflow.issuer import IssuerScriptWithFileSystemInput, ItemId, Slot
class Filter(IssuerScriptWithFileSystemInput[Article]):
loop_mode = 120
input_folder = "gs://mybucket/consumer"
output_folder = "gs://mybucket/filtered"
def __init__(self):
super().__init__()
# read and write a single slot, so the partition is conserved downstream
self.input_slot = self.output_slot = Slot(self.args.slot)
def add_argparser_options(self):
super().add_argparser_options()
self.argparser.add_argument("slot", help="Slot to process.")
def build_item_id(self, item: Article) -> ItemId:
return ItemId(item["url"])
def process_item(self, item: Article, input_source):
if "sponsored" in item["tags"]:
self.stats.inc_value("filtered/sponsored")
return
super().process_item(item, input_source)Overriding process_item() and calling super() only for the items that must continue is the usual way to
filter or transform items. Calling super() deduplicates the item and queues it for the output.
As inputs and outputs are just files in a storage, every stage can be developed, deployed, stopped, scaled and restarted independently of the others. We will come back to this property, which is the basis of the architecture described in later chapters.
By default an issuer drops the items whose id it has already seen (dedupe = True), using a bloom filter
(capacity MAX_ITEMS, false positive rate ERRORS_RATE). This dedup covers only the lifetime of the job: when
the issuer restarts, it starts with an empty filter.
For a deduplication that survives restarts, set LOAD_DELIVERED_IDS_DAYS and call load_last_outputs() in
__init__(): on start, the issuer refills its bloom filter with the ids written to the given folders during the
last LOAD_DELIVERED_IDS_DAYS days. Files are dated by the timestamp in their name, so they must follow the
naming standard above.
class Deduplicator(IssuerScriptWithFileSystemInput[Article]):
loop_mode = 300
input_folder = "gs://mybucket/filtered"
output_folder = "gs://mybucket/deduped"
MAX_ITEMS = 1_000_000_000
LOAD_DELIVERED_IDS_DAYS = 365
def __init__(self):
super().__init__()
self.input_slot = self.output_slot = Slot(self.args.slot)
self.load_last_outputs((self.output_folder,), prefix=f"{self.output_slot}_")
...This yields two recurring archetypes. The consumer does a cheap, in-memory preliminary dedup and distributes the items across slots: it is short lived and can be restarted at any moment, and it is the natural place for processing logic that changes often. The deduplicators, one per slot, run continuously and do the massive persistent dedup. Keeping the heavy dedup out of the consumer means that restarting or updating the consumer never touches the authoritative dedup state, and that dedup scales with the number of slots instead of being limited to a single process. See Consumers and deduplicators for more details.
IssuerScriptWithSCJobInput calls the hook post_process_input_items(spider_job, args) once per input job, after
all its items were processed. It is the place for side effects at job level. For example, a consumer can collect
something from every item, and do something with the collected data once per job:
class Consumer(IssuerScriptWithSCJobInput[Article]):
...
def __init__(self):
super().__init__()
self.authors = set()
def process_item(self, item: Article, input_source):
self.authors.add(item["author"])
super().process_item(item, input_source)
def post_process_input_items(self, spider_job, args):
self.save_authors(self.authors) # i.e. send them somewhere for further crawling
self.authors = set()This simple hook plays a central role in the workflow architecture we will describe later: it is where a consumer writes back into the crawl frontier the new seeds discovered by the spiders.
An issuer with loop_mode set keeps looping forever, reading new inputs as they appear. This is the usual mode of
consumers and deduplicators, which follow the pace of the stages before them. Set close_on_no_inputs = True
instead for an issuer that must process the available inputs and finish: a delivery, a reducer, or any stage
that runs periodically.
A continuous issuer that consumes spider jobs flushes a partial batch (one that didn't reach default_filesize)
when the spider of that source is no longer running, after min_wait_time_secs_to_flush_stopped_spiders
seconds. A source is considered still running while one of the scripts listed in source_crawlmanagers (by
default, ("py:crawlmanager.py",)) is running with that spider as argument. Set this attribute to the names of
the crawl managers that actually schedule the consumed spiders.
On close, an issuer always flushes all its pending items.
There is no specific class for delivery. A delivery script is an IssuerScriptWithSCJobInput (or a file input
issuer) configured for the terminal stage of a pipeline. For example, a delivery that writes one file per spider
job of the spider and stops when there is nothing more to deliver:
class Deliver(IssuerScriptWithSCJobInput[Article]):
output_folder = "s3://customer-bucket/articles"
close_on_no_inputs = True # deliver what is available, then stop
flush_on_each_input = True # one output file per input job...
default_filesize = 10_000_000 # ...not split by size
def build_item_id(self, item: Article) -> ItemId:
return ItemId(item["url"])When the delivery reads the output of an upstream deduplicator instead, it is a file input issuer and sets
dedupe = False. The next chapter shows a delivery scheduled by a graph manager, and
Delivery as an issuer
covers the available configuration and the migration of the deprecated BaseDeliverScript.
Next Chapter: Graph Managers
Foundations
Building blocks
Designing workflows at scale
- Managing Hubstorage Crawl Frontiers
- Independent Agents and Role Separation
- Feeding Spiders
- Closing the Loop
- The Post-Crawl Data Chain
- Keeping It Running
- Reference Architectures
Operating workflows