PySpark RDD Fundamentals
Narrow vs Wide Transformation Partition Mapping
RDD Lineage Fault Tolerance
RDD Architecture Overview
RDD Transformation DAG
Narrow vs Wide Transformations
Lazy Evaluation: Jobs, Stages and Tasks
Calling rdd.map(...) or rdd.filter(...) does no compute work: Spark records the call in the lineage graph and returns an RDD handle, and nothing runs until an action such as count() or saveAsTextFile() is called. At that point the DAGScheduler turns the lineage into an execution plan.
Three units matter when reading a Spark UI:
- A job is created per action:
count()thencollect()on one RDD submits two jobs, each recomputing the lineage unless the RDD was persisted between them. - A stage is a maximal run of narrow transformations: every wide transformation terminates one, because reduce tasks cannot begin until its shuffle write completes.
- A task is one partition's slice of a stage: 400 partitions mean 400 tasks, run in waves of
totalCores.
Worked numbers: textFile() then map(), filter() and reduceByKey() over 400 input partitions producing 200 reduce partitions. One count() action submits a single job with two stages โ 400 map tasks plus 200 reduce tasks, so 600 launches, about 13 waves on a 48-core cluster.
Sizing Partitions and Diagnosing Skew
The partition formula above, P = max(dataSize / partitionSize, totalCores), decides the input partition count. A 120 GB log at the 200 MB target gives 600 partitions; the core floor on a 48-core cluster is 48, so 600 wins and the job runs in 600 รท 48 โ 13 waves. When input is tiny โ a 300 MB dimension table โ the size term yields only 2 partitions, the core floor takes over, and repartition(48) keeps every executor busy. Oversharding fails the other way: 40,000 tasks at 100 ms of scheduling each burn 4,000 seconds of driver time before a record is processed.
Skew hides in the stage metric: a stage completes only when its slowest task completes. If 199 of 200 reduce partitions finish in 8 seconds while one hot key carrying 40ร the median record count runs for 140 seconds, the stage takes 140 seconds and 199 cores idle throughout โ effective utilisation for that stage is about 6 percent. Confirm it in the Spark UI by comparing task durations within one stage, then attack the key: pre-aggregate with reduceByKey so the map-side combiner shrinks the hot key before it crosses the network, or salt the key across several reducer buckets and aggregate twice.
Code Examples
Basic RDD Operations
from pyspark import SparkContext, SparkConf
conf = SparkConf().setAppName("RDD_Basics").setMaster("local[*]")
sc = SparkContext(conf=conf)
# Create RDD from collection
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
rdd = sc.parallelize(data, 4) # 4 partitions
print(f"Partitions: {rdd.getNumPartitions()}")
# Narrow transformations (no shuffle)
mapped = rdd.map(lambda x: x * 2)
filtered = rdd.filter(lambda x: x > 5)
flattened = rdd.flatMap(lambda x: [x, x * 10])
# Wide transformation (shuffle)
pairs = rdd.map(lambda x: (x % 3, x))
grouped = pairs.groupByKey()
reduced = pairs.reduceByKey(lambda a, b: a + b)
# Actions (trigger execution)
print(f"Count: {rdd.count()}")
print(f"First: {rdd.first()}")
print(f"Take: {rdd.take(3)}")
print(f"Sum: {rdd.reduce(lambda a, b: a + b)}")
# Check lineage
print(rdd.toDebugString().decode())
sc.stop()
RDD Persistence Levels
from pyspark import StorageLevel
# Cache in memory (deserialized)
rdd.cache() # Equivalent to persist(StorageLevel.MEMORY_ONLY)
# Persist with specific storage level
rdd.persist(StorageLevel.MEMORY_AND_DISK)
rdd.persist(StorageLevel.MEMORY_ONLY_SER)
rdd.persist(StorageLevel.DISK_ONLY)
rdd.persist(StorageLevel.OFF_HEAP)
# Unpersist when done
rdd.unpersist()
Key Concepts Table
| Concept | Description | Example |
|---|---|---|
| Partition | Logical chunk of data for parallel processing | rdd.getNumPartitions() |
| Lineage | DAG of transformations for fault tolerance | rdd.toDebugString() |
| Narrow Transform | 1:1 partition mapping, no shuffle | map(), filter(), flatMap() |
| Wide Transform | M:N partition mapping, requires shuffle | groupByKey(), reduceByKey(), join() |
| Lazy Evaluation | Transforms built but not executed until action | Build DAG โ Action triggers execution |
| Action | Triggers computation, returns result | collect(), count(), first() |
| Cache/Persist | Store RDD in memory/disk for reuse | rdd.cache() or rdd.persist() |
| Checkpoint | Write RDD to reliable storage, truncate lineage | rdd.checkpoint() |
| Broadcast | Read-only variable cached on each executor | sc.broadcast(variable) |
| Accumulator | Write-only variable for aggregations | sc.accumulator(0) |
Best Practices
- Prefer DataFrames over RDDs โ DataFrames use Catalyst optimizer and Tungsten engine for automatic optimization
- Use
reduceByKeyovergroupByKeyโreduceByKeycombines locally before shuffle, reducing network I/O - Cache wisely โ Only cache RDDs that are reused across multiple actions
- Partition appropriately โ Aim for 128MBโ200MB per partition
- Avoid
collect()on large datasets โ usetake(n)orforeach()instead - Use
coalesce()to reduce partitions โ avoids full shuffle unlikerepartition() - Enable Kryo serialization โ 10x faster than Java serialization
- Monitor shuffle spill โ indicates memory pressure
Key Takeaways
See Also
- SparkSession Architecture โ The entry point that creates and manages RDDs
- DataFrame Operations โ Higher-level API with Catalyst optimizations
- SparkSQL Engine โ SQL queries over RDDs and DataFrames
- Transformation Types โ Comprehensive guide to all transformations
- Kafka Architecture โ Stream processing with RDD-based DStreams