Fault tolerance: lineage, recomputation & checkpointing
Apache Spark · Spark Architecture
Theory
Spark does not copy your data to survive failures. Instead every RDD and DataFrame remembers its lineage: the chain of transformations that produced it from the source. If an executor dies and a partition is lost, the driver simply reruns those steps for that partition only, on another executor. A lost shuffle output forces the map tasks that wrote it to run again, and the same mechanism is why an uncached RDD is recomputed by every action.
Long lineages (loops, iterative algorithms) make recovery and planning slow. Checkpointing fixes that: rdd.checkpoint() or df.checkpoint() writes the data to reliable storage set with sc.setCheckpointDir (HDFS or S3 on a cluster) and replaces the lineage with a read of those files. localCheckpoint() is faster but stores data on executors, so it is not fault tolerant. cache() keeps the lineage and only speeds up reuse. For example, after checkpointing, the lineage of a mapped RDD changes from PythonRDD <- ParallelCollectionRDD to PythonRDD <- ReliableCheckpointRDD.
Why we use it
Lineage is how Spark recovers from failures cheaply, and interviewers often ask how Spark is fault tolerant without replication, and what the difference between cache and checkpoint is. Checkpointing prevents stack overflows and very slow plans in iterative jobs.
When to use it
Rely on lineage for normal jobs. Use cache() when the same data is reused in one job. Use checkpoint() when lineage grows very long (loops, iterative ML, graph algorithms) or when recomputation is expensive; cache first so the checkpoint is not computed twice. Streaming checkpoints are a separate feature for query progress.
How it works
- Executor holding partition 3 is lost
- Driver sees the task failures for that executor
- Partition checkpointed or cached elsewhere? Yes: Read that copy. No: Walk the lineage back to the source.
- Recompute only the missing partitions on healthy executors
- Shuffle output lost too? Yes: Rerun the parent map tasks. No: Read existing shuffle files.
- Job continues with the rebuilt partitions
Syntax
sc.setCheckpointDir("hdfs:///tmp/checkpoints")
rdd.cache(); rdd.checkpoint(); rdd.count() # written on the first action
rdd.isCheckpointed(); rdd.toDebugString()
df2 = df.checkpoint() # eager by default, returns a new DataFrame
df3 = df.localCheckpoint() # faster, NOT fault tolerantExample
import re, tempfile
from pyspark.sql import SparkSession, functions as F
spark = (SparkSession.builder.master("local[2]")
.config("spark.ui.enabled", "false")
.getOrCreate())
sc = spark.sparkContext
sc.setCheckpointDir(tempfile.mkdtemp()) # reliable storage (HDFS/S3 on a cluster)
def lineage(rdd): # RDD class names, child -> parent
return re.findall(r"(\w+RDD)\[", rdd.toDebugString().decode())
calls = sc.accumulator(0) # counts how often map() really runs
def to_pair(line):
calls.add(1)
region, amount = line.split(",")
return region, float(amount)
# 1) Lineage: each RDD remembers its parent and the function that built it
lines = sc.parallelize(["North,55000", "West,30000", "North,1500", "South,52000"], 2)
big = lines.map(to_pair).filter(lambda kv: kv[1] > 10000)
print("lineage:", lineage(big))
# 2) No cache, no checkpoint: every action replays the lineage from the source
big.count(); big.count()
print("map calls after 2 actions:", calls.value) # 4 rows x 2 actions
# 3) cache + checkpoint: computed once, saved to files, lineage cut
calls.value = 0
big.cache() # cache first, so the checkpoint job does not recompute
big.checkpoint()
big.count() # computes, caches and writes the checkpoint files
big.count() # served from cache, no recomputation
print("map calls after 2 more actions:", calls.value)
print("checkpointed:", big.isCheckpointed())
print("lineage after checkpoint:", lineage(big))
# 4) DataFrames: checkpoint() returns a new DataFrame whose plan starts from saved data
orders = spark.createDataFrame([("North", 55000.0), ("West", 30000.0), ("North", 1500.0)],
"region STRING, amount DOUBLE")
agg = orders.groupBy("region").agg(F.sum("amount").alias("sales"))
saved = agg.checkpoint() # eager by default
print("plan root before:", agg._jdf.queryExecution().optimizedPlan().nodeName())
print("plan root after :", saved._jdf.queryExecution().optimizedPlan().nodeName())
saved.orderBy("region").show()
# Output:
# lineage: ['PythonRDD', 'ParallelCollectionRDD']
# map calls after 2 actions: 8
# map calls after 2 more actions: 4
# checkpointed: True
# lineage after checkpoint: ['PythonRDD', 'ReliableCheckpointRDD']
# plan root before: Aggregate
# plan root after : LogicalRDD
# +------+-------+
# |region| sales|
# +------+-------+
# | North|56500.0|
# | West|30000.0|
# +------+-------+
Key points
- Lineage = recipe to rebuild any lost partition; no data replication needed
- Only the lost partitions are recomputed, not the whole dataset
- Without cache, every action replays the lineage from the source
- checkpoint() saves to reliable storage and cuts the lineage
- cache() keeps lineage; checkpoint() replaces it; localCheckpoint() is not durable
- Call cache() before checkpoint() to avoid computing the data twice