# Generate synthetic text (1 million words)import random
words = ["data", "mining", "scale", "spark", "map", "reduce", "cluster", "node"]
big_text = " ".join(random.choices(words, k=1_000_000))
# Method 1: Naive Python loop
t0 = time.time()
counts_naive = {}
for w in big_text.split():
counts_naive[w] = counts_naive.get(w, 0) + 1
t_naive = time.time() - t0
# Method 2: PySpark MapReduce
t1 = time.time()
rdd = sc.parallelize(big_text.split(), numSlices=4)
counts_spark = rdd \
.map(lambda w: (w, 1)) \
.reduceByKey(lambda a, b: a + b) \
.collect()
t_spark = time.time() - t1
print(f"Naive Python : {t_naive:.3f}s")
print(f"PySpark : {t_spark:.3f}s")
print(f"\nTop 5 words (Spark):")
for word, cnt in sorted(counts_spark, key=lambda x: -x[1])[:5]:
print(f" {word:10s} {cnt}")
Output
Naive Python : 0.312s
PySpark : 1.847s ← overhead dominates at small scale
Top 5 words (Spark):
data 125143
mining 124988
scale 124872
spark 125001
map 124996
Markdown
Why is Spark slower here? Spark has startup overhead (JVM, serialization, task scheduling). At 1M words, this overhead dominates. At 1 billion words on a real cluster, Spark wins by orders of magnitude because it distributes work across machines. This is an essential insight: distributed systems have fixed costs: they only pay off at scale.
Markdown
Part 2: Real Data: NASA HTTP Log Analysis
We will analyse the NASA-HTTP server log from July 1995: a classic dataset used in distributed computing courses. It contains ~1.9 million HTTP requests logged at the Kennedy Space Center web server.
Format: host - - [timestamp] "request" status bytes
Code
# Download the NASA log (compressed, ~20MB)!wget -q "ftp://ita.ee.lbl.gov/traces/NASA_access_log_Jul95.gz" -O nasa_log.gz
!gunzip -f nasa_log.gz
!wc -l nasa_log # Count lines
Output
1891715 nasa_log
Code
# Load into Spark RDD
log_rdd = sc.textFile("nasa_log")
# Parse each line with a regex# Format: host - - [timestamp] "GET /path HTTP/1.0" status bytes
LOG_PATTERN = re.compile(
r'(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) \S+" (\d+) (\S+)'
)
defparse_line(line):
m = LOG_PATTERN.match(line)
if m:
host, ts, method, path, status, size = m.groups()
return (host, ts, method, path, int(status), size)
returnNone
parsed = log_rdd.map(parse_line).filter(lambda x: x is not None)
print(f"Parsed lines: {parsed.count():,}")
print("Sample:", parsed.first())
# Q1: What are the top 10 most-requested URLs?
top_urls = parsed \
.map(lambda x: (x[3], 1)) \
.reduceByKey(lambda a, b: a + b) \
.sortBy(lambda x: -x[1]) \
.take(10)
print("Top 10 URLs:")
for url, cnt in top_urls:
print(f" {cnt:8,} {url}")
# Q2: Distribution of HTTP status codes
status_dist = parsed \
.map(lambda x: (x[4], 1)) \
.reduceByKey(lambda a, b: a + b) \
.sortBy(lambda x: -x[1]) \
.collect()
print("HTTP Status Codes:")
for status, cnt in status_dist:
bar = "█" * int(cnt / 30000)
print(f" {status} {cnt:8,} {bar}")
# Q3: Top 10 hosts by number of requests
top_hosts = parsed \
.map(lambda x: (x[0], 1)) \
.reduceByKey(lambda a, b: a + b) \
.sortBy(lambda x: -x[1]) \
.take(10)
print("Top 10 requesting hosts:")
for host, cnt in top_hosts:
print(f" {cnt:6,} {host}")
Complete the following in your own copy of this notebook:
Error rate: What percentage of all requests returned a 4xx or 5xx status code? Use filter() and count().
Hourly traffic: Parse the hour from the timestamp and count requests per hour. Which hour had the most traffic? (hint: timestamp format is 01/Jul/1995:00:00:01 -0400: split on :)
Bandwidth: Sum the bytes field per host and find the top 5 hosts by total bytes transferred. Handle the "-" case (treat as 0).
404 analysis: Which URLs had the most 404 (not found) errors? List the top 10.
Hint for Task 2:ts.split(':')[1] gives you the hour as a string (e.g. "00", "14"). Group and count from there.
Markdown
Reflection Questions
Answer these briefly in a markdown cell in your notebook:
At what approximate data size do you think Spark would start outperforming the naive Python loop on a single machine? Why?
The reduceByKey operation is a reduce. What is the corresponding map step in this pipeline?
If you had 100 machines and 1TB of logs, which parts of this pipeline would run in parallel?