What you will be able to do
- Explain how a DataFrame relates to a Dataset, and why PySpark exposes only DataFrames
- Create, reuse, configure and stop a SparkSession with the builder, and say how it relates to the SparkContext
- Cache and persist a DataFrame, predict when the data is stored, and release it with unpersist()
- Choose a storage level by trading memory against CPU and disk
- Explain where garbage-collection pressure in executors comes from and how serialized and columnar caching reduce it
Key concept
DataFrame = Dataset[Row] — A DataFrame is a Dataset whose elements are untyped Rows with a named-column schema. Typed Datasets exist only in Scala and Java. Every structured API, SQL included, runs on the same optimized execution engine, so the choice of API changes how you write code, not how Spark runs it.
1.DataFrames, Datasets and the Row type
Spark SQL's structured APIs tell Spark two things the plain RDD API hides: the structure of the data and the computation being performed. Spark uses that information to optimize further. Two abstractions carry the structure. A Dataset is a distributed collection built from JVM objects and transformed with functional operations such as map, flatMap and filter. It combines the strong typing and lambda functions of RDDs with Spark SQL's optimized execution engine. A DataFrame is a Dataset organized into named columns, the equivalent of a table in a relational database.
These are one abstraction, not two engines. In Scala, DataFrame is only a type alias for Dataset[Row]. Java has no alias, so you write Dataset<Row>. A Row is the untyped case: the schema names the columns, but the element type is a generic row instead of one of your own classes. Whichever API or language you use, Spark computes the result on the same execution engine. A Scala team can therefore move between SQL strings, DataFrame code and typed Dataset code in one pipeline and pick whichever fits each step best.
The typed API does not exist in every language. The Dataset API is available in Scala and Java only, and Python has none. That is why a PySpark program only ever holds DataFrame objects. No method call or configuration flag turns them into typed Datasets. Python loses less than it seems: because the language is dynamic, you still access a row's field by name with row.columnName. R works the same way. DataFrames can be built from structured files, Hive tables, external databases or existing RDDs, and the DataFrame API is available in Python, Scala, Java and R.
| Language | DataFrame API | Typed Dataset API | How a DataFrame is expressed |
|---|---|---|---|
| Scala | Yes | Yes | Type alias of Dataset[Row] |
| Java | Yes | Yes | Dataset<Row> |
| Python | Yes | No | DataFrame; fields reachable as row.columnName |
| R | Yes | No | DataFrame |
Checkpoint 1 of 8· Check yourself
A PySpark developer wants their records as a typed collection of their own Person class, the way a Scala colleague uses Dataset[Person]. What should they do?
The typed Dataset API exists only in Scala and Java, so no conversion call or flag produces one in PySpark. Because Python is dynamic, fields are still reachable by name as row.columnName. R also has DataFrames only.
“The Dataset API is available in Scala and Java. Python does not have the support for the Dataset API.”Source: spark.apache.org
Checkpoint 2 of 8· Exam question
A developer new to PySpark asks why their code only ever produces DataFrame objects and never a typed Dataset[Row] the way equivalent Scala examples do. Which explanation is accurate?
Correct answer: A — The typed Dataset API is a compile-time JVM feature; PySpark is dynamically typed, so it exposes only the untyped DataFrame, itself Dataset[Row] under the hood.
- A. This is correct: the compile-time type safety that Datasets provide relies on JVM generics and encoders, which Python's dynamic typing cannot support, so PySpark only surfaces the untyped
DataFrame, itself internally represented asDataset[Row]. - B. No such
.as[T]mechanism with Python dataclasses exists in PySpark; the typed Dataset API is not reachable from Python code by any method call. - C. Datasets were not deprecated; they remain fully supported in Scala and Java, where compile-time typing makes the encoder-based API practical to implement.
- D. The objects are not identical across languages: Scala's
Dataset[T]carries a compile-time type parameter and encoder, while Python'sDataFramecarries neither, so the difference is more than naming. - E. No such configuration flag exists in Spark or Databricks Runtime; the absence of typed Datasets in PySpark is a language-level limitation, not a toggle.
2.The SparkSession: building, reusing and stopping it
The SparkSession is the entry point to the Dataset and DataFrame API. Through it you create DataFrames, register them as tables, run SQL, cache tables and read Parquet files. Its properties lead to everything else: read and readStream for sources, catalog for databases and tables, conf for runtime configuration, udf for function registration and streams for active streaming queries.
Inside every classic session sits a SparkContext. The driver is the process that runs your main() function, and its SparkContext acquires and coordinates the application's executors (see Driver, worker nodes, executors and the cluster manager). The session lives in that driver and wraps the context. spark.sparkContext returns the underlying SparkContext, in classic mode only, and spark.stop() stops it. You never build a SparkContext first and derive a session from it. The older pattern was to build a SparkConf, pass it to a SparkContext and stop that context before creating another, because only one SparkContext should be active per JVM. The builder now does this for you, and it also takes over Hive access through enableHiveSupport().
spark = (
SparkSession.builder
.master("local")
.appName("Word Count")
.config("spark.some.config.option", "some-value")
.getOrCreate()
)getOrCreate() does what its name says. It first checks for a valid global default SparkSession. If one exists, it returns that object and applies the builder's options to it. Only if none exists does it create a session and register it as the new default. Passing a different appName therefore never forces a fresh session: in a notebook that already has spark, the builder hands back spark itself. conf.set() can still change runtime settings afterwards.
s1 = SparkSession.builder.config("k1", "v1").getOrCreate()
s1.conf.get("k1") == "v1"
# True
# The configuration of the SparkSession can be changed afterwards.
s1.conf.set("k1", "v1_new")
s1.conf.get("k1") == "v1_new"
# True
# When an existing SparkSession is returned, the config options specified
# in this builder are applied to the existing SparkSession.
s2 = SparkSession.builder.config("k2", "v2").getOrCreate()
s1.conf.get("k1") == s2.conf.get("k1") == "v1_new"
# True
s1.conf.get("k2") == s2.conf.get("k2") == "v2"
# TrueThree calls cover the cases where you do want something new or want to finish:
builder.create()skips the check, builds a new session and makes it the default.spark.newSession()returns a session with its own SQLConf, temporary views and UDFs, but it shares the SparkContext and the table cache.spark.stop()stops the underlying SparkContext. That ends the application, whose executors otherwise stay up for its whole duration.
Checkpoint 3 of 8· Match them up
A notebook already has an active spark session. Match each call to what it does.
Tap a term, then the definition that fits it.
Only create() forces a new default session. getOrCreate() reuses the valid session that already exists. newSession() isolates the SQL configuration, views and UDFs but keeps the same SparkContext. stop() shuts down the SparkContext and so ends the whole application.
“Returns a new SparkSession with separate SQLConf, registered temporary views, and UDFs, but shared SparkContext and table cache.”Source: docs.databricks.com
Checkpoint 4 of 8· Exam question
Which statement correctly describes the relationship between SparkSession and SparkContext in current Spark releases?
Correct answer: A — SparkSession wraps a SparkContext internally and exposes it through spark.sparkContext, unifying the older SQLContext and HiveContext entry points into one object.
- A. This is correct: since Spark 2.0,
SparkSessionis the single entry point and internally holds aSparkContext, accessible viaspark.sparkContext, replacing the need for separateSQLContextandHiveContextobjects. - B. This reverses the actual containment.
SparkContextdoes not wrap or create aSparkSession; insteadSparkSession.builder.getOrCreate()creates or reuses theSparkContextunder the hood. - C. Both objects live in the same driver process and share the same cluster manager connection. There is no scenario in the current architecture where they connect independently.
- D.
SparkContextstill exists and is reachable throughspark.sparkContext; it was not removed, only wrapped so most applications no longer need to instantiate it directly. - E.
SparkSessiondoes more than manage catalog metadata: it is the unified entry point for DataFrame, SQL, and (via its internal context) RDD execution, so no separate context needs manual configuration.
Checkpoint 5 of 8· Exam question
A shared Databricks notebook already has an active SparkSession when a second cell runs the following code:
spark2 = SparkSession.builder.appName("secondary-analysis").getOrCreate()
print(spark2 is spark)
What does this print, and why?
Correct answer: A — True, because getOrCreate() detects the existing active session for the JVM and returns that same object instead of constructing a new one, regardless of the appName passed.
- A. This is correct behavior:
getOrCreate()checks for an active session on the current thread/JVM and returns it if one exists, sospark2 is sparkevaluates toTrueand theappNameargument on the second call is ignored. - B. The
appNameargument only applies when a new session is actually being built; it has no effect on an already-active session and does not trigger a teardown-and-recreate cycle. - C. There is no duplication of the underlying
SparkContext:getOrCreate()returns the identical object, so only oneSparkContextand its memory footprint exist, not two. - D. Databricks notebook cells in the same attached cluster session share the same driver JVM, so they can and do reference the same
SparkSessionobject across cells. - E. Calling
getOrCreate()multiple times is the documented, safe way to obtain the current session; it does not raise an exception on repeated calls within the same JVM.
3.cache(), persist() and unpersist()
Caching lets you choose one DataFrame and keep it in memory across actions, where Spark would otherwise recompute it from the source each time (the general idea is In-memory processing). When a dataset is persisted, each node stores the partitions it computes and reuses them in later actions on that dataset or on datasets derived from it. Those later actions often run more than ten times faster, which matters most for iterative algorithms and interactive exploration.
Calling cache() stores nothing on its own. It marks the DataFrame for persistence. The data is kept only the first time an action computes it. In the program below, the first count() reads the file, filters it and fills the cache along the way. The second count() filters the cached lines in memory.
logData = spark.read.text(logFile).cache()
numAs = logData.filter(logData.value.contains('a')).count()
numBs = logData.filter(logData.value.contains('b')).count()
print("Lines with a: %i, lines with b: %i" % (numAs, numBs))
spark.stop()cache() is persist() with the default storage level, and persist(level) lets you pick another. The default depends on the API. A DataFrame defaults to MEMORY_AND_DISK_DESER, adopted in Spark 3.0 to match Scala. An RDD's cache() uses MEMORY_ONLY. persist() assigns a level only if the DataFrame has none yet, so calling it a second time with a different level does not replace the first. Spark SQL also caches by name: spark.catalog.cacheTable("tableName"). spark.catalog.listCachedTables() lists only named entries, not DataFrames cached without a name.
Cached data leaves in two ways. Spark watches cache usage on each node and evicts old partitions in least-recently-used order. unpersist() (or uncacheTable() for a named table) removes the data at once. It does not block by default; pass blocking=true to wait until the resources are freed. Release caches explicitly, because a cache is not private to the code that made it: cached data is shared across all Spark sessions on the cluster.
A cache only ever saves time. If a cached partition is lost, Spark rebuilds it from the transformations that created it (Fault tolerance through lineage recomputation), and the same applies when a worker is decommissioned and its cache disappears. A query over a half-evicted cache still returns correct results, just more slowly. Cached blocks also share the executor's unified memory with execution, as described in Executor and driver memory, spill and cluster sizing.
Checkpoint 6 of 8· Check yourself
After logData = spark.read.text(logFile).cache() runs, two count() actions follow. When does Spark read the file and store the cached partitions?
cache() only marks the DataFrame for persistence. The first action that computes it stores the partitions, and later actions reuse them. Naming a table is not required for DataFrame caching.
“Sets the storage level to persist the contents of the DataFrame across operations after the first time it is computed.”Source: spark.apache.org
4.Storage levels: trading memory against CPU and disk
A storage level answers three questions: where a partition lives, in what form, and how many copies exist. The answers trade memory against CPU. Deserialized objects are fastest to use but take the most space. Serialized bytes are compact but cost CPU each time they are read. Disk adds room at the price of I/O.
| Level | Form and location | If a partition does not fit in memory |
|---|---|---|
| MEMORY_ONLY | Deserialized Java objects in the JVM | Not cached; recomputed each time it is needed |
| MEMORY_AND_DISK | Deserialized Java objects in the JVM | Stored on disk and read back from there |
| MEMORY_ONLY_SER (Java and Scala) | Serialized, one byte array per partition | Recomputed on the fly |
| MEMORY_AND_DISK_SER (Java and Scala) | Serialized, one byte array per partition | Spilled to disk |
| DISK_ONLY | Partitions on disk only | Not applicable |
| MEMORY_ONLY_2, MEMORY_AND_DISK_2, etc. | As the base level, replicated on two cluster nodes | As the base level |
| OFF_HEAP (experimental) | Like MEMORY_ONLY_SER, in off-heap memory | Requires off-heap memory to be enabled |
df1 = spark.range(10)
df1.storageLevel
# StorageLevel(False, False, False, False, 1)
df1.cache().storageLevel
# StorageLevel(True, True, False, True, 1)
df2 = spark.range(5)
df2.persist(StorageLevel.DISK_ONLY_2).storageLevel
# StorageLevel(True, False, False, False, 2)df1.cache() prints StorageLevel(True, True, False, True, 1), the same value as persist()'s default signature. That shows cache() really is persist() with the default level. To choose a level deliberately:
- If the data fits comfortably at MEMORY_ONLY, keep it there. It is the most CPU-efficient level.
- If not, in Java or Scala, try MEMORY_ONLY_SER with a fast serialization library to save space while keeping access reasonably fast.
- Spill to disk only when the computation was expensive or filtered out much of the data. Otherwise recomputing a partition may be as fast as reading it from disk.
- Use a replicated
_2level when tasks must keep running without waiting for a lost partition to be recomputed, for example when Spark serves requests for a web application.
Every level is fully fault tolerant through recomputation. Replication buys speed of recovery, not safety. Python RDDs add one twist: stored objects are always serialized with Pickle, so choosing a serialized level makes no difference for them. The levels offered for Python RDDs are MEMORY_ONLY, MEMORY_ONLY_2, MEMORY_AND_DISK, MEMORY_AND_DISK_2, DISK_ONLY, DISK_ONLY_2 and DISK_ONLY_3.
Checkpoint 7 of 8· Match them up
Each situation below calls for a different storage level. Match each level to the situation it suits best.
Tap a term, then the definition that fits it.
Use MEMORY_ONLY when the data fits. In Java or Scala, MEMORY_ONLY_SER saves space. Spilling to disk is worth it only when recomputing a partition would be expensive. A replicated _2 level speeds up recovery, but it does not add safety, because every level recovers lost data by recomputing it.
“Use the replicated storage levels if you want fast fault recovery (e.g. if using Spark to serve requests from a web application).”Source: spark.apache.org
5.Garbage collection pressure in executors
Each executor is a JVM, and tasks from different applications run in different JVMs. Anything a task keeps on the heap is therefore something that JVM's garbage collector must track and eventually reclaim. Two kinds of data drive that work: large caches of objects that live a long time, and the many short-lived objects that tasks create while they run.
Large caches are where the storage level matters. A deserialized level such as MEMORY_ONLY keeps every record as its own Java object on the heap. A serialized level packs each partition into one byte array, so a cache that held millions of small objects becomes a handful of large ones and the collector has far less to trace. The cost is CPU, because each read has to deserialize. Caching a DataFrame has a similar effect: Spark SQL caches tables in an in-memory columnar format, scans only the columns a query needs and tunes compression automatically to minimize memory usage and GC pressure. Two settings control this:
spark.sql.inMemoryColumnarStorage.compressed(defaulttrue) picks a compression codec for each column from data statistics.spark.sql.inMemoryColumnarStorage.batchSize(default10000) sets the batch size. Larger batches compress better but risk out-of-memory errors while caching.
Short-lived objects come mostly from shuffles. reduceByKey and aggregateByKey build in-memory structures on the map side, and 'ByKey operations build them on the reduce side. When those structures outgrow memory, Spark spills them to disk, paying for the disk I/O and for more garbage collection. Garbage collection also controls cleanup. Shuffle files stay on disk until the RDDs that produced them are no longer used and have been collected. A long-running application that holds references to old datasets, or whose GC rarely runs, can fill its spark.local.dir with them.
When an executor runs out of memory completely, Spark removes it and retries its tasks. The job slows down, and after repeated failures the stage and then the job fail. Unpersisting caches you no longer need, preferring serialized or columnar forms for large ones, and dropping references to finished datasets all reduce how much the collector has to handle.
Checkpoint 8 of 8· Check yourself
Hours into a long-running Spark application, the disk under spark.local.dir keeps filling with shuffle files from stages that finished long ago. The driver code still holds references to many old intermediate datasets. What best explains this and fixes it?
Spark keeps shuffle files on disk until the datasets that produced them are no longer used and have been collected. Old references, or a GC that rarely runs, keep them around and fill spark.local.dir. Dropping references to finished datasets lets them be cleaned up.
“these files are preserved until the corresponding RDDs are no longer used and are garbage collected.”Source: spark.apache.org
Sources
(11)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://spark.apache.org/docs/latest/sql-programming-guide.htmlSecondary source
“In the Scala API, DataFrame is simply a type alias of Dataset[Row].”
↩︎ DataFrames, Datasets and the Row type“When computing a result, the same execution engine is used, independent of which API/language you are using to express the computation.”
↩︎ DataFrames, Datasets and the Row type“The Dataset API is available in Scala and Java. Python does not have the support for the Dataset API.”
↩︎ DataFrames, Datasets and the Row type“In the Scala API, DataFrame is simply a type alias of Dataset[Row].”
↩︎ Key concept“The Dataset API is available in Scala and Java. Python does not have the support for the Dataset API.”
↩︎ Exam trap 1 - 2.
“The entry point to programming Spark with the Dataset and DataFrame API.”
↩︎ DataFrames, Datasets and the Row type“Returns the underlying SparkContext. Classic mode only.”
↩︎ The SparkSession: building, reusing and stopping it“Returns a new SparkSession with separate SQLConf, registered temporary views, and UDFs, but shared SparkContext and table cache.”
↩︎ The SparkSession: building, reusing and stopping it - 3.https://docs.databricks.com/aws/en/pyspark/reference/classes/sparksession/builder/getOrCreateOfficial docs
“This method first checks whether there is a valid global default SparkSession and, if so, returns that one.”
↩︎ The SparkSession: building, reusing and stopping it“When an existing SparkSession is returned, the config options specified in this builder are applied to it.”
↩︎ The SparkSession: building, reusing and stopping it“This method first checks whether there is a valid global default SparkSession and, if so, returns that one.”
↩︎ Exam trap 2 - 4.
“Enables Hive support, including connectivity to a persistent Hive metastore.”
↩︎ The SparkSession: building, reusing and stopping it - 5.https://spark.apache.org/docs/latest/rdd-programming-guide.htmlSecondary source
“Only one SparkContext should be active per JVM. You must stop() the active SparkContext before creating a new one.”
↩︎ The SparkSession: building, reusing and stopping it“This allows future actions to be much faster (often by more than 10x).”
↩︎ cache(), persist() and unpersist()“The first time it is computed in an action, it will be kept in memory on the nodes.”
↩︎ cache(), persist() and unpersist()“if any partition of an RDD is lost, it will automatically be recomputed using the transformations that originally created it.”
↩︎ cache(), persist() and unpersist()“To block until resources are freed, specify blocking=true when calling this method.”
↩︎ cache(), persist() and unpersist()“storage levels are meant to provide different trade-offs between memory usage and CPU efficiency”
↩︎ Storage levels: trading memory against CPU and disk“Otherwise, recomputing a partition may be as fast as reading it from disk.”
↩︎ Storage levels: trading memory against CPU and disk“All the storage levels provide full fault tolerance by recomputing lost data”
↩︎ Storage levels: trading memory against CPU and disk“In Python, stored objects will always be serialized with the Pickle library, so it does not matter whether you choose a serialized level.”
↩︎ Storage levels: trading memory against CPU and disk“Store RDD as serialized Java objects (one byte array per partition).”
↩︎ Garbage collection pressure in executors“This is generally more space-efficient than deserialized objects, especially when using a fast serializer, but more CPU-intensive to read.”
↩︎ Garbage collection pressure in executors“spill these tables to disk, incurring the additional overhead of disk I/O and increased garbage collection”
↩︎ Garbage collection pressure in executors“if the application retains references to these RDDs or if GC does not kick in frequently”
↩︎ Garbage collection pressure in executors“The first time it is computed in an action, it will be kept in memory on the nodes.”
↩︎ Exam trap 3“Use the replicated storage levels if you want fast fault recovery (e.g. if using Spark to serve requests from a web application).”
↩︎ Checkpoint“these files are preserved until the corresponding RDDs are no longer used and are garbage collected.”
↩︎ Checkpoint - 6.https://spark.apache.org/docs/latest/cluster-overview.htmlSecondary source
“coordinated by the SparkContext object in your main program (called the driver program)”
↩︎ The SparkSession: building, reusing and stopping it“tasks from different applications run in different JVMs”
↩︎ Garbage collection pressure in executors - 7.https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.DataFrame.persist.htmlSecondary source
“This can only be used to assign a new storage level if the DataFrame does not have a storage level set yet.”
↩︎ cache(), persist() and unpersist()“Cached data is shared across all Spark sessions on the cluster.”
↩︎ cache(), persist() and unpersist()“The default storage level has changed to MEMORY_AND_DISK_DESER to match Scala in 3.0.”
↩︎ Exam trap 4“If no storage level is specified defaults to (MEMORY_AND_DISK_DESER)”
↩︎ Prediction“Sets the storage level to persist the contents of the DataFrame across operations after the first time it is computed.”
↩︎ Checkpoint - 8.https://spark.apache.org/docs/latest/sql-performance-tuning.htmlSecondary source
“Entries cached only via Dataset.cache() without a name are not included.”
↩︎ cache(), persist() and unpersist()“Spark SQL will scan only required columns and will automatically tune compression to minimize memory usage and GC pressure.”
↩︎ Garbage collection pressure in executors“Larger batch sizes can improve memory utilization and compression, but risk OOMs when caching data.”
↩︎ Garbage collection pressure in executors - 9.
“Automatically in LRU fashion, manually with unpersist.”
↩︎ cache(), persist() and unpersist()“When a worker is decommissioned, the Spark cache stored on that worker is lost.”
↩︎ cache(), persist() and unpersist()“In-memory blocks, but it depends on storage level.”
↩︎ Storage levels: trading memory against CPU and disk - 10.
“Databricks recommends moving away from df.cache() and df.persist() as they are not compatible with Databricks serverless compute architecture.”
↩︎ cache(), persist() and unpersist() - 11.
“When executors run out of memory, Spark removes them and retries their tasks.”
↩︎ Garbage collection pressure in executors