Exact Top-1,000 Terms Across a Petabyte of Text Files
System DesignModel answerLast updated
Design a distributed batch pipeline that exactly counts term occurrences across petabytes of immutable text and returns the 1,000 most common, handling skew, split edges and retries.
Exact Top-K Term Counts at Petabyte Scale
You have a very large corpus of plain-text files, around a petabyte in total, sitting in an immutable object store such as S3. Individual files can be arbitrarily large. Design a distributed batch system that produces the 1,000 most frequent words across the whole corpus, together with their counts.
Requirements
Functional
- Accept files of any size.
- Counts must be exact. Probabilistic sketches (Count-Min, etc.) are not allowed.
- Processing must be idempotent, so that worker crashes and retries do not change the result.
Non-functional
- The output must be deterministic, independent of the order in which parallel tasks finish.
- The design must scale horizontally across a cluster.
- Extremely common words (for example "the") must not overload any single aggregation task.
What to cover
- Architecture: the stages from reading input through tokenizing, aggregating and producing the final ranking.
- Splitting: how you cut large files into pieces without losing or double-counting words that straddle a cut.
- Data model: what workers exchange with each other, with the coordinator and with storage.
- Failure handling: what happens when a worker dies in the middle of a file segment.
State your assumptions about scale and the definition of a "word" before designing.
Hints
Hint 1
Frame it as a map, shuffle, reduce job. Think about what each map task can pre-aggregate locally before sending anything over the network.
Hint 2
To avoid splitting words at chunk edges, define an ownership rule based on where a word begins, so every word belongs to exactly one chunk.
Hint 3
Make every task a pure function of immutable input, write output to an attempt-specific location, and publish it with a first-writer-wins commit.
Hint 4
For top-K, ask whether a word's total can ever be spread over several reducers. If each word is routed to exactly one reducer, local top-K lists are enough to build the global top-K.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Key ideas
This is a MapReduce-style problem. Three things decide whether an answer is good:
- Boundary correctness: a word cut by a split edge is counted exactly once.
- Skew control: very frequent words do not break a reducer, and exactness is kept.
- Safe commits: retries and speculative duplicates never double-count.
1. Scope and numbers
- Input of about 1 PB at roughly 6 bytes per token gives on the order of 10^14 to 10^15 tokens.
- Distinct words, including typos, URLs and IDs, might reach 10^8 to 10^9. The full count table can be tens of GB, so aggregation must be distributed as well.
- With 256 MB splits there are about 4 million map tasks.
- A cluster of about 2,000 nodes with 16 cores each, at tens of MB/s per core, could finish in minutes in theory. Object-store request and bandwidth limits make an hour a realistic estimate. This is a batch job, not a low-latency service.
Agree on the tokenizer up front: UTF-8 decode, Unicode normalization, lowercase, split on non-alphanumerics. Version it, since determinism requires every worker to use the same one. Also ask about compression: plain gzip is not splittable, so one file becomes one task. Prefer splittable or seekable formats.
2. Architecture
- Planner lists the input prefix and writes split descriptors
(file, start, end)into a durable task table. - Coordinator leases tasks to workers, watches heartbeats and records which attempt committed. State is durable, so a restart can resume.
- Map: read the split with range GETs, tokenize, and count in an in-memory hash map (this is the combiner). If memory fills, spill sorted runs to disk. Finally merge and write
Rpartitions byhash(word) mod R, each sorted by word. - Shuffle: reducer
rfetches partitionrfrom every committed map output. Prefer a remote shuffle service or object storage so finished map output survives node loss. - Reduce: k-way merge the sorted runs, sum counts per word, write full counts, and keep a size-1000 min-heap of the local best.
- Final merge: combine the
R × 1000candidates into the global top 1,000.
The final merge is correct because each word is routed to exactly one reducer, so its count there is already global. Any word in the global top 1,000 must therefore be in the top 1,000 of its own reducer.
3. Split boundaries
Use an ownership rule: a split owns every word whose first byte lies in [start, end).
- If
start > 0, look at bytestart-1. If it is not a delimiter, the first word began in the previous split, so skip to the next delimiter. - Continue reading slightly past
endto finish the last word that started inside the split. - For UTF-8, never start decoding at a continuation byte (
10xxxxxx); advance to a character boundary, and test delimiters on code points. - Cap token length (say 256 bytes) and put longer runs in an overflow bucket, so the over-read is bounded even for a multi-GB run with no delimiter.
Each word begins in exactly one split, so it is counted once, and no index file is required.
4. Data model
Task table: task_id, job_id, type (MAP|REDUCE), input, state (PENDING|RUNNING|COMMITTED), attempt, lease_owner, lease_expiry, committed_attempt, output_uri. Back it with a transactional store such as Postgres, DynamoDB or etcd.
Map output: shuffle/{job}/{map_task}/{attempt}/part-{r}, holding sorted, compressed (word, count:uint64) records plus a footer with record count and checksum.
Reduce output: out/{job}/counts/part-{r} and out/{job}/topk/part-{r}.
Worker RPCs: Lease(), Heartbeat(task, attempt, progress), and Commit(task, attempt, uri, checksum), which is a conditional write that succeeds only if the task is not yet committed.
Combining keeps shuffle volume small: a 256 MB split has at most a few million distinct words, so shuffle traffic is a small fraction of the input.
5. Hot keys
- Combiner first. Even if "the" occurs 10^13 times, after map-side combining it reaches its reducer as roughly one record per map task. The sorted merge handles it with O(1) memory per key.
- Many partitions. Choose
Rfar above the number of reducer slots (e.g. 10,000), so one heavy partition is a small slice of total work and the scheduler can balance. - Salting if still needed. Sample to find heavy hitters, emit
(word#i, count)withi = map_task mod S, reduce, then run a tiny second pass that strips the salt. Addition is associative, so the result stays exact. - Tree aggregation across racks is another option, rarely needed with combiners.
6. Fault tolerance and idempotency
- Pure tasks: immutable input, versioned tokenizer and pure functions mean any task can be rerun safely.
- Worker crash mid-split: heartbeats stop, the lease expires (e.g. 30 s), and the coordinator reissues the task with
attempt+1. The dead attempt's partial files live under its own path, are never committed, and are garbage-collected later. - Commit protocol: write to an attempt-scoped path, then conditionally commit; first writer wins. Reducers read only the committed attempt. Speculative duplicates for stragglers are therefore harmless.
- Lost map output (if stored on local disk): mark the affected maps PENDING and rerun them. A remote shuffle store avoids this.
- Reducer failure: rerun it, write to a temp location, and publish through a manifest or atomic rename.
- Deterministic result: counts are exact integer sums, so order is irrelevant. Break ties by
(count desc, word asc)using byte-wise comparison so the top 1,000 is stable.
7. Verification
- Compare the sum of all counts against an independent total token count produced by the maps.
- Validate checksums on shuffle reads.
- Run a small input through both this pipeline and a single-machine reference and diff the results.
Trade-offs and common mistakes
- Using an approximate sketch: violates the exactness requirement.
- Splitting on raw byte offsets without an ownership rule: causes cut words to be counted twice or as two fragments.
- Skipping the combiner: shuffles every token and turns hot keys into a bottleneck.
- Letting retries write to the same path: leads to torn or duplicate output.
- Too few partitions: one reducer ends up with a huge share.
- Non-deterministic tie-breaking: the 1,000th place can change between runs.
- Keeping all counts on one aggregator: the table is tens of GB and a single node becomes the bottleneck.
Shuffle on local disk is cheaper but needs re-execution on node loss. A remote shuffle service costs more but gives faster recovery.