RDDs (Resilient Distributed Datasets) are Spark's fundamental abstraction — an immutable, partitioned collection of records that can be operated on in parallel.

Put more precisely, an RDD is not the data itself but a recipe for it: a list of partitions, a function that computes each partition from the partitions of its parents, and the list of those parents. Executors hold the actual records only while they compute them, or longer if you ask Spark to cache them. Because the recipe is kept, any partition that goes missing can be computed again, and that is the "resilient" in the name.

Transformations like map, filter, and flatMap are lazy: they build a DAG of dependencies without executing until an action (like reduce or collect) triggers computation.

This pipeline model enables Spark to optimize execution by fusing transformations, minimizing data shuffles, and recovering from failures using lineage information.

Step through the pipeline below: the first four steps only build the DAG, and nothing runs until collect() asks for a result. Click a source record to change its value, click any other record to follow its key through every column, and switch map-side combine off to see how many more records the shuffle has to move.

Six partitions of key–value records on three machines flow through mapValues, filter and reduceByKey: the DAG stays lazy until collect(), then each partition maps, filters, combines and sorts locally, the records shuffle to the partition their key hashes to, and the reduced sums arrive at the driver.

What an RDD is made of

The original paper (Zaharia et al., NSDI 2012) and the RDD class in Spark's source describe every RDD through the same five properties:

  1. Partitions: the pieces the dataset is split into. One partition is processed by one task, so the partition count is the upper bound on parallelism for that step.
  2. A compute function: given a partition, it produces an iterator of records, usually by pulling records from the parent's iterator and transforming them.
  3. Dependencies on parent RDDs, each either narrow or wide.
  4. Optionally, a partitioner for key–value RDDs: the rule that says which partition a key lives in, such as hash or range partitioning.
  5. Optionally, preferred locations for each partition, for example the hosts holding an HDFS block, so the scheduler can run the task next to its data.

Nothing in that list is mutable. A transformation never changes an RDD; it creates a new one whose parent is the old one. That is what makes the lineage trustworthy: the recipe for a partition still describes the same data an hour later.

Transformations and actions

A transformation returns a new RDD and does no work: map, filter, flatMap, mapValues, union, reduceByKey, join, distinct, repartition. An action returns a result to the driver or writes it out: collect, count, take, reduce, foreach, saveAsTextFile. Each action submits one job to the scheduler, which walks the lineage back from the final RDD and decides what to run.

Laziness is what lets the scheduler see the whole chain before it commits to a plan. A map followed by a filter does not produce an intermediate dataset: in one task, each record is read, doubled and tested before the next record is touched. If an action only needs the first few records, as take does, Spark can stop after scanning a few partitions.

The flip side is that nothing is shared between actions unless you say so. Calling count() and then collect() on the same uncached RDD reads the source and runs every transformation twice.

A worked example: the pipeline in the panel

The panel runs rdd.mapValues(_ * 2).filter(_._2 < 8).reduceByKey(_ + _).collect(). The source holds 1818 key–value records in 66 partitions spread over 33 machines.

The first steps only build the DAG. When collect() arrives, every partition runs mapValues and filter back to back in memory. The filter keeps the records whose doubled value is below 88, which leaves 1717 of 1818 records. This is stage 0 in the panel, a pipeline of narrow dependencies.

Then comes the barrier. reduceByKey needs every value of a key in one place, and the values of one key are spread over several partitions. With map-side combine on, each partition first sums its own values per key, so 1111 partial sums are written for the shuffle instead of 1717 records, and 66 of them have to move to a different partition. Switch combine off, which is what groupByKey effectively does, and 1717 records go into the shuffle, 1010 of them moving. On real data the saving grows with the number of records per key in each partition: a thousand values of one key in one partition leave that partition as a single partial sum.

Each reduce partition then merges what it received and produces the final sum per key. The driver collects 66 keys. That second half is stage 1: it cannot start any task until every map task of stage 0 has written its shuffle output.

Narrow and wide dependencies

The split into two stages is not a property of reduceByKey as such but of the dependency it creates. In a narrow dependency each child partition reads at most one partition of each parent (map, filter, mapValues, union, or coalesce without a shuffle). The child can be computed as soon as its own parent partition exists, on the same executor, without touching the network.

In a wide dependency, also called a shuffle dependency, a child partition needs records from many or all parent partitions (groupByKey, reduceByKey, distinct, repartition, sortByKey, and join or cogroup when the inputs are not already partitioned the same way). Every parent partition writes its output split by target partition to local disk, and every child task fetches its slice from all of them. That exchange is the shuffle.

The DAG scheduler article shows how Spark cuts a job into stages at exactly these points, and the fault tolerance article shows why the shuffle files written at a stage boundary double as recovery points.

A partitioner can turn a would-be shuffle into a narrow dependency. If two RDDs were both partitionBy the same HashPartitioner with the same number of partitions, joining them needs no exchange: partition 3 of one side meets partition 3 of the other. mapValues preserves the parent's partitioner because it cannot change keys; map drops it, because Spark cannot know whether your function changed them.

Map-side combine and the shuffle

reduceByKey, aggregateByKey, foldByKey and combineByKey all apply a combiner on the map side. The rule they impose is that the merge function is associative, so partial results can be merged in any grouping. groupByKey cannot combine because it promises the reducer the full list of values, and the combined list is just as big as the original records.

In Spark's sort-based shuffle, each map task writes one data file, ordered by target partition, and an index file that says where each target's slice begins. A reduce task asks every map output for its slice, through the executor that wrote it or through the external shuffle service, and merges the streams. The panel's step that sorts each partition by key before the move shows the same idea at small scale: ordered runs are cheap to merge on the receiving side.

Caching and persistence

rdd.cache() is persist(StorageLevel.MEMORY_ONLY): the first action that computes a partition keeps it in executor memory, and later actions reuse it. Other levels spill to disk (MEMORY_AND_DISK), store serialized bytes to save space at the cost of CPU (MEMORY_ONLY_SER), or keep two replicas on different executors (the _2 variants). A cached partition that is evicted or lost with its executor is not an error; Spark recomputes it from lineage the next time it is needed.

Caching is worth it when an RDD is used by more than one action, or many times inside a loop, as in iterative machine-learning algorithms. It is wasted memory for an RDD read once. Release it with unpersist() when you are done, because cached blocks also keep executors alive under dynamic allocation.

How many partitions

An RDD read from files gets one partition per input split, roughly one per HDFS block or object-store chunk. A shuffle produces as many partitions as you request, or spark.default.parallelism, which on a cluster defaults to the total number of executor cores or 2, whichever is larger. Too few partitions leave cores idle and make each task's memory footprint large; too many add scheduling overhead and produce many tiny shuffle blocks. Spark's tuning guide recommends two to three tasks per CPU core as a starting point; task durations in the Spark UI tell you which way to adjust.

repartition(n) always shuffles and balances partitions evenly. coalesce(n) merges existing partitions without a shuffle, which is cheap but can leave the remaining partitions uneven, and with a small n it lowers the parallelism of everything upstream in the same stage.

RDDs, DataFrames and Datasets

DataFrames and Datasets compile down to RDDs: the physical plan Spark SQL produces runs as RDD operations over internal binary rows. The difference is what the optimizer can see. A lambda passed to map is a black box, while a column expression in a DataFrame can be pushed into the file reader, pruned, reordered and compiled into Java bytecode. For structured data the DataFrame API is faster and shorter.

The RDD API is still the right tool for unstructured records, custom partitioning logic, or algorithms that need explicit control over what runs where. It is also the right mental model for reading any Spark job, because the stages and tasks in the Spark UI are RDD stages and tasks whichever API produced them.

Common pitfalls

  • collect() on a large RDD. It brings every record to the driver and is a common cause of driver out-of-memory errors. Use take, count, an aggregation, or write the result out instead.
  • groupByKey followed by a sum or count. Use reduceByKey or aggregateByKey, which combine on the map side.
  • Mutating driver variables inside a closure. The closure is serialized and shipped to executors; each task changes its own copy, and the driver's variable stays unchanged. Use an accumulator for counters, and an aggregation for anything that matters.
  • Reusing an RDD without caching it. Each action recomputes the whole lineage, including reading the source again.
  • Non-deterministic transformations. A partition recomputed after a failure must produce the same records. Random sampling without a seed, or logic that depends on the order records arrive in after a shuffle, can make a recomputed partition differ from the one it replaces.
  • Skewed keys. One key with most of the records makes one reduce task do most of the work. Salting the key, or pre-aggregating, spreads it.

Short answers

What is an RDD in Spark?

A Resilient Distributed Dataset is an immutable collection of records split into partitions that executors process in parallel. Each RDD knows its parent RDDs and the function that derives it from them, so Spark can rebuild any lost partition from that lineage instead of replicating the data.

What is the difference between a transformation and an action in Spark?

A transformation such as map, filter or reduceByKey returns a new RDD and only records a step in the plan. An action such as collect, count or saveAsTextFile returns a value to the driver or writes output, and it is the action that makes Spark run a job.

Why are Spark transformations lazy?

Because Spark can plan better when it sees the whole chain. Waiting for an action lets the scheduler fuse consecutive narrow transformations into one pass over each partition, cut stages only where data must move, and skip work whose result nobody asked for.

What is the difference between reduceByKey and groupByKey?

reduceByKey merges values with the same key inside each partition before the shuffle, so only one partial result per key and partition crosses the network. groupByKey ships every record and builds the full list of values on the reduce side, which moves more data and can run an executor out of memory on a hot key.

What is the difference between narrow and wide dependencies in Spark?

In a narrow dependency each partition of the child reads at most one partition of each parent, as in map or filter, so the work runs in place. In a wide dependency a child partition reads from many parent partitions, as in groupByKey or a join of differently partitioned inputs, which requires a shuffle and starts a new stage.

Should I use RDDs or DataFrames?

DataFrames and Datasets for almost all new code: the Catalyst optimizer and Tungsten execution can reorder, prune and generate code for them, which they cannot do for opaque RDD lambdas. RDDs remain the execution layer underneath and the API for unstructured data or precise control over partitioning. Spark Connect clients do not support the RDD API at all.

Further reading

  • M. Zaharia, M. Chowdhury, T. Das, A. Dave, J. Ma, M. McCauley, M. J. Franklin, S. Shenker, I. Stoica, "Resilient Distributed Datasets: A Fault-Tolerant Abstraction for In-Memory Cluster Computing", NSDI 2012. The paper that introduced RDDs, lineage and narrow and wide dependencies.
  • Apache Spark documentation, RDD Programming Guide. Transformations, actions, persistence levels, shared variables and the shuffle.
  • B. Chambers, M. Zaharia, Spark: The Definitive Guide, O'Reilly, 2018. Part III covers the low-level RDD API.
  • J. Dean, S. Ghemawat, "MapReduce: Simplified Data Processing on Large Clusters", OSDI 2004. The map, combine, shuffle and reduce model that reduceByKey inherits.
  • M. Armbrust et al., "Spark SQL: Relational Data Processing in Spark", SIGMOD 2015. How DataFrames are optimized and compiled down to RDD execution.
  • On this site: the DAG scheduler, fault tolerance via lineage and dynamic executor allocation on YARN.