Unit 2 · Distributed Architectures for Text Mining¶
1. Setting the scene¶
Scenario: When one laptop is not enough
The CityDocs prototype runs on a data scientist's laptop and works well on 5,000 documents. Then reality arrives:
- the archive holds ten years of documents, too large for one disk to process in reasonable time;
- the citizen app sends ~50,000 messages per day, peaking at hundreds per minute after a storm;
- the platform must keep running when a server fails at 3 a.m.
IT asks: "Which tools do we need, and what does each one do?"
Guiding questions
- Which problems are about volume, which about velocity, which about failure?
- Where should historical data live, and where should fresh results live?
- Can the same architecture serve both search and analytics?
2. Intended learning outcomes¶
| # | Outcome | Bloom | CLO |
|---|---|---|---|
| ILO 2.1 | Explain why large, fast or failure prone workloads require distributed systems. | UNDERSTAND | 7 |
| ILO 2.2 | Describe the roles of HDFS, YARN, MapReduce, Spark, Kafka and Cassandra. | UNDERSTAND | 7 |
| ILO 2.3 | Trace a word count job through Map, Shuffle/Sort and Reduce. | APPLY | 7 |
| ILO 2.4 | Compare Hadoop MapReduce and Spark, and decide whether they replace or complement each other. | ANALYSE | 7 |
| ILO 2.5 | Design a streaming + batch architecture for a text mining use case. | CREATE | 7 |
3. Why distribute?¶
Some data problems exceed the limits of a single computer:
- too large: the data does not fit or cannot be processed in time on one machine;
- too fast: events arrive faster than one machine can ingest them;
- too important to fail: the service must survive machine failures.
A single machine has finite CPU, memory, storage and network bandwidth, and it is a single point of failure. Distributed systems scale out (add machines) rather than scale up (buy a bigger machine). The price is complexity: slow networks, partial failures, data spread across nodes, event ordering, and harder debugging. The foundations are covered in the Parallel Computing course, Unit 5: Distributed Computing, and the individual systems in Units 6 to 8.
Why this matters for text¶
Text mining starts small, but real collections include millions of reviews, support tickets, social posts and chat logs, often arriving continuously. The text mining workflow is itself a pipeline:
flowchart TB
subgraph R1["Get the text"]
direction LR
S["Text sources"] --> I["Ingestion"] --> C["Cleaning and<br/>normalisation"]
end
subgraph R2["Use the text"]
direction LR
F["Feature<br/>extraction"] --> A["Analysis ·<br/>classification · retrieval"]
end
R1 --> R2
When text becomes large, fast or continuous, each stage must run on a cluster.
A short history of the big data stack¶
timeline
title Storage and batch
2003 : Google File System
2004 : MapReduce paper
2006 : Hadoop open source
timeline
title Streaming and serving
2008 : Cassandra
2011 : Kafka
2014 : Spark 1.0 (Structured Streaming 2016)
How far does one machine go?¶
Worked example: indexing the CityDocs archive on one machine
Suppose parsing and tokenising runs at 2 MB/s per core and the archive holds 2 million documents of about 50 KB each, that is \(10^{11}\) bytes (100 GB).
The second number assumes perfect scaling. Network transfer, the shuffle and stragglers make it slower, which is exactly what the rest of this unit is about.
4. The reference architecture¶
In the lecture we use one running technical example, near real time fraud detection, because it exercises every component. Afterwards we transfer it to text.
flowchart TB
P["Python producer<br/>transaction events"] -->|"publish"| K[("Kafka<br/>stream transport")]
K -->|"subscribe"| S["PySpark<br/>processing and detection"]
K --> D["Other consumers<br/>dashboards · logging"]
S -->|"alerts, scores"| C[("Cassandra<br/>online serving store")]
S -->|"raw + enriched history"| H[("HDFS<br/>historical storage")]
H -.->|"batch training"| S
- Python generates transaction events.
- Kafka receives them in a distributed, replayable log.
- PySpark consumes the stream in parallel.
- Detection logic flags suspicious behaviour.
- Cassandra stores operational results for fast lookup.
- HDFS stores history for offline analysis and model training.
5. Hadoop: storage, resources, batch processing¶
flowchart TB
A["Applications<br/>analytics · ETL · ML · text mining jobs"]
P["Processing layer<br/>MapReduce · Spark"]
Y["YARN<br/>cluster resource management and scheduling"]
H["HDFS<br/>distributed storage across many nodes"]
A --> P --> Y --> H
HDFS¶
flowchart TB
NN["NameNode<br/>metadata: file → blocks → locations"]
subgraph W["Worker nodes"]
direction LR
D1["DataNode 1<br/>B1 · B2"]
D2["DataNode 2<br/>B2 · B3"]
D3["DataNode 3<br/>B1 · B3"]
end
NN -.-> D1 & D2 & D3
Files are split into blocks, blocks are replicated across DataNodes, and computation is scheduled close to the data (data locality). The NameNode only tracks metadata.
YARN¶
Yet Another Resource Negotiator is Hadoop's cluster manager. The ResourceManager schedules globally; a NodeManager on each worker runs jobs inside containers. YARN does not store data and does not define analytics logic; it provides resources so that MapReduce or Spark jobs can run.
MapReduce¶
A distributed programming model for large scale batch processing, in two user defined stages with a system provided shuffle in between.
flowchart LR
I["Input splits"] --> M1["Map"] & M2["Map"] & M3["Map"]
M1 & M2 & M3 --> S["Shuffle / Sort<br/>group by key"]
S --> R1["Reduce<br/>a to m"] & R2["Reduce<br/>n to z"]
R1 & R2 --> O["Output"]
Worked example: word count
- Map: each worker reads documents and emits
(word, 1)pairs, e.g.(fraud, 1),(alert, 1). - Shuffle/Sort: all pairs with the same key go to the same reducer.
- Reduce: sum the values, e.g.
(fraud, 2450).
MapReduce writes intermediate results to disk, which makes it robust but slow for iterative workloads such as machine learning. We reuse exactly this pattern to build inverted indexes in Unit 5.
MapReduce in formulas¶
The programmer writes two functions; the framework does the rest:
A partition function decides which of the \(R\) reducers receives a key, so that all values of one key meet in one place:
For word count, \(\text{map}(\text{docID}, \text{text})\) emits \((w, 1)\) for each word \(w\), and \(\text{reduce}(w, [1, 1, \dots, 1])\) emits \((w, \sum)\). In Unit 5 the same skeleton emits \((\text{term}, \text{docID})\) and builds postings lists.
6. Spark: the distributed processing engine¶
flowchart TB
DR["Driver program<br/>builds the execution plan (DAG), schedules tasks"]
DR --> E1["Executor 1<br/>partition A"]
DR --> E2["Executor 2<br/>partition B"]
DR --> E3["Executor 3<br/>partition C"]
E1 & E2 & E3 --> AGG["Combine results<br/>only when needed"]
Spark splits data into partitions, runs transformations on them in parallel and keeps intermediate data in memory where possible. The same engine supports batch ETL, SQL, machine learning and structured streaming.
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
spark = SparkSession.builder.appName("citydocs-wordcount").getOrCreate()
docs = spark.read.text("hdfs:///citydocs/archive/*.txt") # one row per line
counts = (docs
.select(F.explode(F.split(F.lower("value"), r"\W+")).alias("term"))
.where(F.col("term") != "")
.groupBy("term").count() # map + shuffle + reduce
.orderBy(F.desc("count")))
counts.show(10)
messages = (spark.readStream
.format("kafka")
.option("kafka.bootstrap.servers", "broker:9092")
.option("subscribe", "citizen-messages")
.load()
.selectExpr("CAST(value AS STRING) AS text"))
query = (messages.writeStream
.format("console") # replace with a Cassandra / Parquet sink
.outputMode("append")
.start())
Hadoop vs. Spark¶
| Hadoop MapReduce | Spark | |
|---|---|---|
| Model | Older batch model | Newer general purpose engine |
| Intermediate data | Written to disk | Kept in memory where possible |
| Iterative workloads (ML) | Slow | Fast: vendor benchmarks report up to ~100× on in memory iterative jobs |
| Workloads | Batch | Batch, SQL, ML, streaming |
| Has a file system? | Yes (HDFS is part of Hadoop) | No: reads from HDFS, S3, local files, databases, Kafka |
Replace or complement?
Spark usually replaces MapReduce as the processing engine, but complements HDFS and YARN: Spark jobs commonly read from HDFS and run on YARN.
Batch versus streaming: when does the answer arrive?¶
gantt
title A pothole report sent at 09:00
dateFormat HH:mm
axisFormat %H:%M
section Nightly batch
waits for the night job :crit, 09:00, 23:00
batch job runs :23:00, 23:59
section Streaming
routed within seconds :09:00, 09:01
A nightly batch job answers after about 14 hours; a streaming job answers in seconds. Many systems use both: streaming for immediate decisions, batch for retraining and reports.
7. Kafka: the transport layer¶
Kafka is a distributed, append only event log. It decouples producers from consumers and supports high throughput, replay, many independent consumers, partitioning and fault tolerance.
flowchart LR
subgraph T["Topic: citizen messages"]
direction TB
P0["Partition 0 · offsets 0 1 2 3"]
P1["Partition 1 · offsets 0 1 2"]
P2["Partition 2 · offsets 0 1 2 3 4"]
end
PR["Producers"] --> T
P0 --> C1["Consumer 1"]
P1 --> C2["Consumer 2"]
P2 --> C3["Consumer 3"]
subgraph G["Consumer group: spark router"]
C1
C2
C3
end
- Each partition is an ordered log; partitions enable parallel reads and writes.
- An offset records a consumer's position; consumers can rewind and replay.
- Within a consumer group, each partition is read by one consumer, so more partitions allow more parallelism.
# Minimal producer (kafka-python)
import json
from kafka import KafkaProducer
producer = KafkaProducer(bootstrap_servers="broker:9092",
value_serializer=lambda v: json.dumps(v).encode())
producer.send("citizen-messages",
{"id": 81723, "district": "Friedrichshain",
"text": "Bike lane on Warschauer Str. blocked by construction"})
producer.flush()
Two numbers help to size a Kafka topic. Messages with the same key always go to the same partition:
With \(P = 6\) partitions, a group of 8 consumers has 2 idle members. The lag (log end offset minus committed offset) tells how far a consumer is behind; if messages arrive at rate \(\lambda\) and are processed at rate \(\mu > \lambda\), a backlog \(L\) disappears after \(L / (\mu - \lambda)\) seconds.
8. Cassandra: the scalable memory of the pipeline¶
Cassandra is a distributed NoSQL database with a peer to peer architecture: there is no master node, every node can serve requests, and there is no single point of failure.
flowchart LR
CL(("Client")) --> N1
N1["Node 1"] --- N2["Node 2"] --- N3["Node 3"] --- N4["Node 4"] --- N1
R["Record<br/>partition key = district"] -->|"hash(key)"| N2
N2 -.->|"replica"| N3
A partition key is hashed to decide which node stores the row; replicas on further nodes provide availability. Cassandra suits frequent writes and time series like data such as fraud scores, customer histories, or in our case per message classification results. It is not the stream processor.
9. One line roles¶
| System | Role in the pipeline |
|---|---|
| HDFS | Stores large historical data |
| YARN | Manages cluster resources |
| MapReduce | Older batch processing model |
| Spark | Newer distributed processing engine (batch + streaming) |
| Kafka | Transports event streams |
| Cassandra | Stores scalable online results |
10. Transfer: the same architecture for text¶
flowchart TB
APP["City app"] -->|"message JSON"| K[("Kafka<br/>citizen messages")]
K --> SP["Spark Structured Streaming<br/>clean · tokenize · classify"]
SP --> CA[("Cassandra<br/>message_id → department, score")]
SP --> HD[("HDFS / Parquet<br/>all messages")]
HD --> TR["Spark batch<br/>retrain classifier · rebuild index"]
TR -.-> SP
CA --> DB["Department dashboards"]
The analytic task changes (fraud → text classification), but the architectural roles stay the same. Fraud detection is not text mining, yet it follows identical pipeline logic (ingest, clean, derive features, classify), and if transactions include free text fields (merchant names, complaints, notes), text mining plugs in naturally.
The same flow as a sequence of calls:
sequenceDiagram
participant App as City app
participant K as Kafka
participant S as Spark
participant C as Cassandra
participant D as Dashboard
App->>K: produce(district, JSON)
K-->>S: new offsets
S->>S: clean, classify
S->>C: INSERT result
S->>K: commit offset
D->>C: SELECT for Roads
C-->>D: rows
11. Classwork¶
Design exercise (20 min, pairs)
CityDocs wants live topic trends: every 10 minutes, show the top 10 terms in citizen messages per district, and keep one year of history for monthly reports.
Sketch the architecture. For each component, write one sentence on why it is there and what happens if its node fails.
One possible answer
Kafka topic partitioned by district → Spark Structured Streaming with 10 minute tumbling windows computing term counts (word count pattern) → results written to Cassandra (district, window_start as key) for dashboards → raw messages appended to HDFS/Parquet for monthly batch jobs. Failures: Kafka replicates partitions and consumers resume from offsets; Spark recomputes lost partitions from lineage/checkpoints; Cassandra serves from replicas; HDFS re replicates blocks.
12. Check your understanding¶
Does YARN store data?
No. YARN allocates CPU and memory (containers) to jobs. Data is stored in HDFS (or another storage system).
Why is Spark usually faster than MapReduce for machine learning?
ML algorithms iterate over the same data many times. MapReduce writes intermediate results to disk between stages; Spark can cache them in memory.
What is the relationship between Kafka partitions and consumer parallelism?
Within one consumer group, each partition is consumed by at most one consumer. The number of partitions therefore caps the useful number of parallel consumers.
13. Key takeaways¶
- Distribute when data is too large, too fast, or too important to fail.
- HDFS stores, YARN allocates, MapReduce/Spark compute, Kafka transports, Cassandra serves.
- Split → process in parallel → combine is the core idea behind MapReduce, Spark and distributed indexing.
- The same architecture serves fraud detection and text mining: the roles stay, the analytics change.
14. Link to assessment¶
The project allows (and rewards) a scalable pipeline: Hadoop for storage and batch, Kafka for ingestion, Spark / Spark NLP for preprocessing. Your README must contain an architecture diagram (data → preprocessing → model → output); this unit gives you the vocabulary for it.
Further reading¶
- Karau, Konwinski, Wendell & Zaharia, Learning Spark, O'Reilly.
- Leskovec, Rajaraman & Ullman, Mining of Massive Datasets, ch. 2 (MapReduce).
- Dean & Ghemawat (2004), MapReduce: Simplified Data Processing on Large Clusters, OSDI.