CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 1 · Lesson 3/32

    Spark DataFrames, Datasets, SparkSession and caching

    Describe the architecture of Apache SparkTM, including DataFrame and Dataset concepts, SparkSession lifecycle, caching, storage levels, and garbage collection.

    18 min read
    2.86% of exam
    11 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    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.

    Which structured API each language gets
    LanguageDataFrame APITyped Dataset APIHow a DataFrame is expressed
    ScalaYesYesType alias of Dataset[Row]
    JavaYesYesDataset<Row>
    PythonYesNoDataFrame; fields reachable as row.columnName
    RYesNoDataFrame

    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?

    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?

    Sources12

    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().

    Building a session: master URL, application name and a config option, then getOrCreate()python
    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.

    getOrCreate() returns the existing session and merges new builder options into itpython
    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"
    # True

    Three 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.

    Checkpoint 4 of 8· Exam question

    Which statement correctly describes the relationship between SparkSession and SparkContext in current Spark releases?

    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?

    Sources23456

    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.

    Cache once, run two actions against the cached lines, then stop the sessionpython
    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?

    Sources578910

    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.

    Storage levels and what each one does when memory runs short
    LevelForm and locationIf a partition does not fit in memory
    MEMORY_ONLYDeserialized Java objects in the JVMNot cached; recomputed each time it is needed
    MEMORY_AND_DISKDeserialized Java objects in the JVMStored on disk and read back from there
    MEMORY_ONLY_SER (Java and Scala)Serialized, one byte array per partitionRecomputed on the fly
    MEMORY_AND_DISK_SER (Java and Scala)Serialized, one byte array per partitionSpilled to disk
    DISK_ONLYPartitions on disk onlyNot applicable
    MEMORY_ONLY_2, MEMORY_AND_DISK_2, etc.As the base level, replicated on two cluster nodesAs the base level
    OFF_HEAP (experimental)Like MEMORY_ONLY_SER, in off-heap memoryRequires off-heap memory to be enabled
    Reading a DataFrame's storage level before and after cache(), and persisting with DISK_ONLY_2python
    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:

    1. If the data fits comfortably at MEMORY_ONLY, keep it there. It is the most CPU-efficient level.
    2. If not, in Java or Scala, try MEMORY_ONLY_SER with a fast serialization library to save space while keeping access reasonably fast.
    3. 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.
    4. Use a replicated _2 level 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.

    Sources59

    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 (default true) picks a compression codec for each column from data statistics.
    • spark.sql.inMemoryColumnarStorage.batchSize (default 10000) 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?

    Sources65811

    Sources

    (11)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “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. 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. 3.
      “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. 4.
      “Enables Hive support, including connectivity to a persistent Hive metastore.”
      ↩︎ The SparkSession: building, reusing and stopping it
    5. 5.
      “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. 6.
      “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. 7.
      “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. 8.
      “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. 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. 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. 11.
      “When executors run out of memory, Spark removes them and retries their tasks.”
      ↩︎ Garbage collection pressure in executors

    Ready to test yourself?

    Practise Databricks Certified Associate Developer for Apache Spark in quiz mode.

    Spotted a mistake, or was something unclear? Tell us.