Plagiarism detection looks like string matching, and for two documents it almost is. The trouble starts the moment you have a corpus. A student submits an essay; you need to know whether it overlaps with any of the billions of web pages, books, and previously-submitted papers you hold. The naive instinct - compare the new document against every document you have - is a dead end before you write a line of code, because the real question is not “are these two documents similar” but “which pairs, out of a corpus of billions, are similar,” and that is an O(n squared) question that no amount of hardware answers at web scale.
So the spine of this design is a single idea: never compare all pairs. We convert each document into a compact fingerprint, use that fingerprint to cheaply bucket documents so that only genuinely-promising pairs ever meet, and run the expensive exact comparison on that tiny candidate set alone. The chain is shingling (turn a document into a set of overlapping token sequences), MinHash (compress that set into a small signature whose collisions approximate Jaccard similarity), and locality-sensitive hashing / LSH (bucket signatures so near-duplicates collide and the all-pairs step collapses into a candidate-generation step). Get that pipeline right and the rest - ingestion, storage, the query API, scaling - is plumbing. Let me build it properly.
Functional Requirements (FR)
In scope:
- Check a document against the corpus. A user submits a document (an essay, an article, a code file treated as text) and the system returns the most similar documents already in the corpus, each with a similarity score and the specific overlapping passages.
- Detect near-duplicates, not just exact copies. The system must catch paraphrase-light plagiarism: reordered paragraphs, a few words changed, inserted filler, different formatting. Byte-identical detection is table stakes; near-duplicate detection is the point.
- Ingest and index at web scale. A pipeline that continuously folds new documents (crawled web pages, newly submitted papers, uploaded books) into the searchable corpus of billions of documents.
- Report overlapping regions. Not just a single percentage, but which spans of the submitted document match which source, so a human can review. A score with no evidence is useless to a teacher or editor.
- Corpus-wide dedup as a batch job. Periodically find all near-duplicate clusters within the corpus itself (the same article republished on 10,000 sites), both to save storage and to collapse sources in reports.
Explicitly out of scope (say this so you own the scope):
- Semantic / meaning-level plagiarism. Detecting that two passages express the same idea in completely different words (deep paraphrase, translation between languages) is a learned-embedding NLP problem. MinHash over shingles catches lexical near-duplication, which is the overwhelming majority of real plagiarism; true semantic matching is a separate design built on sentence embeddings and ANN vector search. I note where it would bolt on but do not build it here.
- The web crawler. Discovering and fetching the web’s documents (URL frontier, politeness, robots.txt) is its own system-design problem. I consume a stream of “here is a document” and focus on fingerprinting and similarity search.
- OCR / document parsing. Extracting clean text from PDFs, images of scanned pages, and Word files is a preprocessing concern. I assume a
to_text(doc) -> stringexists and operate on normalized text. - The grading / UI layer. How a teacher reviews flagged passages is a product surface, not a systems problem.
The one decision that drives everything: this is a near-duplicate set-similarity problem at a scale where all-pairs comparison is forbidden, so the entire design is organized around converting documents to compact signatures and using LSH to generate a small candidate set before any exact work happens. Unlike a keyword search engine built on an inverted index of terms, the unit of similarity is not a shared word but a shared set of shingles, and the difficulty is making that set comparison tractable across billions of documents.
Non-Functional Requirements (NFR)
- Scale: ~10B documents in the corpus, average ~5KB of text each (~1,000 words). Ingestion of ~50M new documents/day at steady state (crawled pages plus submissions), with a massive one-time backfill. On-demand checks of ~20M documents/day from users.
- Latency: an interactive check (user submits a document, wants a report) should return in a few seconds p99 - this is not a sub-100ms lookup, a few seconds of “analyzing” is acceptable and expected. Of that budget, the LSH candidate lookup must be tens of milliseconds; the exact scoring of candidates and passage alignment consume the rest.
- Availability: 99.9% on the check path. A failed check can be retried; nobody is paged at 3am because one plagiarism report was slow.
- Consistency: eventual consistency. A document crawled an hour ago not yet being searchable is fine. There is no read-your-write requirement, no ordering constraint, no transaction. The corpus the check reads can be minutes-to-hours stale.
- Durability: the durable source of truth is the normalized document text and its MinHash signature. The LSH index is a derived artifact - rebuildable from the signatures, so it must be recoverable, not independently durable.
- Accuracy trade-off: detection is probabilistic. MinHash estimates Jaccard similarity; LSH probabilistically buckets near-duplicates. We tune for high recall at a chosen similarity threshold (catch ~99% of true near-duplicates above, say, 0.8 Jaccard) while keeping false candidates low enough that exact verification stays cheap. Recall-vs-work, dialed by the LSH band configuration, is the defining NFR.
Back-of-the-Envelope Estimation (BoE)
Real numbers with the arithmetic, because they dictate the architecture.
Why all-pairs is dead on arrival (the number that defines the problem):
Corpus: 10,000,000,000 (10B) documents.
All-pairs comparisons = N*(N-1)/2 ≈ (10^10)^2 / 2 = 5 * 10^19 pairs.
Even at 10^9 cheap comparisons/sec/machine across 10,000 machines (10^13/sec):
5 * 10^19 / 10^13 = 5 * 10^6 seconds ≈ 58 days of pure compute,
and that is for ONE pass with a trivial comparison. A real text
comparison is orders of magnitude more expensive per pair.
O(n squared) is physically impossible. The whole design exists to replace that 5 * 10^19 with a candidate-generation step that is near-linear in N.
Signature size (what MinHash buys):
A raw shingle set for a 1,000-word doc, using 9-word shingles:
~992 shingles, each a hash => store as 8-byte hashes = ~8KB/doc of shingles.
10B docs * 8KB = 80 TB just to hold shingle sets. And comparing two
8KB sets is far more expensive than comparing two small signatures.
MinHash signature: 128 hashes * 4 bytes = 512 bytes/doc, fixed size,
regardless of document length.
10B docs * 512B = 5.12 TB of signatures. ~16x smaller than shingle sets
and, crucially, a constant-time 128-integer comparison per pair.
Ingestion throughput:
Steady state: 50M new docs/day / 86,400s ≈ ~580 docs/sec to shingle,
MinHash, and insert into the LSH index. Trivial.
Backfill: 10B docs. At 50K docs/sec across a fingerprinting fleet,
10B / 50,000 = 200,000s ≈ 2.3 days of continuous batch processing.
Check (query) throughput:
20M checks/day / 86,400s ≈ ~230 checks/sec average.
Peak (5x) ≈ ~1,200 checks/sec.
Query volume is modest. As with most near-duplicate systems, the enemy is not QPS; it is the cost of the corpus-wide operations - the backfill fingerprinting and the all-pairs problem the LSH index is built to avoid.
LSH index size:
Signature: 128 integers. LSH config: b=32 bands of r=4 rows each (b*r=128).
Each document contributes 32 band-hashes (one bucket key per band).
Per band entry: band_hash (8B) + doc_id (8B) = 16B, * 32 bands = 512B/doc
of index entries, plus bucket overhead. Round to ~1KB/doc indexed.
10B docs * ~1KB = ~10 TB of LSH index across the fleet.
Storage for normalized text (durable source of truth):
10B docs * 5KB text ≈ 50 TB of normalized text (compressed ~2x => ~25 TB),
in a sharded blob/object store, read only for exact verification and
passage alignment, never scanned on the hot path.
The takeaways: all-pairs is 5 * 10^19 comparisons (impossible); MinHash compresses each document to a fixed 512-byte signature (5TB total) that estimates Jaccard with a cheap integer comparison; LSH turns similarity search into bucket lookups over a ~10TB index; query volume is low (~1,200 QPS peak) but the corpus-scale operations are the real cost. The fingerprint pipeline and the LSH index, not throughput, are the design drivers.
High-Level Design (HLD)
The architecture splits into two paths that share only the derived index. An offline ingestion path (normalize -> shingle -> MinHash -> write signature -> insert into LSH buckets) and an online check path (normalize the query -> MinHash it -> probe LSH for candidates -> exact-verify and score candidates -> align passages -> report). The LSH index is the artifact ingestion produces and checks consume.
OFFLINE INGESTION PATH
┌───────────┐ raw docs ┌───────────────┐ text ┌──────────────────┐
│ Crawler / │ ─────────▶ │ Normalizer │ ─────▶ │ Fingerprinter │
│ Submissions│ │ (to_text, │ │ shingles -> MinHash│
│ (upstream) │ │ lowercase, │ │ 128-hash signature │
└───────────┘ │ strip, tokens)│ └────────┬─────────┘
└───────────────┘ │ signature
┌────────────────────────────────▼──────────┐
│ Ingestion Writer │
│ - write doc_id -> normalized text │
│ - write doc_id -> MinHash signature │
│ - emit 32 band-keys -> LSH inserter │
└──────┬──────────────────┬──────────────────┘
│ │
┌───────────▼──────┐ ┌────────▼────────────────┐
│ Document Store │ │ LSH Index (sharded │
│ (text + signature,│ │ by band_hash): │
│ doc_id keyed) │ │ band_key -> [doc_ids] │
└───────────┬──────┘ └────────┬────────────────┘
│ │
================================== │ ================ │ ==================
ONLINE CHECK PATH ▼
┌────────┐ submit ┌────────────────┐ band-keys ┌──────────────────────┐
│ User │ ───────▶ │ Check Service │ ────────▶ │ LSH Lookup Fleet │
│ (doc) │ ◀─────── │ (normalize, │ ◀──────── │ (band-sharded; │
└────────┘ report │ MinHash, │ candidate │ union bucket members)│
│ gather cands) │ doc_ids └──────────────────────┘
└──────┬─────────┘
│ for each candidate:
┌──────▼────────────┐ ┌────────────────────────────┐
│ Document Store │ │ Verifier + Passage Aligner │
│ (fetch sig + text) │──▶│ (exact Jaccard, then align) │
└───────────────────┘ └────────────────────────────┘
Check flow (the hot path):
- The user submits a document to the Check Service. It runs the same Normalizer used at ingest (extract text, lowercase, collapse whitespace, strip punctuation, tokenize) so the query is in the identical representation as the corpus.
- It shingles the normalized text (overlapping k-word sequences) and computes the MinHash signature - 128 min-hash values - exactly as ingestion does.
- It splits the signature into b bands and hashes each band to a bucket key, then probes the LSH Lookup Fleet (band-sharded) with those b band-keys. Each band lookup returns the set of
doc_ids that share that band bucket. The union of all band hits is the candidate set - typically hundreds to low thousands of documents, not billions. - For each candidate, it fetches the candidate’s stored MinHash signature and computes the exact MinHash-estimated Jaccard (fraction of the 128 hashes that agree) to score and rank. This is cheap: 128-integer comparisons per candidate.
- For the top candidates above the threshold, it fetches the full normalized text from the Document Store and runs passage alignment (find the specific overlapping shingle runs / longest common substrings) to produce the highlighted evidence.
- It returns the ranked report: each matched source with a similarity percentage and the overlapping passages.
Ingestion flow (offline):
- The upstream crawler or submission endpoint hands a raw document to the Normalizer, which produces clean tokenized text.
- The Fingerprinter shingles the text and computes the 128-value MinHash signature.
- The Ingestion Writer persists
doc_id -> {normalized_text, signature, metadata}to the Document Store and emits the document’s b band-keys to the LSH Inserter, which appendsdoc_idto each corresponding band bucket. - Near-duplicate collapsing (the same article on many sites) is handled by a periodic batch LSH self-join, described in the deep dive.
The key insight: all the expensive work (normalizing, shingling, MinHashing, index building, corpus-wide dedup) is offline and eventually consistent; the online path only fingerprints one document and probes a pre-built index, then verifies a tiny candidate set. The two paths meet only at the derived LSH index and the document store, so we scale, rebuild, and fail them independently. Nothing on the check path mutates the corpus.
Component Deep Dive
The hard parts, naive-first then evolved: (1) representing a document as a set so “similar” is set-overlap, (2) comparing those sets cheaply with MinHash, (3) the core problem - avoiding all-pairs with LSH, (4) sharding, ingestion, and corpus-wide dedup.
1. Representing a document so “similar” becomes “set overlap”
Naive approach: compare raw strings or compare bags of words. Either diff the two documents character by character, or represent each document as the set of distinct words it contains and compare those word sets.
Where it breaks:
- String/byte diffing finds only near-identical layouts. Insert one sentence at the top and every subsequent character position shifts; edit distance over 5KB documents is O(n*m) per pair and far too slow for a candidate step, and it is brittle to reordering.
- Bag-of-words loses all order. “The dog bit the man” and “The man bit the dog” have identical word sets. Two documents on the same topic share most common words and look falsely similar; plagiarism of phrasing is invisible because single words carry no local structure. Recall and precision both collapse.
The answer: k-shingling (k-grams of words). Represent a document as the set of all overlapping sequences of k consecutive tokens. For k=9, the document “a quick brown fox jumps over the lazy dog today” yields shingles [a quick brown fox jumps over the lazy dog], [quick brown fox jumps over the lazy dog today], and so on. Each shingle is hashed to an integer, so a document becomes a set of integers.
normalize: "The Dog, bit the man!" -> tokens [the, dog, bit, the, man]
shingle(k): with k=3 -> { (the,dog,bit), (dog,bit,the), (bit,the,man) }
hash each: { 0x9fa1..., 0x3b02..., 0xc7d4... } # a set of integers
Now document similarity is set similarity, measured by Jaccard: J(A,B) = |A ∩ B| / |A ∪ B|. Two documents sharing long runs of identical phrasing share many shingles and have high Jaccard; two documents merely on the same topic share few shingles. Shingling captures local word order (plagiarism’s fingerprint) while being robust to reordering whole paragraphs (the unshifted paragraphs still share their shingles) and to small edits (a changed word only destroys the k shingles overlapping it).
Choosing k matters. Too small (k=1 or 2) and common phrases collide everywhere - “of the”, “in a” - inflating similarity between unrelated documents. Too large and a single edit kills too many shingles, hurting recall. k=5 to 9 words is the usual sweet spot for prose; shorter for code, longer for legal boilerplate. This single parameter trades precision (large k) against robustness to edits (small k).
Shingling is the foundation: it is the representation that makes “similar phrasing” a measurable, order-aware set-overlap quantity.
2. Comparing shingle sets cheaply with MinHash
We have each document as a set of shingle-hashes and we want Jaccard. But the sets are big and comparing them directly is expensive.
Naive approach: store the full shingle set per document and compute exact Jaccard on demand. For a candidate pair, intersect the two integer sets.
Where it breaks:
- Storage. ~8KB of shingle hashes per document times 10B documents is ~80TB, and the sets are variable-length.
- Comparison cost. Exact Jaccard is O(|A| + |B|) per pair - ~2,000 integer operations for two 1,000-word docs. For the exact-verify step over a handful of candidates that is fine, but you cannot build an index over variable-length sets this way, and you certainly cannot compare sets across billions of documents.
The answer: MinHash - a fixed-size signature whose hash-collision probability equals Jaccard. Pick a hash function h. For a set A, define h_min(A) = min over x in A of h(x). The beautiful property: for two sets A and B, the probability that their minima are equal is exactly their Jaccard similarity:
P[ min(h(A)) == min(h(B)) ] = |A ∩ B| / |A ∪ B| = J(A, B)
Why: the element producing the global minimum hash over A ∪ B is equally likely to be any element of the union; the minima of A and B agree precisely when that element is in the intersection. So one min-hash is a single coin flip that lands “equal” with probability J. Use 128 independent hash functions (or one hash with 128 random permutations) and you get a 128-value signature. The fraction of the 128 positions where two signatures agree is an unbiased estimator of Jaccard, with standard error ~1/sqrt(128) ≈ 0.088.
signature(A) = [ min(h_1(x) for x in A), min(h_2(x) for x in A), ...,
min(h_128(x) for x in A) ] # 128 integers, fixed size
estimate J(A,B) ≈ (count of positions i where sig_A[i] == sig_B[i]) / 128
This is the compression that makes everything downstream possible: every document, whatever its length, becomes a fixed 512-byte signature (128 * 4 bytes), and estimating Jaccard between any two is a constant-time 128-integer comparison instead of intersecting variable-length sets. 80TB of shingle sets collapses to 5TB of signatures, and the per-pair comparison cost becomes constant and tiny.
More hashes = more accuracy. 128 gives ~0.09 error; 256 halves it at double the storage. The signature length is the accuracy-vs-storage dial. In practice 128 to 256 is plenty because the exact-verification step re-checks the survivors anyway.
MinHash alone, though, has not solved the scaling problem: estimating J between the query and all 10B signatures is still 10B comparisons per check. We need to avoid even looking at most signatures. That is LSH.
3. Avoiding all-pairs with LSH (the core problem)
Given the query signature, find corpus documents with high Jaccard without comparing against all 10B signatures. This is where the design lives or dies.
Naive approach: linear scan of signatures. Compare the query’s 128-value signature to every stored signature, keep those above threshold.
Where it breaks:
- Per-check cost. 10B signature comparisons * 128 ops = 1.28 * 10^12 ops per check. Even sharded, every check lighting up the whole fleet cannot sustain even modest QPS. And the corpus-wide self-join (dedup) is the full 5 * 10^19 all-pairs nightmare.
- It defeats the purpose. We compressed to signatures precisely so we would not scan them all; a linear scan throws that away.
The answer: Locality-Sensitive Hashing by banding the signature. Split each 128-value signature into b bands of r rows each (b * r = 128), for example b=32 bands of r=4 rows. Hash each band (its r values) to a bucket. Two documents become candidates if they are identical in at least one entire band. At ingest, every document is inserted into b buckets (one per band); at query, the candidates are the union of the query’s b bucket memberships.
Build (per document):
sig = [v0, v1, ..., v127]
for band in 0..31:
band_slice = sig[band*4 : band*4+4] # r=4 values
key = hash(band, band_slice) # include band index to avoid cross-band collisions
lsh_bucket[key].append(doc_id)
Query:
for band in 0..31:
key = hash(band, query_sig[band*4 : band*4+4])
candidates |= lsh_bucket[key] # union across bands
# candidates is typically hundreds, not billions
verify each candidate with exact 128-value Jaccard, keep > threshold
Why this works - the S-curve. For a pair with true Jaccard s, the probability they agree on all r rows of one band is s^r; the probability they do NOT share any of the b bands is (1 - s^r)^b; so the probability they become a candidate (share at least one band) is:
P_candidate(s) = 1 - (1 - s^r)^b
This is an S-shaped curve with a sharp threshold near s ≈ (1/b)^(1/r). With b=32, r=4 the threshold sits around s ≈ 0.42, but the curve is steep: a pair at Jaccard 0.8 has P ≈ 1 - (1 - 0.8^4)^32 ≈ 1 - (1 - 0.41)^32 ≈ 0.9999 (essentially always a candidate), while a pair at 0.3 has P ≈ 1 - (1 - 0.0081)^32 ≈ 0.23 (usually filtered out). b and r are the dials: more rows per band (larger r) raises the threshold and cuts false candidates; more bands (larger b) raises recall at the cost of more candidates to verify. You pick b and r to place the steep part of the S-curve exactly at the similarity you care about (say 0.8), so near-duplicates almost always collide and unrelated documents almost never do.
| b=32, r=4
P(candidate) 1.0 ┤ ______________
│ __/
│ _/
0.5 ┤ _/ <- steep transition ~0.4-0.5
│ __/
│ _____/
0.0 ┤───────/
└────┬────┬────┬────┬────┬────┬────┬──── true Jaccard s
0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8
This is the whole game. LSH turns “compare against 10B documents” into “look in b buckets and union a few hundred candidates,” replacing the O(n squared) all-pairs step with near-linear indexing plus a tiny exact-verification set. The corpus-wide dedup self-join becomes “for each bucket, the documents inside it are candidate near-duplicates of each other” - again near-linear in corpus size instead of quadratic.
Verification is mandatory. LSH and MinHash are both approximate, so after the union we always re-estimate exact (128-value) Jaccard on each candidate and drop those below threshold. This removes the LSH false positives cheaply, because there are only a few hundred of them. Candidates that clear verification then go to passage alignment for human-readable evidence.
| Stage | What it does | Cost per document | Output |
|---|---|---|---|
| Shingling | k-grams -> set of hashes | O(doc length) | ~1,000 integers |
| MinHash | 128 min-hashes | O(128 * shingles) | 512-byte signature |
| LSH insert/probe | b band buckets | O(b) = O(32) | band-key list / candidate union |
| Verify | exact Jaccard on candidates | O(128 * candidates) | scored matches |
| Align | find overlapping passages | O(doc length) on survivors | highlighted evidence |
Each stage is cheap and the expensive one (comparison) only ever runs on the handful of candidates LSH surfaces.
4. Sharding, ingestion, and corpus-wide dedup
One machine cannot hold a 10TB LSH index or serve the fingerprinting fleet, and the index must absorb ~580 new docs/sec while the corpus-dedup self-join must run without an all-pairs blowup.
Naive approach: one LSH index on one big node, rebuilt nightly. Keep all band buckets in one store; rebuild from scratch each night to fold in the day’s documents.
Where it breaks:
- It does not fit or scale. 10TB of buckets and the full corpus’s band-keys will not sit on one node, and a single node cannot ingest the backfill in reasonable time.
- Nightly rebuild is wasteful and stale. Re-inserting 10B documents nightly is pointless churn, and new documents stay invisible for up to a day.
- Hot buckets. Massively-duplicated content (a viral article, a licensing boilerplate) lands tens of thousands of doc_ids in one band bucket, so probing it returns a huge candidate list and the verify step chokes.
The answer: shard the LSH index by band-key, make inserts incremental and append-only, and run dedup as a batched LSH self-join - never all-pairs.
- Shard by band-key (band-partitioned). Each band bucket lives on the shard owning
hash(band_key) mod S. A document’s b band-keys naturally spread across shards, so inserting one document touches b shards with one tiny append each, and a query probes b shards (one bucket lookup each) and unions the results. This spreads both storage and load evenly, and unlike the vector-search world there is no scatter to every shard - each band-key maps to exactly one shard, so a query touches at most b shards regardless of fleet size. - Append-only, incremental inserts. A bucket is just
band_key -> [doc_id, ...]. New documents append; nothing is rebuilt. New content is searchable within seconds of ingestion. The index is a derived KV store, so a lost shard is rebuilt from the durable signatures, not restored from an index backup. - Replicate each shard R times for availability and read throughput; a query routes each band lookup to one replica.
- Hot-bucket handling. Cap bucket fan-out: if a band bucket exceeds a size limit (hyper-duplicated content), either sample it, split it with a secondary hash, or short-circuit - a document matching a 50,000-member bucket is clearly boilerplate and can be flagged as “common/templated content” rather than expanding into 50,000 candidates. Monitor bucket-size distribution and treat the long tail specially.
Shard layout (band-partitioned):
shard_j owns band_keys where hash(band_key) mod S == j
insert(doc): for each of b band_keys -> append doc_id on its owning shard
query(doc) : for each of b band_keys -> lookup bucket on its owning shard,
union memberships -> candidate set
hot bucket : if |bucket| > CAP -> sample / split / flag-as-boilerplate
Corpus-wide dedup without all-pairs. To find every near-duplicate cluster in the corpus (for storage savings and source-collapsing), do NOT compare all pairs. Run a batch MapReduce/Spark LSH self-join: map each document to its b band-keys; group by band-key; within each bucket, every pair is a candidate near-duplicate; emit those candidate pairs; then verify each candidate pair’s exact Jaccard; then union-find the surviving pairs into clusters. The expensive step only ever examines pairs that already collided in a bucket, so the work is proportional to corpus size plus total bucket-internal pairs (bounded by capping hot buckets), not N squared.
Batch self-join (MapReduce):
map: doc -> emit (band_key, doc_id) for each of b bands
reduce: for each band_key bucket -> emit candidate pairs (capped per bucket)
verify: exact Jaccard on candidate pairs, keep > threshold
cluster: union-find over surviving pairs -> near-duplicate clusters
The lesson: band-partition the LSH index so each query touches only b shards (never the whole fleet), make inserts append-only for near-real-time ingestion, cap hot buckets so hyper-duplication cannot explode the candidate set, and run corpus dedup as a bucketed self-join that replaces the N-squared all-pairs step with work proportional to corpus size.
API Design & Data Schema
The check path is a submit-and-report call; ingestion is internal.
Check API (client-facing)
POST /api/v1/check
body: multipart document file OR { "text": "..." }
query params: ?threshold=0.8&limit=20
-> 202 { "check_id": "chk_7a2", "status": "processing" } # async for large docs
GET /api/v1/check/{check_id}
-> 200 {
"check_id": "chk_7a2",
"status": "complete",
"overall_similarity": 0.34, # fraction of submitted doc matched
"matches": [
{ "doc_id": "doc_91", "source_url": "https://site/...",
"jaccard": 0.86,
"matched_passages": [
{ "query_span": [120, 340], "source_span": [50, 270],
"text": "the overlapping sentence run ..." } ] },
{ "doc_id": "doc_12", "source_url": "...", "jaccard": 0.81,
"matched_passages": [ ... ] }
]
}
GET /api/v1/document/{doc_id}
-> metadata + source for a matched document (drill-down)
The check is async: submit returns a check_id immediately, the client polls (or gets a webhook) for the report, because fingerprinting + candidate verification + passage alignment on a long document takes seconds. For short pastes it can return synchronously.
Internal ingestion API
POST /internal/ingest
body: { "doc_id": "doc_91", "source_url": "https://...", "raw": "<bytes>" }
-> { "doc_id": "doc_91", "action": "indexed" }
// Normalizer -> Fingerprinter -> Writer -> LSH inserter
Data stores - the right tool per plane
1. Document Store (durable source of truth) - sharded NoSQL KV, by doc_id. Holds the normalized text and the MinHash signature. Read only during verification and passage alignment, never scanned on the hot path. Read-mostly, no cross-key transactions, shards cleanly on doc_id - NoSQL/object store is the right call; relational buys nothing.
Table: documents (partition key = doc_id)
doc_id STRING PARTITION KEY
source_url STRING
normalized_text TEXT -- compressed; for alignment/evidence
signature BINARY(512) -- 128 * 4-byte MinHash values
shingle_k SMALLINT -- the k used (for reproducibility)
lang STRING
ingest_ts TIMESTAMP
Query: fetch signature + text for a candidate = one point read by doc_id.
Index: PK on doc_id. (No secondary indexes needed on the hot path.)
2. LSH Index (derived) - sharded KV, by band-key. The band buckets. This is what checks actually probe. Not independently durable - rebuilt from signatures.
Store: lsh_buckets (partition = hash(band_key) mod S)
band_key BIGINT PARTITION KEY -- hash(band_index, band_slice)
doc_ids LIST<STRING> -- members of this bucket (append-only)
Query: candidate gen = b point reads (one per band), union the lists.
Insert: b appends (one per band). Hot buckets capped / split.
3. Signature store. In practice the signature lives both in the Document Store row (durable) and can be cached hot in an in-memory tier keyed by doc_id, so the verify step’s per-candidate signature fetch is a fast lookup rather than a full-row read.
4. Check-results store - short-lived KV / Redis. check_id -> report, with a TTL, so the async poll is cheap and repeated polls do not re-run the check.
5. Dedup-cluster store (batch output). cluster_id -> [doc_ids] plus a doc_id -> canonical_doc_id map produced by the batch self-join, used to collapse duplicate sources in reports.
Why NoSQL/KV throughout and no relational store on the hot path: every hot-path operation is either a band-bucket lookup (KV point read), a signature/text fetch by doc_id (KV point read), or an in-memory Jaccard comparison. There is no transaction, no join across users, no ordering constraint, no “assign exactly one.” The corpus is enormous, read-mostly, and shards trivially by doc_id (document store) or band_key (index). Relational’s strengths (ACID, joins, foreign keys) are exactly what this system never needs, and its costs (single-writer bottlenecks, hard horizontal scaling) are exactly what would kill it. So: sharded KV stores, band-partitioned LSH buckets, eventual consistency everywhere, because a document indexed minutes late is fine.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each:
1. All-pairs comparison (breaks before you start). Finding similar pairs by comparing every document to every other is 5 * 10^19 comparisons - impossible. Fix: MinHash + LSH. Compress each document to a fixed signature and bucket by bands so only documents sharing a band ever get compared. The O(n squared) step becomes near-linear candidate generation plus a tiny exact-verify set. This is the single optimization that makes the system exist.
2. Signature scan per check. Even with signatures, comparing the query to all 10B of them is ~10^12 ops/check. Fix: LSH banding so a check only probes b buckets and verifies the few hundred documents they contain, never the full corpus.
3. The index does not fit on one machine. ~10TB of buckets plus billions of inserts.
Fix: band-partition the LSH index across S shards (by hash(band_key)); each insert touches b shards with one append, each query touches b shards with one lookup. No scatter to the whole fleet, because every band-key lives on exactly one shard.
4. Hot buckets from hyper-duplicated content. A viral article or boilerplate lands tens of thousands of doc_ids in one band bucket, exploding the candidate set. Fix: cap bucket size - sample, secondary-split, or flag the input as “common/templated content” instead of expanding into 50,000 candidates. Monitor the bucket-size distribution and treat the tail specially.
5. Ingesting without a rebuild. Re-inserting 10B documents nightly is wasteful and leaves new content stale for a day. Fix: append-only incremental inserts. A new document’s b band-keys append to their buckets in seconds; the index is never rebuilt, only derived from signatures if a shard is lost. New content is searchable near-real-time.
6. Fingerprinting throughput (the ingestion cost). Backfilling 10B documents (normalize + shingle + MinHash) is a ~2.3-day batch; MinHash over ~1,000 shingles * 128 hashes is the hot inner loop. Fix: batch, parallelize, and speed up MinHash - use a single hash with 128 random permutations (or one-permutation MinHash with densification) instead of 128 independent hashes, SIMD the min-reduction, and run the fingerprinter as a throttled Spark/MapReduce job decoupled from the check path. Steady-state ~580/sec is trivial.
7. Corpus-wide dedup blowing up. A self-join over 10B documents, done naively, is all-pairs again. Fix: bucketed LSH self-join in MapReduce - group by band-key, emit only intra-bucket candidate pairs (capped), verify, union-find into clusters. Work is proportional to corpus size plus bounded bucket-internal pairs, not N squared.
8. Repeated / near-identical submissions. The same document resubmitted, or minor edits of it. Fix: cache checks keyed by the query signature (or a strong hash of normalized text); identical resubmissions return the cached report and skip fingerprinting and lookup entirely.
9. Passage alignment cost on long documents. Producing highlighted evidence (longest common substrings / overlapping shingle runs) is O(doc length) per survivor. Fix: run alignment only on the handful of candidates that clear verification, not on all candidates; use the already-computed shingle positions to localize matches, and cap evidence to the top passages per source.
10. Single points of failure and durability. Fix: the LSH index is derived from the durable signatures, so a lost shard/replica is re-derived, not restored. Document Store and signatures are replicated and multi-region. The Check and Fingerprint services are stateless behind load balancers. No single node whose loss stops checking; at worst a shard replica rebuilds while others serve.
Wrap-Up
The trade-offs that define this design:
- Candidate generation over exact comparison, deliberately. All-pairs is physically impossible at 10B documents, so we accept a probabilistic candidate step (MinHash estimates Jaccard, LSH buckets probabilistically) and clean it up with cheap exact verification on the survivors. Recall-vs-work, dialed by the LSH band configuration, is the defining trade of the whole system.
- Shingles over words or bytes. k-word shingles capture local phrasing (plagiarism’s fingerprint) while surviving paragraph reordering and small edits - the representation that makes “similar wording” a measurable set-overlap.
- Fixed signatures over raw sets. MinHash collapses variable-length 8KB shingle sets into fixed 512-byte signatures whose agreement estimates Jaccard with a constant-time integer comparison - 16x less storage and an indexable, comparable fingerprint.
- Band-partitioned LSH over a scatter-to-all index. Each band-key lives on one shard, so a check touches only b shards and unions a few hundred candidates, not the whole corpus or the whole fleet - and the same banding turns corpus dedup into a near-linear self-join instead of N squared.
- Offline heavy, online light. All the expensive, batchy work (normalize, shingle, MinHash, index-build, dedup) is offline and eventually consistent; the online path only fingerprints one document and probes a derived index, then verifies a tiny set. The two meet only at the index and the document store, so they scale and fail independently.
One-line summary: a near-duplicate detection system where each document is normalized into k-word shingles, compressed into a fixed MinHash signature that approximates Jaccard, and bucketed by LSH bands in a band-partitioned index so every check unions a few hundred candidates and exactly verifies them in a few seconds - replacing the impossible O(n squared) all-pairs comparison with near-linear candidate generation, approximate, eventually consistent, and derived-not-durable throughout.
Comments