Spark - Why Spark Exists
🎯 The Problem: Why Spark Exists
Limitations of Traditional MapReduce
MapReduce Model:
Input → Map → Reduce → Output (to disk)
↓
Every iteration reads from disk again!
The Inefficiency:
- ❌ Acyclic data flow - Data flows from stable storage → stable storage
- ❌ Apps must reload data from disk on each query
- ❌ Terrible for:
- Iterative algorithms (machine learning, graphs)
- Interactive data mining (R, Python, Excel-like tools)
Analogy: Like going to the library, checking out a book, reading one chapter, returning it, then repeating this for every chapter. You waste time traveling back and forth instead of keeping the book on your desk!
What MapReduce Does Well:
- ✅ Runtime flexibility
- ✅ Automatic fault recovery
💡 The Solution: Apache Spark
Definition
Open-source, distributed computing system for big data processing that keeps working sets in memory for efficient reuse.
Core Innovation: RDD (Resilient Distributed Dataset)
RDD = Immutable, partitioned collections of objects that can be cached in memory
🔑 Key RDD Properties
1. In-Memory Computing
- Data stays in RAM between operations
- No repeated disk I/O
- 100x faster than Hadoop for in-memory workloads
2. Fault Tolerance WITHOUT Replication
- Lineage tracking - Remember HOW data was created
- If partition lost → recompute from lineage
- Much cheaper than storing 3 copies (like HDFS)
Analogy: Instead of storing 3 cakes in different places (expensive), just keep the recipe. If a cake is destroyed, follow the recipe to recreate it. The recipe is tiny compared to actual cakes!
3. Partitioning
- Data split across multiple nodes
- Each partition processed in parallel
- Scalable, high-performance computation
4. Lazy Evaluation
- Transformations don't execute immediately
- Spark builds execution plan (DAG)
- Executes only when action is called
- Optimizes entire workflow
5. Immutability
- RDDs cannot be modified
- Transformations create NEW RDDs
- Simpler reasoning about data flow
📊 Hadoop vs Spark Comparison
| Feature | Hadoop MapReduce | Spark RDD |
|---|---|---|
| Storage | Disk-based | In-memory |
| Speed | Slow iteration | 100x faster |
| APIs | Limited | Rich transformations |
| Fault Model | Replication | Lineage-based |
| Best For | Batch processing | Iterative + Interactive |
| Iteration Cost | High (disk I/O) | Low (memory) |
🏗️ Spark Architecture
Components
┌─────────────────────────────────────┐
│ Driver Program │
│ (Your Spark Application) │
│ - SparkContext │
│ - DAG Scheduler │
└──────────┬──────────────────────────┘
│ Tasks
↓
┌──────────────────────────────────────┐
│ Cluster Manager │
│ (YARN, Mesos, K8s, Standalone) │
└──────────┬───────────────────────────┘
│
┌──────┴──────┬──────────┐
↓ ↓ ↓
┌─────────┐ ┌─────────┐ ┌─────────┐
│Worker 1 │ │Worker 2 │ │Worker 3 │
│Cache 1 │ │Cache 2 │ │Cache 3 │
│Block 1 │ │Block 2 │ │Block 3 │
└─────────┘ └─────────┘ └─────────┘
Data Flow:
- Driver sends tasks to workers
- Workers execute on cached/partitioned data
- Results sent back to driver
🎨 Spark Programming Model
Two Types of Operations
1. Transformations (Lazy - Build DAG)
Create a NEW RDD from existing one
| Operation | Description | Example |
|---|---|---|
map | Apply function to each element | rdd.map(x => x * 2) |
filter | Select matching elements | rdd.filter(x => x > 10) |
flatMap | Map then flatten | rdd.flatMap(line => line.split(" ")) |
groupByKey | Group values by key | rdd.groupByKey() |
reduceByKey | Reduce values by key | rdd.reduceByKey(_ + _) |
sortByKey | Sort by key | rdd.sortByKey() |
join | Join two RDDs | rdd1.join(rdd2) |
union | Combine two RDDs | rdd1.union(rdd2) |
distinct | Remove duplicates | rdd.distinct() |
sample | Random sample | rdd.sample(false, 0.1) |
Key Point: Transformations are NOT executed until an action is called!
2. Actions (Eager - Trigger Execution)
Return results to driver or save to storage
| Operation | Description | Example |
|---|---|---|
count | Count elements | rdd.count() |
collect | Return all elements | rdd.collect() |
reduce | Aggregate elements | rdd.reduce(_ + _) |
take(n) | Return first n elements | rdd.take(10) |
first | Return first element | rdd.first() |
foreach | Apply function to each | rdd.foreach(println) |
save | Save to storage | rdd.saveAsTextFile(...) |
lookup(key) | Return value for key | rdd.lookup("foo") |
Analogy: Transformations = writing a shopping list (planning), Actions = actually going to the store and buying items (execution).
Example: Lazy Evaluation
# NO execution yet - just building DAG
rdd1 = sc.textFile("data.txt") # Transformation
rdd2 = rdd1.filter(lambda x: "error" in x) # Transformation
rdd3 = rdd2.map(lambda x: x.upper()) # Transformation
# NOW execution starts!
result = rdd3.count() # ActionDAG Built:
textFile → filter → map → count
Spark optimizes this entire pipeline before execution!
📝 Example 1: Log Mining
Use Case
Load error messages from logs into memory, then interactively search for patterns.
Code
// Load and cache data
lines = spark.textFile("hdfs://server_logs.txt")
errors = lines.filter(_.startsWith("ERROR"))
messages = errors.map(_.split('\t')(2))
cachedMsgs = messages.cache() // ← Keep in memory!
// Interactive queries (FAST!)
cachedMsgs.filter(_.contains("mysql")).count // ~1 sec
cachedMsgs.filter(_.contains("php")).count // ~1 sec
cachedMsgs.filter(_.contains("timeout")).count // ~1 secPerformance
| Dataset | In-Memory | On-Disk |
|---|---|---|
| Wikipedia | < 1 sec | 20 sec |
| 1 TB data | 5-7 sec | 170 sec |
Speedup: ~20-30x
Real-world: Netflix analyzes billions of streaming events daily using similar Spark patterns, caching frequently accessed user behavior data for instant recommendations.
📈 Example 2: Logistic Regression (Machine Learning)
Goal
Find the best line separating two classes (binary classification).
Visualization
Class A (●)
●
● ╱ ← Optimal line
● ╱
● ╱
╱ ○
╱ ○
╱ ○ Class B (○)
Code
val data = spark.textFile(...).map(readPoint).cache() // ← Cache!
var w = Vector.random(D) // Random initial weights
for (i <- 1 to ITERATIONS) {
val gradient = data.map(p =>
(1 / (1 + exp(-p.y*(w dot p.x))) - 1) * p.y * p.x
).reduce(_ + _)
w -= gradient // Update weights
}Mathematical Formula
Where:
- = weight vector (the line we're finding)
- = feature vector (data point)
- = label (+1 or -1)
- Sigmoid:
Performance Comparison
| Iterations | Hadoop | Spark |
|---|---|---|
| 1 | 174s | 174s |
| 5 | 635s | 174s |
| 10 | 1270s | 174s |
| 20 | 2540s | 174s |
| 30 | 3810s | 174s |
Analysis:
- Hadoop: 127s per iteration (reads from disk every time)
- Spark first iteration: 174s (initial load + compute)
- Spark subsequent iterations: ~6s (data cached in RAM!)
Speedup: 20-25x for iterative algorithms
Real-world: Uber trains demand prediction models using Spark, processing millions of rides to optimize pricing and driver matching in real-time.
🛡️ RDD Fault Tolerance
Lineage Tracking
Concept: Track HOW data was created, not replicate the data itself.
Example Lineage Graph
messages = textFile("hdfs://...")
.filter(_.startsWith("ERROR"))
.map(_.split('\t')(2))Lineage DAG:
[HDFS File]
↓ filter(_.startsWith("ERROR"))
[Filtered RDD]
↓ map(_.split('\t')(2))
[Mapped RDD]
If partition lost:
- Spark checks lineage
- Recomputes ONLY lost partition
- Re-executes:
textFile → filter → mapfor that partition
Analogy: Breadcrumb trail - if you get lost, follow breadcrumbs back and retrace your steps. You don't need someone to teleport you to where you were!
Fault Recovery Performance
Experiment: 10 iterations, inject failure at iteration 6
| Iteration | No Failure | With Failure | Notes |
|---|---|---|---|
| 1 | 119s | 119s | Initial load |
| 2-5 | ~57s | ~57s | Cached |
| 6 | 57s | 81s | ← Failure! |
| 7-10 | ~57s | ~57s | Recovered |
Recovery overhead: Only 24 seconds!
- Only lost partition recomputed
- Subsequent iterations normal
- Automatic, no manual intervention
🧠 Memory Behavior
Performance vs Cached Percentage
| Memory Cached | Iteration Time |
|---|---|
| 0% (disabled) | 68.8s |
| 25% | 58.1s |
| 50% | 40.7s |
| 75% | 29.7s |
| 100% | 11.5s |
Key Insights:
- Even 25% caching → 15% faster
- 50% caching → 41% faster
- Full caching → 83% faster
Important: Spark gracefully degrades with limited RAM - doesn't fail, just recomputes or spills to disk.
🧩 Core Spark Components
1. Spark Core
- Foundation for distributed execution
- Implements RDD abstraction
- Memory management
2. Spark SQL
- Structured data processing with SQL
- DataFrames and Datasets
- Query optimization
- Supports Parquet, JSON, Hive, JDBC
Real-world: Airbnb runs thousands of SQL queries daily on petabytes of data using Spark SQL to analyze booking patterns.
3. Spark Streaming
- Real-time data stream processing
- Micro-batch architecture
- Sources: Kafka, Flume, Kinesis
Real-world: Twitter analyzes trending topics in real-time, processing millions of tweets/second using Spark Streaming.
4. MLlib (Machine Learning)
Scalable ML library:
- Classification (spam detection)
- Clustering (customer segmentation)
- Regression (price prediction)
- Collaborative filtering (recommendations)
Real-world: Spotify uses MLlib to analyze billions of song plays, powering personalized playlist recommendations.
5. GraphX (Graph Processing)
Graph computation framework:
- PageRank (node importance)
- Connected Components (clusters)
- Shortest Paths
- Triangle Counting
Real-world: LinkedIn uses GraphX to analyze their professional network, suggesting connections and job opportunities.
🚀 Deployment Modes
1. Standalone
- Simple cluster mode
- Good for testing/development
2. YARN (Hadoop)
- Integrates with existing Hadoop infrastructure
- Uses Hadoop's resource manager
3. Apache Mesos
- Fine-grained resource sharing
- Can run alongside other frameworks
4. Kubernetes
- Modern container orchestration
- Auto-scaling
- Cloud-native
5. Cloud Services
| Provider | Service | Notes |
|---|---|---|
| AWS | EMR | Elastic MapReduce |
| Azure | HDInsight | Integrated with Azure |
| GCP | Dataproc | Fast provisioning |
| Multi-cloud | Databricks | Managed Spark platform |
Real-world Examples:
- Netflix: AWS EMR → 1 trillion events/day
- Apple: Databricks on Azure → ML workloads
- Lyft: Kubernetes → ride analytics
🎯 Real-World Production Use Cases
1. Conviva - In-Memory Data Mining on Hive
- Aggregations with same WHERE clause
- Hive: 20 hours
- Spark: 0.5 hours
- 40x speedup from:
- Not re-reading unused columns
- Avoiding repeated decompression
- In-memory deserialized objects
2. City Traffic Prediction - Mobile Millennium
- GPS data from smartphones
- Real-time traffic pattern prediction
3. Twitter Spam Classification - Monarch
- ML on streaming tweets
- Real-time spam detection
4. Collaborative Filtering
- Matrix factorization for recommendations
- User-item preference prediction
🏢 Major Companies Using Spark
| Company | Use Case |
|---|---|
| Netflix | 1T events/day, recommendations |
| Uber | Demand prediction, pricing |
| Airbnb | Pricing algorithms, fraud detection |
| Apple | Siri improvements, analytics |
| Profile recommendations, job matching | |
| Visual search, content recommendations | |
| Spotify | Music recommendations, playlists |
| Trend analysis, spam detection |
⚙️ Spark Scheduler
Features
1. DAG Execution
- Creates Directed Acyclic Graph
- Optimizes execution order
- Identifies stages
2. Pipeline Optimization
- Combines multiple transformations
- Reduces intermediate materialization
3. Cache-Aware Scheduling
- Reuses cached data
- Schedules tasks near data (locality)
4. Partition-Aware
- Avoids unnecessary shuffles
- Optimizes joins
Example DAG with Stages
Stage 1 Stage 2 Stage 3
A ─┐
├─► join ──┐
B ─┘ │
├─► union ─► groupBy ─► map
C ─┐ │
├─► join ──┘
D ─┘
E ────────────────────────────────────►
F ────────────────────────────────────►
G (cached) ════════════════════════════►
Legend:
── = RDD lineage
══ = Cached partition
Stage boundaries: Shuffle operations (join, groupBy)
💻 Interactive Spark
Spark Shell
Modified Scala interpreter for interactive use:
$ spark-shell
Welcome to Spark Shell!
scala> val data = sc.textFile("hdfs://...")
scala> val filtered = data.filter(_.contains("error"))
scala> filtered.count()
res0: Long = 12345
scala> filtered.cache() // Cache for reuse
scala> filtered.take(10) // View first 10Implementation:
- Modified wrapper code generation
- Distribute classes over network to workers
- Each line tracks dependencies
Analogy: Like a Python Jupyter notebook for big data - experiment with massive datasets interactively, see results immediately.
📚 Practical Code Examples
Example 1: Log Processing
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("LogAnalysis").getOrCreate()
sc = spark.sparkContext
# Load logs
logs = sc.textFile("server_logs.txt")
# Filter errors
errors = logs.filter(lambda line: "ERROR" in line)
# Count by error type
error_counts = errors.map(lambda line: (line.split()[1], 1)) \
.reduceByKey(lambda a, b: a + b)
# Results
print(error_counts.collect())
# [("ConnectionTimeout", 120), ("DatabaseDown", 45)]Real-world: Datadog and Splunk analyze billions of log events/day using similar patterns.
Example 2: Sentiment Analysis
# Word lists
positive_words = {"good", "happy", "love", "awesome"}
negative_words = {"bad", "sad", "hate", "terrible"}
# Load tweets
tweets = sc.textFile("tweets.txt")
# Analyze sentiment
sentiment = tweets.flatMap(lambda line: line.split()) \
.map(lambda word:
("positive", 1) if word.lower() in positive_words
else ("negative", 1) if word.lower() in negative_words
else None) \
.filter(lambda x: x is not None) \
.reduceByKey(lambda a, b: a + b)
print(sentiment.collect())
# [("positive", 300), ("negative", 120)]Real-world: Brandwatch monitors millions of social media posts for brand sentiment analysis.
🆚 Related Work & Comparisons
DryadLINQ, FlumeJava
- Similar distributed collection API
- ❌ Cannot reuse datasets efficiently
- ✅ Spark: Explicit caching and reuse
Relational Databases
- Use lineage/provenance
- ✅ Spark extends to big data scale
Iterative MapReduce (Twister, HaLoop)
- Implicit data sharing for fixed patterns
- ❌ Less flexible than Spark's explicit caching
Caching Systems (Nectar)
- Store data in files
- ❌ No explicit control over what's cached
- ✅ Spark: Programmer controls caching
GraphLab, Piccolo
- Fine-grained writes (distributed shared memory)
- Different approach than Spark's coarse-grained transformations
✨ Spark Advantages Summary
1. ⚡ Speed
- 100x faster than Hadoop (in-memory)
- Eliminates disk I/O bottlenecks
2. 🔄 Flexibility
- Batch, streaming, ML, graph analytics
- Unified platform
3. 👨💻 Ease of Use
- SQL, Python, Scala, Java, R
- High-level APIs
4. 📊 Scalability
- Thousands of nodes
- Petabytes of data
5. 🛡️ Fault Tolerance
- Lineage-based recovery
- Automatic, fast recovery
🎓 Domain Applications
🔍 Big Data Analytics
- Log processing
- Clickstream analysis
- A/B testing
💰 Finance & Security
- Fraud detection
- Risk modeling
- Network traffic analysis
- Anomaly detection
🏥 Healthcare
- DNA sequence analysis
- Medical image processing
- IoT health monitoring
🎯 Recommendations & AI
- Collaborative filtering
- Content personalization
- Search ranking
🌐 Real-Time
- Stream processing
- Live dashboards
- Real-time alerting
🔑 Key Takeaways
1. RDDs Enable Efficient Reuse
- Keep working sets in memory
- Avoid repeated disk I/O
2. Lineage-Based Fault Tolerance
- Track how data was created
- Recompute on failure
- No replication overhead
3. In-Memory = Speed
- Orders of magnitude faster
- Critical for iterative algorithms
4. Lazy Evaluation
- Build execution plan (DAG)
- Optimize before execution
- Execute only when needed
5. Unified Platform
- Batch, streaming, ML, graph
- One framework for all workloads
6. Production Ready
- Thousands of companies
- Petabyte-scale deployments
📐 Important Formulas
Logistic Regression Gradient
Sigmoid Function
🎯 Exam Tips
Q1: What makes Spark faster than Hadoop?
Answer:
- In-memory processing (no repeated disk I/O)
- Lineage tracking instead of replication
- DAG optimization
- Lazy evaluation
Q2: How does Spark handle failures?
Answer:
- Lineage tracking (remembers how data was created)
- Recomputes lost partitions from lineage
- Only lost data recomputed, not entire dataset
- Automatic recovery
Q3: When is Spark better than Hadoop?
Answer:
- ✅ Iterative algorithms (ML)
- ✅ Interactive queries
- ✅ Real-time processing
- ❌ Simple one-pass batch jobs (Hadoop is fine)
Q4: What are transformations vs actions?
Answer:
- Transformations: Lazy, build DAG (map, filter, join)
- Actions: Eager, trigger execution (count, collect, save)
Q5: What is lineage?
Answer:
- DAG of transformations that created an RDD
- Used for fault recovery
- Cheaper than data replication
- Example:
textFile → filter → map
🔄 Transformation vs Action Quick Reference
Transformations (Return RDD)
map, filter, flatMap, groupByKey, reduceByKey,
sortByKey, join, union, distinct, sample
Actions (Return Value)
count, collect, reduce, take, first, foreach,
save, lookup
Remember: Transformations are lazy, actions trigger execution!
📊 Performance Comparison Table
| Workload | Hadoop | Spark | Speedup |
|---|---|---|---|
| Iterative ML (30 iter) | 3810s | 174s | 22x |
| Interactive queries | 20 hours | 0.5 hours | 40x |
| Log mining (1TB) | 170s | 5-7s | 25-30x |
| Full-text search | 20s | <1s | 20x+ |
🌟 Best Practices
1. Cache Wisely
- Cache data reused across multiple operations
- Use
persist()with storage levels - Unpersist when done
2. Minimize Shuffles
- Shuffles are expensive (network transfer)
- Use
reduceByKeyinstead ofgroupByKey - Partition data appropriately
3. Tune Parallelism
- Set number of partitions based on cluster size
- Too few → underutilized cluster
- Too many → overhead
4. Broadcast Small Data
- Broadcast small lookup tables
- Avoid sending large data to executors
5. Monitor Performance
- Use Spark UI
- Check DAG visualization
- Monitor memory usage
📚 Additional Resources
Official
- Download: spark.apache.org
- Documentation: spark.apache.org/docs/latest
- Contact: matei@berkeley.edu (original creator)
Cloud Platforms
- Databricks (databricks.com)
- AWS EMR
- Azure HDInsight
- Google Cloud Dataproc
Frameworks Built on Spark
- Bagel - Pregel on Spark (graph processing)
- Shark - Hive on Spark (SQL)
- MLlib - Machine learning
- GraphX - Graph analytics
🎊 Final Summary
Spark provides:
- ✅ Fast iterative algorithms
- ✅ Interactive data exploration
- ✅ Real-time stream processing
- ✅ Machine learning at scale
- ✅ Graph analytics
- ✅ Unified platform for all workloads
Key Innovation: In-memory computing with lineage-based fault tolerance
Production Proven: Used by thousands of organizations processing petabytes daily
Good luck on your exam, Google! 🚀