Skip to content
Bronze 5 min read 2 practice problems ↓

RDDs, DataFrames and Datasets

Spark has three ways to write a job: RDDs, DataFrames and Datasets. Older tutorials and interviews still mention all three. This lesson shows what each one is, the same small job in two of them, when an RDD still makes sense, and what all three share underneath.

Step 2 · Spark internals · Bronze · How a job runs, lesson 2 of 5

Read first: Transformations vs actions (skip if you know it)

In plain words first

Think of giving instructions to a moving company. With an RDD you hand them sealed boxes and say "carry each one, open it, and do this to whatever is inside": they cannot see what is in the boxes, so they cannot plan. With a DataFrame you hand them a labelled inventory, "200 chairs, 50 tables, only take the chairs", and they can plan the cheapest way to do it.

Spark has three APIs. RDDs are the sealed boxes, DataFrames the labelled inventory, and Datasets (Scala and Java only) a typed version of the inventory.

The three APIs

APIWhat it holdsLanguagesOptimised by Catalyst
RDD (2011)Any objects; Spark does not know their structureScala, Java, PythonNo
DataFrame (2015)Rows with a known schema of named, typed columnsScala, Java, Python, R, SQLYes
Dataset (2016)Typed objects with a schema; a DataFrame is Dataset[Row]Scala and Java onlyYes, except inside lambdas

PySpark has RDDs and DataFrames. Datasets need compile-time types, which Python does not have, so in Python the DataFrame is the structured API. Spark Connect (Spark 3.4+) and serverless platforms do not support RDDs at all.

The same job twice

PySparkSpark SQL · Revenue per country
# RDD: Spark sees only "apply this Python function"
revenue = (sales.rdd
    .filter(lambda r: r.amount > 0)
    .map(lambda r: (r.country, r.amount))
    .reduceByKey(lambda a, b: a + b))

# DataFrame: Spark sees filter, group and sum
revenue = (sales
    .filter(F.col("amount") > 0)
    .groupBy("country")
    .agg(F.sum("amount").alias("revenue")))
SELECT country, SUM(amount) AS revenue
FROM sales
WHERE amount > 0
GROUP BY country

When an RDD still makes sense

  • Low-level control of partitioning with a custom partitioner (Scala/Java).
  • Data with no tabular structure at all, processed by arbitrary code (rare; mapInPandas or a Python data source usually covers it in PySpark).
  • Reading legacy code: sc.textFile, mapPartitions, reduceByKey still appear in older jobs and interviews.
  • df.rdd.getNumPartitions() is still the common way to check partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more → counts.

What all three share

Underneath, every DataFrame query becomes RDD operations: the physical plan is executed as RDDs of binary rows. So the core ideas are the same for all three: lazy transformationstransformation: An operation that describes a new DataFrame (filter, select, join) without running anything yet. Learn more →, actionsaction: An operation that needs a result (count, show, write), so Spark has to run the job. Learn more → that trigger jobs, lineage used to recompute lost partitions, narrow and wide dependencies, and stagesstage: A group of steps Spark can run without moving data between machines. A new stage starts at every shuffle. Learn more → split at shufflesshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more →. reduceByKey vs groupByKey is the RDD version of "aggregate before the shuffle": reduceByKey combines values on each executorexecutor: A worker process on a cluster machine that runs tasks and holds data in memory. Learn more → first; groupByKey ships every value across the network.

Tip: if an interviewer asks about RDDs, say what they are, then explain why you would use a DataFrame, mentioning CatalystCatalyst: Spark's query optimizer. It rewrites your DataFrame code into a faster equivalent plan before running it. Learn more →, TungstenTungsten: Spark's engine for storing rows as compact bytes and generating fast code, instead of using Java objects. Learn more → and the Python serialisationserialization: Turning objects into bytes so they can be sent over the network or stored, and back again. Learn more → cost. That is the answer they are looking for.

Try it yourself

Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.

Goal: Write a small aggregation the way it would look in a real job: DataFrame code, written to ParquetParquet: A columnar file format: values of each column are stored together, so queries read only the columns they need. Learn more →.

Production patternPySpark · The DataFrame version, as it would appear in a job
from pyspark.sql import functions as F

sales = spark.createDataFrame(
    [("IN", 120.0), ("IN", -5.0), ("US", 80.0), ("DE", 40.0)], ["country", "amount"])

revenue = (sales.filter(F.col("amount") > 0)
                .groupBy("country")
                .agg(F.sum("amount").alias("revenue")))
revenue.write.mode("overwrite").parquet("lab/rdd_vs_df/revenue")
spark.read.parquet("lab/rdd_vs_df/revenue").orderBy("country").show()

Output from a real run

+-------+-------+
|country|revenue|
+-------+-------+
|     DE|   40.0|
|     IN|  120.0|
|     US|   80.0|
+-------+-------+

What to notice:

  • India's revenue is 120.0, not 115.0: the -5.0 row was filtered out before summing.
  • Three countries in, three rows out: one per group.

Common mistakes

  • Converting to an RDD to do something a DataFrame can do — df.rdd.map(...) loses all optimisation and adds Python serialisation.
  • Thinking Datasets exist in PySpark — They are Scala/Java only; in Python, a DataFrame is the structured API.

Key takeaways

  • RDDs are collections of opaque objects; DataFrames are typed tables Spark understands.
  • Datasets are Scala/Java only; in Python the DataFrame is the structured API.
  • Use an RDD only for legacy code or low-level control; everything tabular belongs in a DataFrame.
  • All three share lineage, lazy transformations, actions and stages split at shuffles.

Interview prep

THE QUESTION

"RDD vs DataFrame: which do you use and why?"

DataFrames, almost always. They have a schema, so Catalyst can optimise the plan (predicate pushdown, column pruning, join selection), Tungsten stores rows compactly, and code generation fuses operators; in PySpark they also avoid sending rows to Python. RDDs give low-level control but none of that. Mention that DataFrames run on RDDs underneath, and that reduceByKey beats groupByKey for the same reason partial aggregation helps groupBy.

Avoid: "DataFrames are faster" without saying why: Catalyst optimises the plan and Tungsten keeps rows in compact binary form, which an RDD of objects cannot get.

Follow-ups · answer out loud, then open

Follow-up"Why is a Python RDD map so much slower than the same logic as DataFrame functions?"
With an RDD, every row is pickled, sent to a Python worker, processed by your function and pickled back; Spark cannot see inside the lambda, so it cannot prune columns, push filters or generate code. DataFrame built-in functions run inside the JVM on binary rows, are optimised by Catalyst and fused by whole-stage code generation. Python only builds the plan.
Scenario"You inherit an RDD job that parses logs with regexes and aggregates them. How would you modernise it?"
Read the files as a DataFrame of lines (spark.read.text), parse with regexp_extract or split, then aggregate with groupBy. Keep a UDF only for logic built-ins cannot express. Validate by comparing outputs on a sample, then compare runtime and shuffle sizes in the Spark UI.
Trap"Datasets are type-safe, so PySpark users should use Datasets."
PySpark has no typed Dataset API; Datasets exist in Scala and Java. In Python, a DataFrame is the API. Even in Scala, typed lambdas on Datasets are opaque to Catalyst, so column expressions are often faster than typed map calls.

Check yourself

3 questions

Which API is not available in PySpark?

Show the answer

Dataset. Typed Datasets need compile-time types, available in Scala and Java.

What happens to a lost partition of a DataFrame on a failed executor?

Show the answer

Spark recomputes it from its lineage. Every API shares lineage: Spark replays the steps that built the lost partition.

Which is a fair reason to still use an RDD today?

Show the answer

Reading legacy code, or custom partitioning in Scala/Java. Everything tabular is faster as a DataFrame; RDDs remain for legacy code and low-level control.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · How a job runs · lesson 3 of 5 · 8 min read
Why DataFrames are faster than RDDs
Column pruning, pushdown, no Python round trip, Tungsten rows and code generation: five reasons, and how one lambda switches them off.

Related lessons

Previous: Transformations vs actions

Primary sources: RDD programming guide · SQL, DataFrames and Datasets