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

  1. Executor holding partition 3 is lost
  2. Driver sees the task failures for that executor
  3. Partition checkpointed or cached elsewhere? Yes: Read that copy. No: Walk the lineage back to the source.
  4. Recompute only the missing partitions on healthy executors
  5. Shuffle output lost too? Yes: Rerun the parent map tasks. No: Read existing shuffle files.
  6. 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 tolerant

Example

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

Apache Spark topics

Spark Fundamentals

Spark Architecture

RDDs

DataFrames

Aggregations & Joins

Spark SQL

Window Functions

Cleaning & Complex Types

UDFs

Performance Tuning

Structured Streaming

MLlib & Ecosystem

Interview Prep

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Master Apache Spark

PySpark and Spark SQL from the ground up: DataFrames, joins, window functions, partitions and performance tuning, Structured Streaming and more. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice PySpark Write real PySpark — DataFrames, joins, window functions and Spark SQL — in a live editor with hidden tests and instant checking. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Spark  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

{{ sec.h }}

{{ sec.body }}

{{ sec.body }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
On screen — where to click

{{ rich.ui.title }}

{{ u.text }}
  1. {{ st.n }}{{ st.text }}
{{ rich.ui.title }}
{{ u.text }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
Want to run this yourself? Try the same API on Practice PySpark Online right in your browser, or run it locally after pip install pyspark (needs Java 17+), or paste it into a Databricks Free Edition notebook.
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic