What is the role of SparkSession?

Updated May 5, 2026

Short answer

SparkSession is the main entry point for programming with Apache Spark and is used to create and manage Spark applications. It provides access to Spark functionality such as creating DataFrames, running SQL queries, reading data, and interacting with Spark configurations. In Spark 2.0 and later, SparkSession replaced older entry points like SQLContext and HiveContext by combining their capabilities into one unified interface.

Deep explanation

SparkSession is an object that acts as a gateway between an application and the Spark execution engine. Every Spark application typically starts by creating a SparkSession, which is then used throughout the application to perform data processing tasks.

A typical Spark application flow looks like:

TEXT
Application Code
|
v
SparkSession
|
v
Spark Engine
|
v
Cluster Resources
|
v
Data Processing Jobs

The SparkSession manages the connection between the user's code and Spark's internal components.

---

Why SparkSession Is Important

Before Spark 2.0, developers commonly used multiple entry points:

  • SparkContext for core Spark functionality.
  • SQLContext for SQL and DataFrame operations.
  • HiveContext for Hive integration.

Example older approach:

Python
sc = SparkContext()
sqlContext = SQLContext(sc)
hiveContext = HiveContext(sc)

Spark 2.0 introduced SparkSession to simplify this:

Python
from pyspark.sql import SparkSession
spark = SparkSession.builder \
.appName("MyApplication") \
.getOrCreate()

Now a single object provides access to most Spark features.

---

Main Responsibilities of SparkSession

1. Creating DataFrames

A major responsibility of SparkSession is creating DataFrames from different data sources.

Example:

Python
df = spark.read.csv("customers.csv", header=True)

The SparkSession provides the read API that allows applications to load data from:

  • CSV files.
  • JSON files.
  • Parquet files.
  • Hive tables.
  • JDBC databases.
  • Cloud storage systems.

Example:

Python
employees = spark.read.json("employees.json")
employees.show()

---

2. Running SQL Queries

SparkSession allows developers to execute SQL queries directly.

Example:

Python
df.createOrReplaceTempView("employees")
result = spark.sql(
"SELECT * FROM employees WHERE salary > 50000"
)
result.show()

The SparkSession manages the SQL execution environment.

---

3. Managing Spark Configuration

SparkSession provides access to Spark configuration settings.

Example:

Python
spark.conf.set(
"spark.sql.shuffle.partitions",
"100"
)

Configurations control things such as:

  • Memory usage.
  • Number of partitions.
  • Execution behavior.
  • Optimization settings.

---

4. Accessing the SparkContext

Although SparkSession is the preferred entry point, it internally uses a SparkContext.

Example:

Python
sc = spark.sparkContext

SparkContext is responsible for:

  • Connecting to the cluster manager.
  • Creating RDDs.
  • Coordinating distributed execution.

Relationship:

TEXT
SparkSession
|
v
SparkContext
|
v
Cluster Manager
|
v
Executors

---

5. Supporting DataFrame and Dataset APIs

SparkSession enables Spark's higher-level APIs:

  • DataFrames.
  • Datasets.
  • Spark SQL.

These APIs allow Spark to optimize queries using the Catalyst optimizer.

Example:

Python
df = spark.read.parquet("sales.parquet")
df.filter(
df.amount > 1000
).groupBy(
"region"
).count()

SparkSession helps Spark analyze and optimize this operation before execution.

---

Creating a SparkSession

The standard way to create a SparkSession is with the builder pattern.

Example:

Python
from pyspark.sql import SparkSession
spark = SparkSession.builder \
.appName("SalesAnalysis") \
.master("local[*]") \
.getOrCreate()

Explanation:

  • appName() gives the Spark application a name.
  • master() defines where Spark runs.
  • getOrCreate() creates a new session or returns an existing one.

---

getOrCreate() Behavior

A common pattern is:

Python
spark = SparkSession.builder.getOrCreate()

getOrCreate() checks whether an active SparkSession already exists.

If one exists:

TEXT
Return existing SparkSession

If one does not exist:

TEXT
Create a new SparkSession

This prevents accidentally creating multiple Spark sessions in the same application.

---

SparkSession and Cluster Execution

SparkSession itself does not process data. It coordinates requests that are executed by Spark's distributed engine.

Example:

TEXT
User Code
|
v
SparkSession
|
v
Logical Plan
|
v
Catalyst Optimizer
|
v
Physical Plan
|
v
Executors Process Data

The SparkSession helps create execution plans, but the actual computation happens on worker nodes.

---

SparkSession in Different Languages

SparkSession is available in multiple Spark APIs.

PySpark

Python
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName(
"Example"
).getOrCreate()

Scala

SCALA
val spark = SparkSession.builder()
.appName("Example")
.getOrCreate()

Java

Java
SparkSession spark =
SparkSession.builder()
.appName("Example")
.getOrCreate();

---

Lifecycle of SparkSession

A typical Spark application follows this lifecycle:

TEXT
1. Create SparkSession
|
v
2. Load data
|
v
3. Transform data
|
v
4. Execute actions
|
v
5. Stop SparkSession

At the end of an application:

Python
spark.stop()

This releases resources used by Spark.

---

SparkSession vs SparkContext

FeatureSparkSessionSparkContext
IntroducedSpark 2.0Earlier Spark versions
Main purposeUnified Spark entry pointCore Spark connection
DataFramesYesNo direct support
SQLYesNo
RDD operationsThrough SparkContextYes
Recommended for new applicationsYesOnly when low-level APIs are needed

---

Real-world example

A company collects sales data from multiple stores and wants to calculate total revenue by region.

The Spark application starts by creating a SparkSession:

Python
from pyspark.sql import SparkSession
spark = SparkSession.builder \
.appName("SalesReport") \
.getOrCreate()
sales = spark.read.csv(
"sales.csv",
header=True,
inferSchema=True
)
report = sales.groupBy(
"region"
).sum(
"amount"
)
report.show()
spark.stop()

Execution flow:

TEXT
sales.csv
|
v
SparkSession
|
v
DataFrame Created
|
v
Transformations Applied
|
v
Spark Optimizes Query
|
v
Executors Process Data
|
v
Revenue Report Generated

The developer interacts mainly through SparkSession, while Spark handles distributed processing behind the scenes.

Common mistakes

  • * Thinking SparkSession performs the actual data processing. It only provides access to Spark functionality and coordinates execution.
  • * Creating multiple SparkSessions unnecessarily in the same application.
  • * Using old `SQLContext` and `HiveContext` patterns in new Spark applications without a specific reason.
  • * Confusing SparkSession with SparkContext. SparkSession is a higher-level entry point that internally uses SparkContext.
  • * Forgetting to call `spark.stop()` in long-running scripts when resources need to be released.
  • * Assuming SparkSession makes operations run immediately. Most DataFrame operations are lazy and execute only when an action is called.
  • * Using SparkSession configuration changes after jobs have already started and expecting existing executions to change.
  • * Believing SparkSession stores all application data. Data is distributed across Spark executors, not stored inside the session.

Follow-up questions

  • What is the difference between SparkSession and SparkContext?
  • Why was SparkSession introduced in Spark 2.0?
  • Does SparkSession execute Spark jobs immediately?
  • How does SparkSession help optimize Spark queries?
  • How do you create a SparkSession in PySpark?
  • When would you use SparkContext directly instead of SparkSession?

More Apache Spark interview questions

View all →