Streaming Design for Cleaning and Near-Duplicate Removal of Web Crawl Text
System DesignModel answerLast updated
Design a horizontally scalable streaming system that extracts text from 100TB of crawled HTML, filters it, removes near-duplicates and reports live metrics, all in one pass.
Your team is preparing pretraining data for a large language model. The raw material is 100 TB of crawled HTML pages. Design a streaming system that turns it into a clean, filtered, near-duplicate-free English text corpus. It must do so in one pass, without writing intermediate copies of the pages back to storage.
What the system must do
- Text extraction: Turn each HTML page into normalized plain text, removing navigation, ads, scripts, styles and other boilerplate.
- Quality gates: Reject documents that are too short, contain too many non-alphanumeric characters, or are not identified as English by a language classifier.
- Near-duplicate removal: Detect and drop documents that are very similar to ones already seen in the stream, without a lookup against one giant global table.
- Live metrics: Report throughput, per-filter rejection rates and the distribution of document lengths as the job runs.
Constraints
- Horizontal scale: The design must keep working at 100 TB and beyond by adding machines, with no single choke point.
- Memory: Each worker has 32 GB of RAM, so the full dedup index cannot live in memory on one node.
- Failure handling: If a node dies, the job must resume from recent progress rather than restart from scratch, and every surviving document must appear in the output exactly once.
What to deliver
Describe the architecture and name the technologies you would use for ingestion, processing and storage. Explain in detail how fuzzy deduplication works without a global full-table lookup, and how you would track metrics in real time. Back your choices with rough capacity numbers and discuss trade-offs.
Hints
Hint 1
Start with arithmetic: estimate the document count, the text volume after HTML removal, and the cores needed to finish in a fixed window such as 24 hours.
Hint 2
Do not push raw HTML through a message broker. Send small pointers (file and byte range) through the queue and let workers read bytes from object storage.
Hint 3
MinHash signatures split into LSH bands give you keys that can be hash-partitioned. Each state-holding worker owns a slice of the index, so no node needs the whole table.
Hint 4
Think about delivery guarantees explicitly: checkpointed state plus a transactional (two-phase commit) sink gives exactly-once output after a crash.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size the problem
- Input: 100 TB of HTML, most likely stored as WARC archives on object storage such as S3 or GCS.
- Documents: at roughly 50 KB per page, about 2 billion pages.
- Text volume: extraction shrinks data about 10x, so around 10 TB of text. After quality filters and dedup, perhaps 20-40% survives: 2-4 TB of final corpus.
- Throughput target (24 h run): 100 TB / 86,400 s is about 1.2 GB/s, or about 23k documents/s.
- Compute: extraction dominates at roughly 30-50 documents/s per core, so plan for about 500-800 cores, i.e. 30-50 workers with 16-32 cores and 32 GB RAM.
- Semantics to confirm: "near-duplicate" means roughly Jaccard similarity of 0.8 or more on word shingles; dedup spans the whole stream; output must be exactly-once.
2. Architecture
Object storage (WARC) -> Split planner -> Kafka [work items: path + byte range]
-> Stage A (stateless): fetch, extract, normalize, filter, langID, fingerprints
-> keyBy(band bucket) -> Stage B (stateful LSH index, RocksDB)
-> keyBy(doc_id) -> Stage C (verdict join) -> Iceberg/Parquet sink
All stages -> metrics endpoint -> Prometheus -> Grafana / alerts
Sampled rejects -> audit bucket
Ingestion. A planner lists the archives and publishes small work items (path, offset, length) to Kafka. Workers stream the bytes straight from object storage. Pushing 100 TB through the broker would multiply storage and network cost through replication and retention for no benefit. Only the much smaller extracted text travels between later stages.
Processing. Apache Flink: keyed state on RocksDB (spills to local SSD, not RAM), asynchronous checkpoints to object storage, and two-phase-commit sinks for exactly-once output. Spark Structured Streaming is a reasonable alternative; Ray Data suits Python-heavy teams but has weaker stateful-dedup support.
Storage. Parquet in Apache Iceberg tables on object storage, partitioned by crawl and shard. Iceberg's atomic commits pair naturally with the 2PC sink and allow snapshot reads and audits.
3. Stage A: extraction and filtering (stateless)
Order operations from cheap to expensive so the costly work runs on fewer documents.
- Parse the WARC record; keep only successful HTML responses.
- Extract the main content with a density-based extractor (trafilatura or jusText), which drops navigation, ads, scripts and styles.
- Normalize: Unicode NFKC, strip control characters, collapse whitespace.
- Heuristic gates: at least ~50 words, alphanumeric ratio at least ~0.7, mean word length between ~3 and 10, limited share of lines ending in ellipses.
- Language ID with fastText (
lid.176, about 1 ms per document, tiny model loaded once per worker). Keep English above a confidence threshold such as 0.65. - Compute an exact content hash and a 128-permutation MinHash over word 5-gram shingles.
Every rejection increments a counter labeled with its reason.
4. Fuzzy dedup without a global lookup
MinHash + LSH. Split the 128-value signature into b = 16 bands of r = 8 rows. Two documents become candidates if any band matches exactly. The approximate similarity threshold is (1/b)^(1/r) = (1/16)^(1/8), about 0.71. To make matching stricter, change the split, for example b = 9, r = 13 gives about 0.84. Choose it from the target Jaccard threshold and the tolerable false-positive and false-negative rate.
Sharding the index. Band buckets partition naturally:
- Stage A emits 16 records per document:
(band_id, hash(band values)) -> doc_id. keyByon that bucket key routes every record with the same key to exactly one Stage B task.- That task owns its slice of the index. No node holds the whole table and no cross-node lookups are needed.
State sizing.
- RocksDB keyed state: 2B docs x 16 bands x about 12 bytes is about 400 GB cluster-wide, or about 8 GB per node across 50 nodes, on local SSD with a hot cache in RAM.
- Partitioned Bloom or Cuckoo filters: around 32B entries at 1% false-positive rate needs about 10 bits each, roughly 40 GB total and under 1 GB per node. Cost: a false positive drops a unique document, which is usually acceptable for pretraining data.
Verdict join. Stage B emits (doc_id, band_id, seen_before). Stage C, keyed by doc_id, collects the 16 verdicts (with a timeout) and drops the document if any band was already seen. To avoid shuffling text 16 times, hold the text in keyed state in Stage C, or keep it in a side topic and join by doc_id.
Exact dedup first. Run the same keyed pattern on the exact content hash before LSH. It is cheap and often removes 30% or more of duplicates, shrinking LSH load.
Order sensitivity. In a stream, first-seen wins. If you need the best-quality copy instead, you need a second pass or a bounded window. State this trade-off explicitly. Also store the MinHash with each output row so later cross-crawl dedup can reuse it.
5. Fault tolerance and exactly-once
- Flink takes asynchronous, incremental checkpoints every few minutes to object storage. These cover Kafka offsets and RocksDB state together, so on failure the job restores the last checkpoint and replays only the work since.
- The Iceberg sink uses two-phase commit: files are written during the checkpoint and committed atomically when it completes, so replayed work does not create duplicate output.
- Work items are idempotent (a byte range of an immutable file), so reprocessing is safe.
- Use a dead-letter path for malformed records so one bad archive does not stall the pipeline.
6. Real-time metrics
- Each task exposes counters and histograms: documents in and out, bytes in, rejects labeled by reason (
too_short,low_alnum,non_english,exact_dup,fuzzy_dup), and a histogram of word counts with fixed log-scale buckets. - Prometheus scrapes them; Grafana shows throughput, per-stage rejection rate and length distribution. Histograms are mergeable across workers, which is why fixed buckets beat per-node percentiles.
- Alerts: throughput drop, sudden change in a rejection rate (often a sign of a broken extractor or a bad shard), checkpoint duration growth, consumer lag.
- Keep a small sample of rejected documents in an audit bucket to validate thresholds.
7. Trade-offs and common mistakes
- Mistake: sending raw HTML through Kafka. Send pointers instead.
- Mistake: a single dedup database or one big in-memory set. Partition by band key.
- Mistake: running language ID or MinHash before cheap filters, wasting CPU.
- Mistake: ignoring delivery semantics. Without checkpoints and a transactional sink, retries create duplicates or lose data.
- Trade-off: Bloom filters save memory but lose a small fraction of unique documents; RocksDB is exact but needs SSDs and more state to checkpoint.
- Trade-off: looser LSH thresholds remove more near-duplicates but risk discarding legitimately similar pages (templates, boilerplate-heavy sites); validate on a labeled sample.
- Scaling: the design scales by adding partitions and workers. The main hot-spot risk is skewed band keys (very common content); mitigate by exact-dedup first and by capping or salting extremely hot keys.