Repository navigation
Post Crawl Data Chain
Previous Chapter: Closing the Loop
- Introduction
- The stages
- Deduplicators
- Filters
- Balancers
- Reducers
- File queues: the folder is the state
- Downloads and delivery
- Where duplicates come from, and who absorbs them
The consumer is the first stage of the post-crawl data chain: the sequence of issuers that takes the raw items extracted by the spiders up to the files the customer receives. The Issuers chapter introduced the building blocks: batch files, slots, file input issuers and deduplication. This chapter describes the stages that usually appear in a chain, the role of each one, and how they cooperate as independent agents.
spider jobs ──► consumer ──► filters ──► deduplicators ──► balancer ──► [download queue] ──► delivery
(seeds back (one per slot) downloader
to frontier) manager + spider
None of the stages is mandatory except the first and the last ones. Each stage reads the output folder of the previous one and writes its own output folder, following the batch naming standard (see Batches, slots and filenames). The consumer partitions the items by hash of their id into slots, and the stages that follow keep that partition, one instance per slot, as long as they need it (typically up to the deduplicators).
| Stage | Purpose | Instances | Mode |
|---|---|---|---|
| Consumer | read the spider jobs, write seeds, light dedup, partition by id | one, or one per source | continuous |
| Filter | drop the items that the customer doesn't want | one per slot | continuous |
| Deduplicator | persistent dedup across all the history | one per slot | continuous |
| Balancer | regroup the items into batches suited for the next stage | one | continuous |
| Reducer | merge several versions of the same entity into one | one | run to completion |
| Downloader | download the media of each item | one manager, many spider jobs | continuous |
| Delivery | write the files the customer receives | one | run to completion |
Placing the filters before the deduplicators is not arbitrary: a deduplicator remembers every id it lets through, so an item filtered out after the deduplicator could never pass again, even when the filters change. Filtering first, and deduplicating what remains, keeps the dedup history consistent with what was actually delivered.
The deduplicators perform the massive, persistent deduplication. There is one instance per slot of the consumer output, each one reading only its slot and writing only its slot, as in the persistent deduplication example. As the same id always lands in the same slot, each instance sees all the occurrences of the ids of its slot, and the instances never need to know about each other. The total capacity grows with the number of slots. As an indication, ten deduplicators with bloom filters of around a billion items each (around 6 ScrapyCloud units per job, because of the filter size) are enough for years of continuous crawling of dozens of sources.
On start, a deduplicator refills its bloom filter with the ids of its own previous output (load_last_outputs()).
When items continue their way to further stages, the folders of those stages must be included too, so that an id
already passed along stays deduplicated even after its file left the deduplicator output folder:
from shub_workflow.issuer import IssuerScriptWithFileSystemInput, Slot
class Deduplicator(IssuerScriptWithFileSystemInput[Article]):
loop_mode = 300
input_folder = "gs://mybucket/filtered"
output_folder = "gs://mybucket/deduped"
MAX_ITEMS = 1_000_000_000
ERRORS_RATE = 1e-9
LOAD_DELIVERED_IDS_DAYS = 1000
DOWNSTREAM_FOLDERS = ("gs://mybucket/downloading",)
def __init__(self):
super().__init__()
self.input_slot = self.output_slot = Slot(self.args.slot)
self.load_last_outputs((self.output_folder,) + self.DOWNSTREAM_FOLDERS, prefix=f"{self.output_slot}_")
...Two consequences of using bloom filters must be accepted: a small rate of new items is wrongly discarded as
duplicates (the false positive rate, ERRORS_RATE), and a deduplicator has a maximal capacity (MAX_ITEMS). When
the number of processed items reaches it, the issuer stops by itself, and it is started again (see
Keeping It Running) with a fresh filter,
refilled from the outputs.
As the deduplicators are long lived and hold a big state in memory, keep them free of logic that changes often. Anything that changes — filters, transformations, normalizations — belongs to cheaper stages, typically the consumer or the filters, which can be stopped and redeployed at any time.
A filter drops the items that the customer doesn't want: by language, by size, by keywords, etc. It overrides
process_item() and calls super() only for the items that pass (see
Chaining stages: reading batch files).
Customers change their filters. When the filters are data rather than code (for example, a file in a bucket), the
filter stage can load them on start, and a change only requires a restart of the filters. Count every rejection
reason in the stats (self.stats.inc_value(f"filtered_out/{reason}")), so the monitors can tell how much each filter
removes; and when an audit trail is needed, write the rejected items into a separate folder.
The deduplicators produce batches partitioned by id hash, with the size that suits deduplication. The next stage may need something else: for example, batches of a single source, with a size adapted to the cost of downloading the items of that source. A balancer reads all the slots and regroups the items:
from shub_workflow.issuer import IssuerScriptWithFileSystemInput, ItemId
BATCH_SIZES = {"mysite.com": 500, "othersite.com": 2500}
class Balancer(IssuerScriptWithFileSystemInput[Article]):
loop_mode = 120
input_folder = "gs://mybucket/deduped"
output_folder = "gs://mybucket/download_queue"
separate_output_by_source = True # one batch file per source
def build_item_id(self, item: Article) -> ItemId:
return ItemId(item["id"])
def get_filesize_from_item(self, item: Article) -> int:
return BATCH_SIZES.get(item["source"], 1000)Its output is named <source>_<timestamp>.jl.gz, so a downloader manager can select the batches of each source by
prefix, as in Feeding spiders with batch files.
A balancer can also distribute the items among several queues, for example one per customer filter, with
get_output_slot_for_item().
Sometimes the same entity is collected many times with different contents: a product page visited on different
days, a collection that grows over time. The deduplicators can't help, because the versions have different ids
(which include, for example, a version number). A reducer keeps a single version of each entity: it reads the
deduplicated batches, keeps the best version of each entity (the latest, the most complete) and writes them. A reducer
usually runs to completion (close_on_no_inputs = True), periodically, before the delivery, and its output folder is
included in the reload of the deduplicators, so that a version that was reduced away is not issued again.
Many stages of a workflow have the same structure: something produces units of work as files, and something else must process each file exactly once. The pattern used everywhere is a file queue: a set of folders where each folder is a state, and moving a file from one folder to another is a state transition.
requests/ ──claim──► processing/ ──done──► completed/
▲ │
└──── reschedule ────┘
- A producer writes new files into
requests/(or the output folder of an issuer). - A consumer of the queue claims a file by moving it into
processing/. Only files inrequests/are listed, so a claimed file is never claimed again, even after a restart. - When the processing is completed, the file is moved into
completed/(or removed). - A file stuck in
processing/because its processing failed is rescheduled by moving it back intorequests/.
Each transition has a single owner, and the state of every unit of work is visible by just listing the folders. No
database, no coordinator: the storage is the state. The same structure, with different names, is the download queue
(download_queue/ → downloading/), a queue of customer requests (requests/ → processing/ → completed/), or
a queue of reports to send (results/ → sent/).
The file name is usually the identifier of the unit of work, and it can be propagated everywhere: in the tags of the jobs that process it, in the output paths. Then everything about a unit of work can be found from its name.
When the deliverable is not only the extracted data but also files — images, videos, documents —, the chain includes a download stage. A downloader manager claims the batches of the download queue and schedules one downloader spider job per batch, passing the batch file path (see Feeding spiders with batch files). The downloader spider downloads each file, uploads it to the delivery storage, and yields one item per input record, with the result of the download: the uploaded path, or the error.
The delivery is then an issuer that reads the finished downloader jobs. With flush_on_each_input = True it writes
one delivery file per downloader job, next to the files that job uploaded (see
Delivery is a configuration).
When a stage fed with batch files fails on many of its records — downloads are the typical case, with timeouts, temporary bans and files that disappeared —, the issuer that consumes the jobs of that stage can retry them. It doesn't retry them because of its position in the chain, but because it is the consumer of the spider stage: it reads every output record, with its result, and it knows the queue the spider stage reads its batches from. So it can write the failed records back into that queue:
- it classifies each error as recoverable (a timeout, a temporary ban) or unrecoverable (the file doesn't exist anymore);
- the records with recoverable errors are written back into the input queue of the spider stage as a new batch (for
example, with a
_r<n>suffix that counts the retries), where its crawl manager will claim them again; - the records with unrecoverable errors continue their way as failed, or are dropped.
In the example above that consumer is the delivery, because it is the issuer that reads the downloader jobs. But the pattern applies to any issuer that consumes a spider stage fed with batch files. It is also optional: it is worth its complexity only when that stage fails often. Many download stages fail rarely enough to just accept, or investigate, their failures.
When it is used, the classification of errors is the part that needs attention over time: an unrecoverable error classified as recoverable makes the same records cycle forever through the queue, wasting resources.
The chain is designed for at-least-once processing (see The principles). It helps to know where duplicates can appear, and which stage absorbs each kind:
| Event | Duplicates produced | Absorbed by |
|---|---|---|
| The same item found by two spider jobs | the item, twice | the consumer (same job lifetime) or the deduplicators |
| The consumer restarts in the middle of a job | the items of that job | the deduplicators |
| A deduplicator restarts | nothing, if its reload includes its own and the downstream outputs | — |
| A file stage restarts in the middle of a file | the items of that file | the deduplicators, if the stage is before them; the stage's own dedup, if after |
| The delivery restarts in the middle of a job | the delivery file of that job |
flush_on_each_input: the job is consumed right after its file is written |
The general rule: the stages before the deduplicators can be careless about duplicates, and the stages after them must either process each input atomically, or reload the ids of their own outputs on start.
Next Chapter: Keeping It Running
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