๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
NEWSLIVESearch All Content
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

PySpark RDD Fundamentals: Architecture, Transformations, and Actions

PySpark FundamentalsRDD๐ŸŸข Free Lesson

PySpark RDD Fundamentals

Narrow vs Wide Transformation Partition Mapping

Narrow (1:1)Wide (N:M Shuffle)P0P1P2P3P0'P1'P2'P3'map, filter, flatMap, unionP0P1P2P3P0'P1'P2'P3'groupByKey, reduceByKey, join, repartitionShuffle Barrier: data written to disk, transferred across network, read by reducer

RDD Lineage Fault Tolerance

textFile()map()filter()reduceByKey()collect()Lineage: If P2 of reduceByKey lost โ†’ recompute only P2 from source โ†’ map โ†’ filter โ†’ reduceByKey

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() then collect() 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

python
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

python
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

ConceptDescriptionExample
PartitionLogical chunk of data for parallel processingrdd.getNumPartitions()
LineageDAG of transformations for fault tolerancerdd.toDebugString()
Narrow Transform1:1 partition mapping, no shufflemap(), filter(), flatMap()
Wide TransformM:N partition mapping, requires shufflegroupByKey(), reduceByKey(), join()
Lazy EvaluationTransforms built but not executed until actionBuild DAG โ†’ Action triggers execution
ActionTriggers computation, returns resultcollect(), count(), first()
Cache/PersistStore RDD in memory/disk for reuserdd.cache() or rdd.persist()
CheckpointWrite RDD to reliable storage, truncate lineagerdd.checkpoint()
BroadcastRead-only variable cached on each executorsc.broadcast(variable)
AccumulatorWrite-only variable for aggregationssc.accumulator(0)

Best Practices

  1. Prefer DataFrames over RDDs โ€” DataFrames use Catalyst optimizer and Tungsten engine for automatic optimization
  2. Use reduceByKey over groupByKey โ€” reduceByKey combines locally before shuffle, reducing network I/O
  3. Cache wisely โ€” Only cache RDDs that are reused across multiple actions
  4. Partition appropriately โ€” Aim for 128MBโ€“200MB per partition
  5. Avoid collect() on large datasets โ€” use take(n) or foreach() instead
  6. Use coalesce() to reduce partitions โ€” avoids full shuffle unlike repartition()
  7. Enable Kryo serialization โ€” 10x faster than Java serialization
  8. Monitor shuffle spill โ€” indicates memory pressure

Key Takeaways

See Also

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-16

โ€”
โ˜†โ˜†โ˜†โ˜†โ˜†
0 ratings

Rate & Feedback

Need Expert PySpark Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement