Understand Spark from application start to report output. Learn the Spark processes, APIs, execution plan, partitions, joins, memory, streams, and the Spark UI. See Spark and HBase in one practical example. Compare 14 poor and better performance patterns.
Read data. Plan operations. Run tasks. Make an output dataset.
▦
HBase · distributed storage
Keep rows by row-key range. Serve the rows through RegionServers.
01 / SPARK
Who runs a Spark application?
Start with the Spark processes. A process is a program that runs. An application can start more than one job.
01 / Application
Application
One user program that Spark runs. It has one driver and its own executors.
02 / Process
Driver
The driver plans jobs. It schedules tasks. It collects task results and reports job status.
03 / API
SparkSession
The main entry point for DataFrame and SQL work. In PySpark, its usual name is spark.
04 / API
SparkContext
The lower-level entry point to Spark. SparkSession gives access to it.
05 / Service
Cluster Manager
A service that gives cluster resources to applications. Examples are YARN and Kubernetes.
06 / Machine
Worker Node
A machine that runs application work. A node can host executor processes.
07 / Process
Executor
A process that runs tasks. It also keeps cached data and shuffle data.
08 / Resource
Core / Task Slot
An allocated executor CPU core normally lets one CPU task run at a time.
09 / Setting
Deploy Mode
Client mode starts the driver at the submit location. Cluster mode starts it in the cluster.
Diagram 01 — One Spark application
The manager gives resources. The driver gives work to executor processes.
CLUSTER ARCHITECTURE
Request. The driver asks the cluster manager for executors.
Launch. The cluster manager starts an executor on each worker node.
Run. The driver sends tasks to the executor cores and receives status and results.
Example: A daily Spark application reads payments from HBase. The driver plans the report. Two executors read the initial four Spark partitions. The RegionServers still own the HBase data. They are not Spark executors.
Client mode
The driver starts where the user submits the program. The executors run on cluster nodes.
Cluster mode
The cluster starts the driver. This is useful for an unattended daily report.
Do not confuse these terms: An application is not one job. One application can run many jobs. An executor is not a RegionServer.
The driver can show the Spark version and the application ID. Your cluster version can differ from the reference version.
PYSPARK · CHECK SPARK RUNTIMESpark ≥ 3.5
# Run this in a PySpark notebook or spark-submit program.
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("payment-guide").getOrCreate()
print("Spark version:", spark.version)
print("Application ID:", spark.sparkContext.applicationId)
print("Default parallelism:", spark.sparkContext.defaultParallelism)
print("Spark UI:", spark.sparkContext.uiWebUrl)
On EMR: how YARN gives resources to Spark
On Amazon EMR, the cluster manager is YARN. YARN controls the memory and the CPUs of the cluster nodes. Spark does not own the nodes. Spark must ask YARN for space before it starts a process. If YARN has no free space, your application waits.
10 / YARN service
ResourceManager
The YARN service that controls the cluster. It knows the free memory and vCPUs of each node. It keeps the queues and decides which application gets space next. On EMR, it runs on the primary node. Its web UI uses port 8088.
11 / YARN service
NodeManager
The YARN agent on each core node and task node. It tells the ResourceManager how much memory and how many vCPUs the node gives to YARN. It starts containers and monitors their memory.
12 / Resource
Container
A fixed quantity of memory and vCPUs on one node, for example 4 GiB and 2 vCPUs on node B. Each process of your application runs in one container. A container cannot use two nodes.
13 / Process
ApplicationMaster
The first container that YARN starts for an application. Each application has its own ApplicationMaster (AM). The AM asks the ResourceManager for more containers, for example 10 executors of 6 GiB each.
14 / Setting
Queue
A share of the cluster resources. The scheduler puts each application in a queue. On EMR, the scheduler is usually the Capacity Scheduler. If the queue is full, the application waits.
15 / Resource
Memory Overhead
Memory that an executor uses outside the JVM heap. The container size is spark.executor.memory plus spark.executor.memoryOverhead. The default overhead is 10% of the executor memory, with a minimum of 384 MiB.
Node capacity: Two settings tell YARN how much each node gives: yarn.nodemanager.resource.memory-mb and yarn.nodemanager.resource.cpu-vcores. EMR sets them from the instance type. The operating system and the HDFS and YARN services use the remaining memory.
Diagram 02 — How a spark-submit starts on YARN
Cluster mode. YARN starts the ApplicationMaster first. The ApplicationMaster then asks for the executor containers.
YARN · CLUSTER MODE
Submit.spark-submit sends the application to the ResourceManager. It also copies the application files to a staging folder in HDFS.
Start the AM. The scheduler finds free space in the queue. The ResourceManager tells one NodeManager to start the ApplicationMaster in container 1.
Ask for executors. The ApplicationMaster registers with the ResourceManager. It asks for one container for each executor.
Start executors. The ResourceManager gives containers on nodes that have free space. The ApplicationMaster tells the NodeManager on each node to start an executor in its container.
Run. Each executor registers with the driver. The driver sends tasks and receives the results. At the end, the ApplicationMaster unregisters and YARN releases all the containers.
Client mode
The driver runs in the spark-submit process, on the node where you submit the application. The ApplicationMaster is small (spark.yarn.am.memory, 512 MiB by default). It only asks for executor containers. If the spark-submit process stops, the application stops. Use client mode for notebooks and the PySpark shell.
Cluster mode
The driver runs in the ApplicationMaster container, on a cluster node. The size of this container comes from spark.driver.memory and its overhead. The application continues if you close your terminal. Use cluster mode for scheduled jobs.
What lives in the driver and what goes to the executors
The SparkSession and its SparkContext are only in the driver. Each application has one SparkContext. Spark does not copy it to the executors. The deploy mode only changes the location of the driver. In client mode, the SparkContext is in the spark-submit process, usually on the EMR primary node. In cluster mode, it is in the ApplicationMaster container. In the two modes, the executors run in other containers and do not have a SparkContext.
Only in the driver
The SparkSession and the SparkContext. The connection to YARN. The query plans, the DAG of stages, and the task scheduler. The results of collect().
Sent to the executors
Serialized tasks. Each task has your function, the variables that the function uses, and one partition to process. Broadcast variables, one copy for each executor. The Spark configuration and the files from --jars and --py-files, when the executor starts.
Do not use the SparkContext in a function that runs on the executors: The SparkContext cannot be serialized. If a map function or a UDF uses spark or sc, the job fails. Spark shows an error that says that the SparkContext can only be used on the driver. Do the Spark operation in the driver, or use a join or a broadcast variable.
How the executor cores run the tasks of a stage
Spark makes one task for each partition in each stage. If a stage has 200 partitions, Spark makes 200 tasks for that stage. A job that has two stages of 200 partitions runs 400 tasks. One executor core runs one task at a time, because spark.task.cpus is 1 by default. Thus an executor that has 4 cores runs 4 tasks at the same time.
Example: one executor with 4 cores and a stage with 200 tasks. When a core completes a task, the scheduler gives it the next task that waits.
Core 1
T1T8T11T14T16…
Core 2
T2T5T7T9…
Core 3
T3T12…
Core 4
T4T6T10T13T15…
Wide blocks are tasks that take more time, for example tasks that read a large partition.
What Spark does not do
Spark does not give a fixed list of 50 tasks to each core before the stage starts. The driver keeps a list of tasks that wait. It sends the next task to the first task slot that becomes free.
What you see as a result
If all tasks take the same time, each core runs approximately 50 tasks, in approximately 50 waves of 4. If some partitions are larger, the numbers are different. For example, one core can run 60 tasks and a different core can run 40 tasks. Data locality can also change the core that gets a task.
With more executors, Spark sends the tasks to all free task slots in the cluster. For example, 5 executors with 4 cores each give 20 slots. Then 20 tasks run at the same time, and the 200 tasks finish in approximately 10 waves. Use more partitions than task slots, for example 2 to 4 partitions for each core. Then a slow task delays the stage less, because the other cores continue to run the tasks that wait.
The application stays in ACCEPTED
YARN has no free space for the ApplicationMaster container. Open the YARN UI on port 8088. Look at the queue of the application and at the memory that other applications use.
Fewer executors than you asked for
The cluster has no free space for more containers. Spark runs tasks on the executors that it has. EMR turns on dynamic allocation by default, so Spark asks for executors when the work needs them.
Container killed by YARN
A container used more physical memory than its size, and the NodeManager stopped it. The log shows "Container killed by YARN for exceeding memory limits". The exit code is usually 143 (SIGTERM). Increase spark.executor.memoryOverhead or decrease the memory that each task uses.
Exit code 137
Code 137 is SIGKILL. The process did not stop after SIGTERM, or the Linux out-of-memory killer stopped it. Examine the memory of the node and of the container.
02 / SPARK
What data does Spark process?
A DataFrame has rows and columns. A schema defines the column types. Spark can read data from many systems.
Version: all local PySpark examples in this chapter use APIs available in Spark 3.5.0.
01 / Data type
DataFrame
A distributed table with named columns and a schema. Use it for most PySpark data work.
02 / Data type
Schema
The names and data types of the columns. A schema tells Spark how to interpret each value.
03 / Structure
Row / Column
One row contains one record. A column contains one field for all rows.
04 / API
RDD
A Resilient Distributed Dataset. It is a lower-level distributed collection with partitions.
05 / API
Dataset
A typed distributed collection in Scala and Java. Python uses the DataFrame API.
06 / API
Spark SQL
An interface to write SQL statements for structured data. It uses the Spark SQL engine.
07 / Metadata
Catalog / Table
A catalog holds table information. A table name can refer to data in files or another source.
08 / Extension
UDF
A user-defined function. Use native Spark functions first when they can do the work.
09 / Input
Data Source
The system or format from which Spark reads data. Examples are Parquet, CSV, JDBC, and an HBase connector.
Diagram 03 — A DataFrame has a schema
Selected columns from the eight-row sample. The DataFrame also contains payment_date.
DATA MODEL
row_keystring
merchantstring
amount_auddecimal(12,2)
statusstring
00#TXN1001
Grocery
120.00
SUCCESS
00#TXN1002
Travel
80.00
FAILED
01#TXN1003
Travel
250.00
SUCCESS
Important: The DataFrame looks like one table. Spark can keep its rows in many partitions on many executors. Use a decimal type for money.
Run this first. This synthetic dataset matches the eight rows in Chapter 14. It uses an in-memory DataFrame, so the example does not need HBase or S3. It does not reproduce HBase region placement or input splits.
DataFrame operations select the records and columns that you need. They do not change the source DataFrame.
PYSPARK · SELECT, FILTER, AND CREATE A COLUMNSpark ≥ 3.5
You can use Spark SQL instead of the DataFrame expression syntax. Both use the Spark SQL engine.
PYSPARK · USE SPARK SQL ON THE SAME DATAFRAMESpark ≥ 3.5
payments_df.createOrReplaceTempView("payments")
summary_sql = spark.sql("""
SELECT merchant, COUNT(*) AS success_count,
SUM(amount_aud) AS total_aud
FROM payments
WHERE status = 'SUCCESS'
GROUP BY merchant
ORDER BY merchant
""")
summary_sql.show()
Partition note: The sample has a payment_date column. An output folder such as dt=2026-10-03 is a storage partition. It does not specify the number of Spark task partitions.
03 / SPARK
How does Spark plan work?
The query plan is not the same as the Python statement list. Spark can combine operations and select a better execution plan.
01 / Operation
Transformation
An operation that defines a new dataset. Examples are filter, select, and groupBy.
02 / Operation
Action
An operation that requests a result or writes output. Examples are count, show, and write.save.
03 / Rule
Lazy Evaluation
Spark records many transformations before it runs the necessary work. An action can start execution.
04 / Plan
DAG
A directed acyclic graph. It shows how computation steps depend on one another.
05 / Recovery
Lineage
The recorded operations from which Spark can calculate a dataset again.
06 / Plan
Logical Plan
The operations that the query must do. Spark can optimise this plan.
07 / Plan
Physical Plan
The execution steps that Spark selects. Use explain() to inspect them.
08 / Optimiser
Catalyst
The Spark SQL optimiser. It rewrites and selects query plans.
09 / Optimisation
Predicate Pushdown
A data source applies a supported filter before it sends the data to Spark. Support depends on the source.
Diagram 04 — From Python code to a Spark result
Transformations define the work. The action requests the result.
LAZY EXECUTION
Transformation
Adds a step to the plan. Nothing runs yet.
Action
Asks for a result, so Spark plans and runs a job.
Shuffle
Moves rows between tasks. It usually separates two stages.
Example: The filter line does not make a separate Spark job by itself. A later action starts the necessary work. The job count depends on the action and execution plan.
EXAMPLE · PYSPARK LAZY TRANSFORMATIONS + ACTIONSpark ≥ 3.5
from pyspark.sql import functions as F
# Use payments_df from Chapter 02. These lines build a plan.
report = (payments_df
.filter(F.col("status") == "SUCCESS")
.groupBy("merchant")
.agg(F.sum("amount_aud").alias("total_aud")))
report.explain("formatted") # Inspect the physical plan.
report.orderBy("merchant").show() # Request the result.
Look for an Exchange operator in the physical plan. It usually indicates a redistribution of records.
PYSPARK · COMPARE A NARROW STEP AND A WIDE STEPSpark ≥ 3.5
# The filter usually has a narrow dependency.
narrow = payments_df.filter(F.col("status") == "SUCCESS")
# This grouping generally needs a shuffle (wide dependency).
wide = narrow.groupBy("merchant").agg(
F.count("*").alias("payment_count"))
wide.explain("formatted") # Look for Exchange in the plan.
wide.orderBy("merchant").show()
04 / EXECUTION
How Spark divides the work
Spark processes partitions in parallel. The Spark driver plans the work. Spark executors run the tasks.
Concept 01
Job
A job is a computation. An action can start a job.
Concept 02
Stage
A stage is a set of tasks. A shuffle usually makes a new stage.
Concept 03
Task
A task is one unit of work. An executor runs each task.
Concept 04
Partition
A partition is one part of a dataset. One task processes one partition in a stage.
Diagram 05 — One example job
The first stage has four partitions. The second stage has two partitions.
EXECUTION FLOW
Task count
A stage runs one task for each partition it reads. Stage 1 has 4; stage 2 has 2.
Every-to-every
Each stage-1 task writes a piece for each stage-2 task. That is why a shuffle is costly.
Read the task boxes: T means Task. P means Partition. The partition count can change after a shuffle.
EXAMPLE · PYSPARK JOB TRIGGERSpark ≥ 3.5
# Define work with the sample DataFrame.
result = (payments_df
.filter("amount_aud > 100")
.groupBy("merchant")
.count())
# The action requests the result and can start Spark jobs.
result.show()
This lower-level RDD example helps you see the relationship between a partition and a task. The four partitions do not represent HBase regions.
PYSPARK · SHOW THE ROWS IN EACH RDD PARTITIONSpark ≥ 3.5
# RDD example: four partitions contain the integers 0 to 11.
sc = spark.sparkContext
numbers = sc.parallelize(range(12), 4)
# Each mapPartitionsWithIndex call runs for one RDD partition.
def inspect_partition(index, values):
yield (index, list(values))
print(sorted(numbers.mapPartitionsWithIndex(inspect_partition).collect()))
Spark does not run a transformation immediately. It starts the necessary work when an action needs a result. One action can start more than one job.
05 / SPARK
How do partitions and shuffles work?
Spark uses partitions to divide data. A stage starts one task for each partition that the stage must process.
Version: Spark 3.5.0+. Adaptive Query Execution can change the final shuffle partition count. DataFrame.rdd needs classic Spark.
01 / Dependency
Narrow Dependency
A child partition needs data from a limited number of parent partitions. A filter is usually narrow.
02 / Dependency
Wide Dependency
A child partition can need data from many parent partitions. groupBy often needs a wide dependency.
03 / Data move
Shuffle
Spark redistributes records among partitions. A shuffle often moves data across the network.
04 / Operation
Repartition
An operation that makes a new partition layout. It normally causes a shuffle.
05 / Operation
Coalesce
An operation that merges partitions to reduce the partition count. It does not do a full shuffle, and it cannot increase the count.
06 / Capacity
Parallelism
The number of tasks that can do work at the same time. Task count and available cores both matter.
07 / Recovery
Task Attempt
One execution attempt for a task. Spark can retry a failed task.
08 / Placement
Data Locality
How close the task is to its input data. Local reads can reduce data transfer.
09 / Problem
Skew
An uneven distribution of data or work. One large partition can delay a stage.
Diagram 06 — Narrow and wide operations
A narrow operation can keep work inside a partition. A wide operation can need a shuffle.
DEPENDENCIES
Narrow
Spark chains narrow steps inside one task, with no data movement.
Wide
A child partition needs rows from many parents, so Spark shuffles and starts a new stage.
Diagram 07 — Four tasks and six task slots
Each executor has two allocated cores in this example.
PARALLEL WORK
Parallelism
Tasks that run at the same time ≤ executors × cores. Here 3 × 2 = 6 slots.
Idle slots
No ready task, too few partitions, or another bottleneck.
Important: More executors do not automatically make more input partitions. More partitions do not guarantee more speed. Too many small tasks can also add overhead.
Diagram 08 — Data skew makes one task slow
Task 3 reads most of the data, so the whole stage waits for it. The numbers are examples.
SKEW
Read it
Three tasks finish early. Their cores wait (hatched) until task 3 ends.
Effect
The slowest task sets the stage time, not the average task.
Symptoms: Three tasks finish. One task continues for much longer. Check partition size, shuffle read, and key distribution. Adaptive Query Execution (AQE) can reduce some types of skew, such as supported skewed joins.
EXAMPLE · PYSPARK PARTITION COMMANDSSpark ≥ 3.5
# Use the sample payments_df from Chapter 02.
print("Current partitions:", payments_df.rdd.getNumPartitions())
# Repartition normally introduces a shuffle.
eight = payments_df.repartition(8)
print("After repartition:", eight.rdd.getNumPartitions())
# Coalesce can reduce the count without a full shuffle.
four = eight.coalesce(4)
print("After coalesce:", four.rdd.getNumPartitions())
# The SQL shuffle partition target is a session setting (default 200).
# Examples that change it reset it at the end with spark.conf.unset().
print("Shuffle target:", spark.conf.get("spark.sql.shuffle.partitions"))
Find the partition that Spark assigns to each row. The result depends on Spark’s hash partitioning.
PYSPARK · SEE THE PARTITION ID OF EACH RECORDSpark ≥ 3.5
# These four Spark partitions are NOT the four HBase regions.
distributed = (payments_df
.repartition(4, "merchant")
.withColumn("spark_pid", F.spark_partition_id()))
distributed.select("merchant", "row_key", "spark_pid").show()
(distributed.groupBy("spark_pid").count()
.orderBy("spark_pid").show())
With AQE disabled, the configured value is easier to see in the planned shuffle. AQE can change the count at runtime.
PYSPARK · CHANGE THE SHUFFLE PARTITION TARGETSpark ≥ 3.5
spark.conf.set("spark.sql.adaptive.enabled", "false")
spark.conf.set("spark.sql.shuffle.partitions", "2")
merchant_totals = (payments_df
.groupBy("merchant")
.agg(F.sum("amount_aud").alias("total_aud")))
merchant_totals.explain("formatted")
merchant_totals.orderBy("merchant").show()
# Restore the defaults so later examples are not affected.
spark.conf.unset("spark.sql.shuffle.partitions")
spark.conf.unset("spark.sql.adaptive.enabled")
Note: AQE can merge shuffle partitions during execution. The final task count can differ from the initial spark.sql.shuffle.partitions value.
06 / SPARK
How do joins and aggregations work?
A query can combine two datasets. A group operation can calculate a total for each key. These operations often need data movement.
Version: broadcast(), joins, and AQE settings in these examples are available in Spark 3.5.0.
01 / Operation
Join
An operation that combines records with a condition, such as merchant_id.
02 / Strategy
Broadcast Join
Spark sends one small input to executor processes. The large input does not need a join-key shuffle in this plan.
03 / Strategy
Sort-Merge Join
Spark can shuffle and sort both inputs by the join key, then match the rows.
04 / Operation
Aggregation
An operation that calculates a group result. Examples are sum, count, and avg.
05 / Optimisation
Partial Aggregation
Spark calculates local group results before it combines them. This can reduce shuffle data.
06 / Optimisation
AQE
Adaptive Query Execution. Spark can change some plan decisions with runtime statistics.
07 / Optimisation
Column Pruning
Spark reads only the columns that the query needs, when the source supports it.
08 / Optimisation
Partition Pruning
Spark skips storage partitions that do not match a supported filter.
09 / Metadata
Statistics
Data such as row counts and sizes. The optimiser can use these values to select a plan.
Diagram 09 — Join a large table to a small table
The payment table has two million rows. The merchant lookup table has only 50 rows.
BROADCAST JOIN
Use it when
One side is small enough to copy to every executor.
Benefit
Spark reads the large side in place. Only the small side crosses the network.
Example: The lookup table is small. A broadcast join can avoid a large join-key shuffle. A different plan can be better when both inputs are large.
EXAMPLE · COMPLETE PYSPARK BROADCAST JOINSpark ≥ 3.5
from pyspark.sql import functions as F
# The lookup has only three rows, so a broadcast join can fit.
merchant_lookup = spark.createDataFrame([
("Grocery", "Retail"), ("Travel", "Services"),
("Energy", "Utilities")
], ["merchant", "sector"])
joined = (payments_df
.join(F.broadcast(merchant_lookup), on="merchant", how="left")
.filter(F.col("status") == "SUCCESS"))
report = (joined.groupBy("sector")
.agg(F.sum("amount_aud").alias("total_aud")))
report.explain("formatted")
report.orderBy("sector").show()
AQE can combine small shuffle partitions. The exact final plan depends on runtime statistics and your Spark settings.
# These settings apply to subsequent query planning.
spark.conf.set("spark.sql.adaptive.enabled", "true")
spark.conf.set("spark.sql.adaptive.coalescePartitions.enabled", "true")
spark.conf.set("spark.sql.shuffle.partitions", "8")
# AQE can change parts of the plan while a job runs.
adaptive_totals = (payments_df.groupBy("merchant")
.agg(F.sum("amount_aud").alias("total_aud")))
adaptive_totals.collect() # Finish the small demonstration.
adaptive_totals.explain("formatted")
# Restore the default shuffle target for later examples.
spark.conf.unset("spark.sql.shuffle.partitions")
Filter early
Keep SUCCESS records before an expensive join when the result permits it. Check whether the source pushes the filter down.
Use AQE
AQE can merge small shuffle partitions, optimise supported skewed joins, or change a join strategy.
Do not assume: A broadcast hint is always accepted. The join type and the physical plan determine the final strategy.
07 / SPARK
How does Spark use memory and recover?
Spark can keep reused data in memory or on disk. Spark can calculate lost partitions again when it has the necessary lineage and input.
01 / Reuse
Cache
Keep reusable dataset data so later actions can read it more quickly.
02 / Reuse
Persist
Store reusable data with a selected storage level. Data can use memory, disk, or both.
03 / Cleanup
Unpersist
Remove a cached or persisted dataset when you do not need it.
04 / Memory
Spill
Write intermediate data to disk when there is not enough memory for an operation.
05 / Recovery
Checkpoint
Save a stable copy to reliable storage. Spark can then use it as a new start point.
06 / Recovery
Fault Tolerance
The ability to continue or recover after some failures. Spark can retry tasks and recompute lost partitions.
07 / Sharing
Broadcast Variable
A read-only value that Spark sends efficiently to executors for reuse in tasks.
08 / Sharing
Accumulator
A variable that tasks can add to. The driver can read its aggregated value.
09 / Memory
Garbage Collection
A JVM memory cleanup operation. High GC time can indicate memory pressure.
Diagram 10 — Cache data only when you reuse it
The daily report uses the same filtered rows two times.
MEMORY + REUSE
Do not cache by default
A cache uses executor memory and can evict other data or spill.
Good case
Several actions reuse one costly DataFrame. Call unpersist() when they finish.
Cost: Cached data uses executor resources. The first action still calculates the cached data. Remove the cache when the two reports finish.
EXAMPLE · PYSPARK CACHE AND CLEANUPSpark ≥ 3.5
from pyspark.sql import functions as F
# The Chapter 02 dataset includes payment_date.
successful = payments_df.filter(F.col("status") == "SUCCESS").cache()
successful.count() # Materialise the cache on this action.
by_merchant = successful.groupBy("merchant").count()
by_day = successful.groupBy("payment_date").count()
by_merchant.show()
by_day.show()
successful.unpersist() # Release the stored partitions.
MEMORY_AND_DISK lets Spark store cached partitions on disk when needed. Use storage only when reuse justifies the cost.
Production checks: Do not cache every DataFrame. Do not use collect() to move a large dataset to the driver. If a task spills or fails with an out-of-memory error, inspect partition sizes and memory metrics.
08 / SPARK
How does Spark read and write files?
Spark can read S3 files, HDFS files, SQL sources, and connector data. The source type can change how Spark plans input partitions.
01 / Format
Parquet
A column-based file format. It is useful for many analytic workloads.
02 / Format
CSV / JSON
Text-based file formats. They are easy to exchange, but Spark often needs more work to parse them.
03 / Read
File Scan
A read operation that gets records from files. Spark can combine small files or divide some large inputs.
04 / Layout
Storage Partition
A folder or table layout made with keys such as dt=2026-10-03.
05 / Output
Write Mode
The instruction that tells Spark what to do with output that already exists, such as append or overwrite. Check the scope before you overwrite data.
06 / Performance
Small-File Problem
A large number of very small files can increase the time to list files and schedule tasks.
Diagram 11 — File layout is not Spark task layout
A date folder can contain more than one file. Spark plans file input partitions separately.
DATA SOURCES
Read side
Spark splits large files and packs small ones (spark.sql.files.maxPartitionBytes).
Write side
Each write task that has rows writes at least one file. Here, 3 tasks give 3 or more files.
Important: Do not assume that one file makes one Spark partition. Spark splits large files and packs small files together. HBase scans use their connector’s split rules.
EXAMPLE · SAVE A DAILY PARQUET REPORTSpark ≥ 3.5
# Spark 3.5.0+; this local example needs no S3 access.
from pathlib import Path
from tempfile import mkdtemp
from pyspark.sql import functions as F
# Use payments_df from Chapter 02.
output_dir = str(Path(mkdtemp(prefix="spark-report-")) / "merchant_count")
daily = payments_df.filter(
F.col("payment_date") == F.to_date(F.lit("2026-10-03")))
(daily.groupBy("merchant").count()
.write.mode("overwrite").parquet(output_dir))
print("Report written to:", output_dir)
# Production alternative: read a partitioned Parquet location on S3A.
# daily = spark.read.parquet("s3a://YOUR-BUCKET/payments/") \
# .filter(F.col("dt") == "2026-10-03")
In this example, a table partition is an output folder. It is not a Spark execution partition or an HBase region.
PYSPARK · PARTITION AN OUTPUT BY PAYMENT DATESpark ≥ 3.5
# Spark 3.5.0+; partitionBy() creates file-system folders.
from pathlib import Path
from tempfile import mkdtemp
from pyspark.sql import functions as F
output = str(Path(mkdtemp(prefix="spark-partition-demo-"))
/ "payments_partitioned")
(payments_df
.withColumn("dt", F.date_format("payment_date", "yyyy-MM-dd"))
.write.mode("overwrite").partitionBy("dt").parquet(output))
# This reads storage partitions. It does not read HBase regions.
reloaded = spark.read.parquet(output).filter(F.col("dt") == "2026-10-03")
reloaded.select("row_key", "dt").show()
# Production alternative: output = "s3a://YOUR-BUCKET/payments_partitioned/"
Different partitions: A table folder named dt=... is a storage partition. A Spark partition is a task input or output unit. An HBase region is a row-key range. These terms do not mean the same thing.
09 / SPARK
What changes when data arrives continuously?
A batch job reads bounded data. A streaming query processes new input as it arrives.
Version: these rate-source and micro-batch examples work with Structured Streaming in Spark 3.5.0+.
01 / Mode
Batch
A computation on a bounded input. A daily report is a batch job.
02 / Mode
Structured Streaming
A Spark API that processes new data with DataFrame operations.
03 / Execution
Micro-Batch
One small batch of newly available input data. Structured Streaming uses this model by default.
04 / Control
Trigger
A setting that controls when the query checks for new work.
05 / Time
Event Time
The time at which an event occurred. It can differ from arrival time.
06 / Time
Watermark
A limit that helps Spark manage late events and state for supported stateful operations.
07 / State
State Store
Storage for intermediate results in a stateful streaming query.
08 / Recovery
Streaming Checkpoint
Saved query progress and the state that the query needs. It helps a query restart after a failure.
09 / Output
Sink
The destination for output records. The sink can affect delivery guarantees.
Diagram 12 — A payment stream arrives in micro-batches
The numbers show only an example timeline.
STREAM PROCESSING
Micro-batch
Each trigger processes the events that arrived since the previous batch.
Checkpoint
◆ Spark writes the offsets before a batch runs and ○ a commit after it. A restart resumes from them.
Example: A payment processor sends events to Kafka. Spark reads new records and calculates a one-minute count. A watermark can manage late data for supported stateful operations. End-to-end guarantees also depend on the source and sink.
EXAMPLE · RUNNABLE PYSPARK RATE STREAM (LOCAL DEMO)Spark ≥ 3.5
from pyspark.sql import functions as F
from tempfile import mkdtemp
# Local practice input. No Kafka installation is required.
ticks = (spark.readStream.format("rate")
.option("rowsPerSecond", 2).load())
counts = (ticks
.withColumn("bucket", F.col("value") % 3)
.groupBy("bucket").count())
checkpoint = mkdtemp(prefix="spark-rate-guide-")
query = (counts.writeStream.format("console")
.outputMode("complete")
.option("checkpointLocation", checkpoint)
.trigger(processingTime="5 seconds").start())
try:
query.awaitTermination(15) # Run the example for about 15 s.
finally:
query.stop()
A watermark helps bound state for supported event-time operations. In production, use a durable checkpoint location.
PYSPARK · EVENT-TIME WINDOW AND WATERMARKSpark ≥ 3.5
# Use ticks from the preceding rate-source example.
windowed = (ticks
.withWatermark("timestamp", "30 seconds")
.groupBy(F.window("timestamp", "10 seconds"))
.count())
# This is a DataFrame definition. Start a writeStream
# with a suitable sink and checkpoint to run the query.
windowed.printSchema()
Important: This code is illustrative. A watermark does not mean that Spark will always drop every event after the watermark. Do not promise exactly-once delivery for all external sinks.
10 / SPARK
How do you check a slow Spark job?
First identify the slow stage. Then identify its slow tasks. Use logs and Spark UI metrics to find the cause.
01 / Tool
Spark UI
A web view for applications, jobs, stages, tasks, executors, SQL, and cached data.
02 / View
SQL Tab
A view of SQL or DataFrame query execution and its physical plan.
03 / View
Jobs Tab
A view of the jobs and their stages.
04 / View
Stages Tab
A view of task attempts, task duration, shuffle I/O, and other metrics.
05 / View
Executors Tab
A view of executor use, task counts, storage, and error information.
06 / Metric
Shuffle Read / Write
Measurements of data that tasks send or receive through a shuffle.
07 / Metric
GC Time
Time used by JVM memory cleanup. Very high values can show memory pressure.
08 / History
Event Log / History Server
A saved execution record and a service that can show old application runs.
09 / Tool
Explain
An API that shows the selected or planned query operations.
Diagram 13 — Start at the symptom
Use the Spark UI to identify the stage and task that need attention.
TROUBLESHOOTING
Rule
Run the same input before and after one change, and compare the same metrics.
Spark UI
Stage and task metrics show where time goes before you tune a setting.
EXAMPLE · USEFUL CHECKSSpark ≥ 3.5
# Spark 3.5.0+. Use the eight-row payments_df from Chapter 02.
from pyspark.sql import functions as F
report = (payments_df.filter(F.col("status") == "SUCCESS")
.groupBy("merchant")
.agg(F.sum("amount_aud").alias("total_aud")))
report.explain("formatted")
print("Input partitions:", payments_df.rdd.getNumPartitions())
print("Shuffle target:", spark.conf.get("spark.sql.shuffle.partitions"))
print("AQE enabled:", spark.conf.get("spark.sql.adaptive.enabled"))
# DataFrame.rdd requires classic Spark, not Spark Connect.
Use this check with a large dataset to find uneven record counts. Equal counts do not guarantee equal task duration.
from pyspark.sql import functions as F
# Inspect the count of records in each output partition.
with_id = (payments_df.repartition(4)
.withColumn("partition_id", F.spark_partition_id()))
(with_id.groupBy("partition_id").count()
.orderBy("partition_id").show())
A job group can help you identify an operation in the Spark UI. This example has six successful rows.
PYSPARK · LABEL A JOB IN THE SPARK UISpark ≥ 3.5
sc = spark.sparkContext
sc.setJobGroup("PAYMENT_AUDIT", "Count successful payments")
try:
audit_count = payments_df.filter("status = 'SUCCESS'").count()
print("Successful payments:", audit_count)
finally:
# PySpark has no clearJobGroup(); clear the thread-local labels instead.
for key in ("spark.jobGroup.id", "spark.job.description"):
sc.setLocalProperty(key, None)
Where to look: The Spark UI usually starts on driver port 4040 if the port is available. Configure event logs to inspect finished applications with the History Server. In a managed cluster, use the UI or log links that your platform provides.
11 / HBASE
How HBase divides the data
HBase stores rows in row-key order. Each region contains one row-key range. A RegionServer serves one or more regions.
HBase reference: 3.0.0. A deployed HBase 2.x table has the same general region concepts. Confirm connector compatibility with the actual HBase branch.
Concept 05
Region
A region is part of an HBase table. It contains rows from one row-key range.
Concept 06
RegionServer
A RegionServer is a server process. It reads and writes the rows in its regions.
Concept 07
Region Split
HBase divides a region into two daughter regions when the split policy selects a split.
Other HBase terms that you will see
Storage
Row Key
A byte sequence that identifies one table row. HBase orders rows by this key.
Storage
Column Family
A group of columns that HBase stores together. The table defines its column families.
Storage
Cell / Version
A cell has a row key, family, qualifier, timestamp, and value. A cell can have versions.
Write path
MemStore
Memory that holds new cell updates before a flush. Each region has MemStore structures.
Write path
WAL
Write-Ahead Log. HBase records writes so it can recover updates after some failures.
Storage
HFile
A sorted storage file for HBase data. HBase writes new HFiles when it flushes MemStore data.
Storage
Flush
An operation that writes MemStore data to HFiles.
Maintenance
Compaction
An operation that merges HFiles and can remove data that is no longer needed.
Management
HMaster
A master process that coordinates table and region administration. RegionServers serve the row data.
Diagram 14 — HBase write path
This is a simplified view of one write to a RegionServer.
HBASE INTERNALS
Locate. The client finds the region for the row key in hbase:meta (and caches it).
Put. The client sends the write to RegionServer A. The server appends it to the WAL on HDFS first.
MemStore. The server adds the cell to region R2's MemStore, a sorted in-memory buffer.
Ack. HBase acknowledges the write. The write is durable because the WAL holds it.
Flush. Later, a full MemStore flushes to a new immutable HFile on HDFS.
Note: A region split and an HFile compaction are different operations. A split changes region key ranges. A compaction reorganises storage files.
Diagram 15 — One table, four regions
Two RegionServers serve four regions in this example.
STORAGE LAYOUT
Region
A contiguous, sorted row-key range. The range includes the start key but not the end key.
RegionServer
One server serves many regions. HBase can move a region to another server.
The ranges and row keys are examples. Actual region boundaries use a start key and an exclusive end key. A RegionServer can serve regions from different tables.
Diagram 16 — One region split
HBase selects a split key. It makes two daughter regions.
REGION GROWTH
Range
The two daughters cover exactly the parent's key range.
Storage
A split does not copy data. Compaction rewrites the daughters' files later.
HBase does not have to copy all stored data immediately. It can move a daughter region to another RegionServer later.
The sample app creates the 00, 01, 02, and 03 key prefixes. A prefix is not an HBase Region ID. HBase regions use exact key ranges.
PYSPARK · INSPECT EXAMPLE ROW-KEY PREFIXESSpark ≥ 3.5
# This works on the sample rows. It does not contact HBase.
from pyspark.sql import functions as F
by_prefix = (payments_df
.withColumn("key_prefix", F.substring("row_key", 1, 2))
.groupBy("key_prefix").count()
.orderBy("key_prefix"))
by_prefix.show()
12 / LINK
How Spark reads HBase data
This example uses an HBase TableInputFormat scan. The default scan can make one InputSplit for each HBase region.
Version boundary: PySpark examples use Spark 3.5.0+; HBase scan setup is connector-specific. One InputSplit for each partition is not a universal rule.
New term
InputSplit
An InputSplit describes one part of an input scan. The input format makes the InputSplits.
Key relation
Scan task
Spark makes a partition for each InputSplit in this example. One scan task reads one partition.
Diagram 17 — Four regions become four scan tasks
Follow one row from left to right: region, InputSplit, Spark partition, scan task.
EXAMPLE MAPPING
Connector assumption
TableInputFormat makes one InputSplit per region by default. Other connectors and settings can make more or fewer.
Spark
One task in the scan stage reads each initial partition, preferably on the region's host.
Important: This relation depends on the connector and its settings. A connector can make more or fewer InputSplits than the region count.
Do not confuse these two terms
The word “split” has two different meanings here.
HBASE STORAGERegion SplitHBase divides one region into two regions. This changes the table layout.
INPUT SCANInputSplitAn input format defines one part of an input scan. This describes read work.
There is no universal, built-in PySpark reader for HBase. The two common paths are below. Both need cluster setup, so you cannot run them offline. Pick the one your platform supports.
# Apache hbase-connectors (hbase-spark). Submit with its jars and the
# cluster's hbase-site.xml, for example:
# spark-submit --jars hbase-spark.jar,hbase-spark-protocol-shaded.jar \
# --files /etc/hbase/conf/hbase-site.xml report.py
# Check the connector's Spark, Scala and HBase compatibility first.
from pyspark.sql import functions as F
hbase_df = (spark.read.format("org.apache.hadoop.hbase.spark")
.option("hbase.table", "payments")
.option("hbase.columns.mapping",
"row_key STRING :key, merchant STRING d:merchant, "
"amount_aud STRING d:amount_aud, status STRING d:status")
.option("hbase.spark.use.hbasecontext", False)
.load()
.withColumn("amount_aud", F.col("amount_aud").cast("decimal(12,2)")))
# The connector plans the scan partitions from the regions it must read.
print("HBase scan partitions:", hbase_df.rdd.getNumPartitions())
The second path uses HBase’s own MapReduce input format. Each InputSplit becomes one Spark partition. This API is easiest from Scala, because PySpark cannot read HBase Result objects without extra converter classes.
// spark-shell --jars <HBase mapreduce and client jars for your HBase version>
import org.apache.hadoop.hbase.HBaseConfiguration
import org.apache.hadoop.hbase.client.Result
import org.apache.hadoop.hbase.io.ImmutableBytesWritable
import org.apache.hadoop.hbase.mapreduce.TableInputFormat
val conf = HBaseConfiguration.create() // reads hbase-site.xml
conf.set(TableInputFormat.INPUT_TABLE, "payments")
conf.set(TableInputFormat.SCAN_ROW_START, "01#") // inclusive
conf.set(TableInputFormat.SCAN_ROW_STOP, "03#") // exclusive: R2 and R3
conf.set(TableInputFormat.SCAN_COLUMNS, "d:merchant d:amount_aud d:status")
val rows = spark.sparkContext.newAPIHadoopRDD(conf,
classOf[TableInputFormat], classOf[ImmutableBytesWritable], classOf[Result])
// One InputSplit per region in the range: 2 here.
println(s"Scan partitions: ${rows.getNumPartitions}")
Without a cluster, practise on the Chapter 02 sample. Its partition count comes from your local cores, not from HBase regions, so it does not model a real scan.
PYSPARK · OFFLINE STAND-INSpark ≥ 3.5
# Spark 3.5.0+. Offline only: this is NOT an HBase scan.
hbase_df = payments_df
print("Local partitions:", hbase_df.rdd.getNumPartitions()) # set by local cores
hbase_df.printSchema()
13 / HBASE SCANS
HBase scans from PySpark: worked examples
Each example has a task and two versions of the PySpark code. Version A uses the Apache hbase-connectors DataFrame reader. Version B uses TableInputFormat with a Scan that you convert to a Base64 string. Each version shows the measured result: the regions that HBase scanned, the rows that HBase read, and the rows that HBase sent to Spark.
Tested on 9 October 2026 with HBase 2.5.16, Spark 3.5.9 (PySpark), and Apache hbase-connectors hbase-spark 1.0.1 on one machine. The row counts come from the RegionServer read metrics. Other connectors and versions can push down different filters.
A · hbase-connectors
You write DataFrame filters such as F.col("row_key") >= "01#". The connector changes some filters into start rows, stop rows, and HBase filters. It ignores other filters, and then Spark applies them after the read. You get a DataFrame directly.
B · TableInputFormat
You build an HBase Scan object with a start row, a stop row, and filters. TableMapReduceUtil.convertScanToString() serializes it to Base64 for the hbase.mapreduce.scan key. HBase runs exactly that Scan, with one Spark partition for each region in the range. You need a small converter class to get Python values.
Reduces the read
Start row and stop row
HBase reads only the rows from the start row (included) to the stop row (not included). It does not open the other regions.
Reduces the transfer
Server-side filter
HBase reads every row in the range. Then it sends only the rows that pass the filter. The disk work does not decrease.
Reduces nothing in HBase
Spark filter
HBase sends every row in the range to Spark. Then Spark removes rows. Use this only on a small range.
The main rule: First make the row-key range small. Then use filters to decrease the rows that HBase sends. A filter on a column value cannot replace a good row-key range. This rule is the same for version A and version B.
The test table
The table is the payments table from Chapter 14. It has the same eight rows. The table has four regions, with split keys 01#, 02#, and 03#.
HBASE SHELL · MAKE THE TABLE WITH FOUR REGIONSHBase 2.x
Version A: install the connector on the RegionServers. A server-side filter from the connector (SparkSQLPushDownFilter) runs inside the RegionServer. The RegionServer must have hbase-spark, hbase-spark-protocol-shaded, and the Scala 2.12 library on its classpath. Without them, every filtered read fails, also a filter on the row key only. If you cannot change the RegionServers, set hbase.spark.pushdown.columnfilter to False. Version B uses only HBase filters, so it does not need these jars.
Setup for version B · TableInputFormat
PySpark cannot serialize the HBase Result objects that TableInputFormat returns. Without a converter, the job fails with not serializable result: org.apache.hadoop.hbase.io.ImmutableBytesWritable. Spark no longer includes the old example converters, so compile these two small classes once. They change the row key to a str, and each row to a dict.
JAVA · CONVERTERS FOR PYSPARK (BUILD ONCE)Java 8+
// File: example/hbase/ResultToMapConverter.java
package example.hbase;
import java.util.HashMap;
import java.util.Map;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.spark.api.python.Converter;
/** Turns an HBase Result into a Map. PySpark receives it as a dict. */
public class ResultToMapConverter implements Converter<Object, Object> {
@Override
public Object convert(Object obj) {
Result result = (Result) obj;
Map<String, String> row = new HashMap<>();
row.put("row_key", Bytes.toString(result.getRow()));
for (Cell cell : result.rawCells()) {
row.put(Bytes.toString(CellUtil.cloneQualifier(cell)),
Bytes.toString(CellUtil.cloneValue(cell)));
}
return row;
}
}
// File: example/hbase/KeyToStringConverter.java
package example.hbase;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.spark.api.python.Converter;
/** Turns the HBase row key into a Python str. */
public class KeyToStringConverter implements Converter<Object, Object> {
@Override
public Object convert(Object obj) {
return Bytes.toString(((ImmutableBytesWritable) obj).copyBytes());
}
}
SHELL · COMPILE THE CONVERTERSHBase 2.x
# SPARK_HOME/jars has the Spark and Hadoop classes. "hbase mapredcp" gives the HBase client jars.
mkdir -p out
javac --release 8 -cp "$SPARK_HOME/jars/*:$(hbase mapredcp)" -d out example/hbase/*.java
jar cf hbase-pyspark-converters.jar -C out .
# spark-submit --jars hbase-pyspark-converters.jar,<HBase client jars> \
# --files /etc/hbase/conf/hbase-site.xml scans.py
B · TABLEINPUTFORMAT · BUILD A SCAN, CONVERT TO BASE64, READSpark ≥ 3.5
hb = spark._jvm.org.apache.hadoop.hbase
B = hb.util.Bytes
flt = hb.filter
Scan = hb.client.Scan
EQ, NE, LT, GT = (hb.CompareOperator.EQUAL, hb.CompareOperator.NOT_EQUAL,
hb.CompareOperator.LESS, hb.CompareOperator.GREATER)
SCHEMA = "amount_aud string, merchant string, row_key string, status string"
def scan_to_base64(scan):
"""The Base64 string for hbase.mapreduce.scan (serialized protobuf Scan)."""
return hb.mapreduce.TableMapReduceUtil.convertScanToString(scan)
def read_tif(scan, table="payments"):
"""Version B: run one Scan through TableInputFormat. Return a DataFrame."""
conf = {"hbase.mapreduce.inputtable": table,
"hbase.mapreduce.scan": scan_to_base64(scan)}
rdd = sc.newAPIHadoopRDD(
"org.apache.hadoop.hbase.mapreduce.TableInputFormat",
"org.apache.hadoop.hbase.io.ImmutableBytesWritable",
"org.apache.hadoop.hbase.client.Result",
keyConverter="example.hbase.KeyToStringConverter",
valueConverter="example.hbase.ResultToMapConverter",
conf=conf)
return spark.createDataFrame(rdd.values(), SCHEMA)
def column_equals(qualifier, value, op=EQ):
"""SingleColumnValueFilter on family d. Rows without the column are dropped."""
f = flt.SingleColumnValueFilter(B.toBytes("d"), B.toBytes(qualifier), op, B.toBytes(value))
f.setFilterIfMissing(True)
return f
def next_key(key):
"""The first possible key after key. Use it as an exclusive stop row."""
return B.toBytes(key + "\x00")
How to read the results: The four boxes are the four regions. A dark box is a region that HBase scanned. “Rows read” counts the rows that the RegionServers read. “Rows sent” counts the rows that HBase sent to Spark. The table has 8 rows.
Part 1 · Row-key filters: these set the start row and stop row
01
Read one payment by its row key
Task. Show payment 01#TXN1003.
A · hbase-connectorsDataFrame reader. Write DataFrame filters. The connector builds the scan.
A · HBASE-CONNECTORS · ONE ROW KEYSpark ≥ 3.5
one = payments.filter(F.col("row_key") == "01#TXN1003")
one.show()
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 1 of 4Rows read in HBase: 1Rows sent to Spark: 1Spark partitions: 1
B · TableInputFormatBuild a Java Scan. Convert it to a Base64 string. HBase runs exactly that Scan.
B · TABLEINPUTFORMAT · ONE ROW KEYSpark ≥ 3.5
scan = (Scan().withStartRow(B.toBytes("01#TXN1003"))
.withStopRow(next_key("01#TXN1003"))) # stop row = the next possible key
one_b = read_tif(scan)
one_b.show()
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 1 of 4Rows read in HBase: 1Rows sent to Spark: 1Spark partitions: 1
A: an equality test on the row key becomes an HBase Get. B: a range that contains only one key does the same work. Both versions read one row from region R2.
02
Set the start row and the stop row
Task. Read all payments in salt bucket 01#.
A · hbase-connectorsDataFrame reader. Write DataFrame filters. The connector builds the scan.
A · HBASE-CONNECTORS · START ROW AND STOP ROWSpark ≥ 3.5
# Start row "01#" is included. Stop row "02#" is not included.
bucket_01 = payments.filter(
(F.col("row_key") >= "01#") & (F.col("row_key") < "02#"))
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 1 of 4Rows read in HBase: 2Rows sent to Spark: 2Spark partitions: 1
B · TableInputFormatBuild a Java Scan. Convert it to a Base64 string. HBase runs exactly that Scan.
B · TABLEINPUTFORMAT · START ROW AND STOP ROWSpark ≥ 3.5
scan = Scan().withStartRow(B.toBytes("01#")).withStopRow(B.toBytes("02#"))
bucket_01_b = read_tif(scan)
# Without filters, you can also use the plain keys and no Scan object:
# conf = {"hbase.mapreduce.inputtable": "payments",
# "hbase.mapreduce.scan.row.start": "01#",
# "hbase.mapreduce.scan.row.stop": "02#"}
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 1 of 4Rows read in HBase: 2Rows sent to Spark: 2Spark partitions: 1
A: >= sets the start row and < sets the stop row. B: you set them on the Scan. HBase opens only region R2 in both versions.
03
Read all rows that start with a prefix
Task. Read salt bucket 02#. Then read the keys from 01#TXN1004 to 02#TXN1005, both included.
A · hbase-connectorsDataFrame reader. Write DataFrame filters. The connector builds the scan.
A · HBASE-CONNECTORS · PREFIX AND BETWEENSpark ≥ 3.5
Regions scanned: 1 of 4Rows read in HBase: 2Rows sent to Spark: 2Spark partitions: 1
between("01#TXN1004", "02#TXN1005")
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 2 of 4Rows read in HBase: 2Rows sent to Spark: 2Spark partitions: 2
B · TableInputFormatBuild a Java Scan. Convert it to a Base64 string. HBase runs exactly that Scan.
B · TABLEINPUTFORMAT · PREFIX AND BETWEENSpark ≥ 3.5
bucket_02_b = read_tif(Scan().setStartStopRowForPrefixScan(B.toBytes("02#")))
# Do NOT use withStopRow(key, True) here. TableInputFormat lost the
# "inclusive" flag when the range crossed a region: 02#TXN1005 was missing.
crossing_b = read_tif(Scan().withStartRow(B.toBytes("01#TXN1004"))
.withStopRow(next_key("02#TXN1005")))
setStartStopRowForPrefixScan("02#")
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 1 of 4Rows read in HBase: 2Rows sent to Spark: 2Spark partitions: 1
start 01#TXN1004, stop next_key("02#TXN1005")
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 2 of 4Rows read in HBase: 2Rows sent to Spark: 2Spark partitions: 2
Both versions read only the rows in the range. Version B trap: with withStopRow("02#TXN1005", True), the test returned 1 row, not 2. To include the last key, use the next possible key (key + "\x00") as an exclusive stop row.
04
Read several key ranges or keys (OR)
Task. Read row 00#TXN1002 and the range 03# to 03#TXN1008. Then read a list of keys.
A · hbase-connectorsDataFrame reader. Write DataFrame filters. The connector builds the scan.
A · HBASE-CONNECTORS · OR OF KEY RANGES AND OR OF KEYSSpark ≥ 3.5
from functools import reduce
two_ranges = payments.filter(
((F.col("row_key") >= "00#TXN1002") & (F.col("row_key") <= "00#TXN1002"))
| ((F.col("row_key") >= "03#") & (F.col("row_key") < "03#TXN1008")))
keys = ["01#TXN1003", "03#TXN1007"]
some_keys = payments.filter(
reduce(lambda a, b: a | b, [F.col("row_key") == k for k in keys])) # not isin()
Two ranges
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 2 of 4Rows read in HBase: 2Rows sent to Spark: 2Spark partitions: 2
B · TableInputFormatBuild a Java Scan. Convert it to a Base64 string. HBase runs exactly that Scan.
B · TABLEINPUTFORMAT · MULTIROWRANGEFILTER, OR ONE SCAN FOR EACH RANGESpark ≥ 3.5
RowRange = flt.MultiRowRangeFilter.RowRange
# Option 1: one Scan with a MultiRowRangeFilter.
ranges = flt.MultiRowRangeFilter([
RowRange(B.toBytes("00#TXN1002"), True, B.toBytes("00#TXN1002"), True),
RowRange(B.toBytes("03#"), True, B.toBytes("03#TXN1008"), False)])
two_ranges_b = read_tif(Scan().setFilter(ranges))
# Option 2: MultiTableInputFormat with one Scan for each range.
def range_scan(start, stop):
s = Scan().withStartRow(B.toBytes(start)).withStopRow(stop)
s.setAttribute("scan.attributes.table.name", B.toBytes("payments"))
return scan_to_base64(s)
scans = [range_scan("00#TXN1002", next_key("00#TXN1002")),
range_scan("03#", B.toBytes("03#TXN1008"))]
rdd = sc.newAPIHadoopRDD(
"org.apache.hadoop.hbase.mapreduce.MultiTableInputFormat",
"org.apache.hadoop.hbase.io.ImmutableBytesWritable",
"org.apache.hadoop.hbase.client.Result",
keyConverter="example.hbase.KeyToStringConverter",
valueConverter="example.hbase.ResultToMapConverter",
conf={"hbase.mapreduce.scans": ",".join(scans)})
two_ranges_b2 = spark.createDataFrame(rdd.values(), SCHEMA)
Option 1: MultiRowRangeFilter
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 4 of 4Rows read in HBase: 2 + 1 check in each regionRows sent to Spark: 2Spark partitions: 4
Option 2: MultiTableInputFormat
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 2 of 4Rows read in HBase: 2Rows sent to Spark: 2Spark partitions: 2
A: an OR of row-key tests becomes one scan or Get for each part. B option 1: the Scan covers the full table, so Spark makes a partition for every region. HBase opens each region, then jumps (seeks) to the ranges. B option 2: each range is its own Scan, so HBase opens only the regions in the ranges. Use option 2 when the ranges are in few regions. For a list of keys in version B, use one RowRange or one Scan for each key.
Part 2 · Column-value filters: these decrease the rows that HBase sends
05
Filter on a column value only
Task. Find all failed payments.
A · hbase-connectorsDataFrame reader. Write DataFrame filters. The connector builds the scan.
A · HBASE-CONNECTORS · VALUE FILTER, WITH AND WITHOUT PUSHDOWNSpark ≥ 3.5
failed = payments.filter(F.col("status") == "FAILED")
# The same filter when the RegionServers do not have the connector jars:
no_pushdown = read_payments(**{"hbase.spark.pushdown.columnfilter": False})
failed_in_spark = no_pushdown.filter(F.col("status") == "FAILED")
Pushdown on (default)
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 4 of 4Rows read in HBase: 8Rows sent to Spark: 2Spark partitions: 4
Pushdown off
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 4 of 4Rows read in HBase: 8Rows sent to Spark: 8Spark partitions: 4
B · TableInputFormatBuild a Java Scan. Convert it to a Base64 string. HBase runs exactly that Scan.
B · TABLEINPUTFORMAT · SINGLECOLUMNVALUEFILTERSpark ≥ 3.5
Regions scanned: 4 of 4Rows read in HBase: 8Rows sent to Spark: 2Spark partitions: 4
The row key does not contain the status, so HBase must read every row in every region. A (pushdown on) and B both send only the 2 failed rows. On a large table, a filter on a value only is a full table scan in both versions.
06
Row-key range AND column value
Task. Find the successful payments in buckets 01# and 02#.
A · hbase-connectorsDataFrame reader. Write DataFrame filters. The connector builds the scan.
A · HBASE-CONNECTORS · KEY RANGE AND VALUE (AND)Spark ≥ 3.5
Regions scanned: 2 of 4Rows read in HBase: 4Rows sent to Spark: 3Spark partitions: 2
This is the best pattern. The key range limits the read to 4 rows. The status filter limits the transfer to 3 rows. AND makes the read smaller. Use AND when you can.
07
Row-key range OR column value
Task. Find the payments in bucket 00#, and all failed payments.
A · hbase-connectorsDataFrame reader. Write DataFrame filters. The connector builds the scan.
A · HBASE-CONNECTORS · KEY RANGE OR VALUE (OR)Spark ≥ 3.5
Regions scanned: 4 of 4Rows read in HBase: 8Rows sent to Spark: 3Spark partitions: 4
A failed payment can be in any region. So the key range cannot limit the scan, and HBase reads every row. An OR between a row-key test and a value test always becomes a full table scan. On a large table, make two reads and join them with unionByName(): the key range is then cheap, and only the value read is a full scan.
08
Filters that need care
Task. Find payments that are not SUCCESS, keys that end with TXN1005, and keys that do not start with 00#.
A · hbase-connectorsDataFrame reader. Write DataFrame filters. The connector builds the scan.
A · HBASE-CONNECTORS · FILTERS THAT THE CONNECTOR DID NOT SEND TO HBASESpark ≥ 3.5
payments.filter(F.col("status") != "SUCCESS") # not equal
payments.filter(F.col("row_key").like("%TXN1005")) # key suffix
payments.filter(~F.col("row_key").startswith("00#")) # NOT prefix
payments.filter(F.col("row_key").isin("01#TXN1003", "03#TXN1007")) # use example 04
payments.filter(F.col("amount_aud").cast("int") > 100) # function on a column
All five filters
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 4 of 4Rows read in HBase: 8Rows sent to Spark: 8Spark partitions: 4
B · TableInputFormatBuild a Java Scan. Convert it to a Base64 string. HBase runs exactly that Scan.
B · TABLEINPUTFORMAT · THE SAME FILTERS AS HBASE FILTERSSpark ≥ 3.5
not_success = read_tif(Scan().setFilter(column_equals("status", "SUCCESS", NE)))
suffix = read_tif(Scan().setFilter(
flt.RowFilter(EQ, flt.RegexStringComparator("TXN1005$"))))
not_00 = read_tif(Scan().setFilter(flt.MultiRowRangeFilter([
flt.MultiRowRangeFilter.RowRange(B.toBytes("01#"), True, None, False)]))) # 01# to the end
# A cast has no HBase filter. Read the range, then filter in Spark.
not_success (NOT_EQUAL)
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 4 of 4Rows read in HBase: 8Rows sent to Spark: 2Spark partitions: 4
suffix (RowFilter regex)
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 4 of 4Rows read in HBase: 8Rows sent to Spark: 1Spark partitions: 4
A: all five filters caused a full read, and HBase sent all 8 rows. Spark then removed rows. explain() can show some of these filters in PushedFilters, but that does not prove that HBase used them. B: you can send NOT_EQUAL and regex filters to HBase, so HBase sends fewer rows. HBase still reads every row. A key suffix search needs a different row-key design in both versions. For “NOT prefix”, use a range: HBase then skips the rows in the prefix.
09
Compare numbers that HBase keeps as text
Task. Find payments with an amount greater than 100 AUD.
A · hbase-connectorsDataFrame reader. Write DataFrame filters. The connector builds the scan.
A · HBASE-CONNECTORS · THE TEXT-COMPARISON TRAPSpark ≥ 3.5
HBase compares bytes, not numbers, in both versions. "8" is greater than "1", so "80" > "100". If you must filter numbers in HBase, write them as fixed-width text (for example 000080) or as sortable binary values.
10
Tune the scan
Task. Read a large range quickly, without damage to the RegionServer cache.
A · hbase-connectorsDataFrame reader. Write DataFrame filters. The connector builds the scan.
A · HBASE-CONNECTORS · SCAN OPTIONSSpark ≥ 3.5
import time
now_ms = int(time.time() * 1000)
tuned = read_payments(**{
"hbase.spark.query.cachedrows": "1000", # rows in each RPC
"hbase.spark.query.cacheblocks": "false", # do not fill the block cache
"hbase.spark.query.timerange.start": str(now_ms - 7 * 86_400_000),
"hbase.spark.query.timerange.end": str(now_ms), # only cells from the last 7 days
})
recent_03 = tuned.filter(F.col("row_key").startswith("03#"))
B · TableInputFormatBuild a Java Scan. Convert it to a Base64 string. HBase runs exactly that Scan.
B · TABLEINPUTFORMAT · SET THE OPTIONS ON THE SCANSpark ≥ 3.5
scan = (Scan().setStartStopRowForPrefixScan(B.toBytes("03#"))
.setCaching(1000) # rows in each RPC
.setCacheBlocks(False) # do not fill the block cache
.setTimeRange(now_ms - 7 * 86_400_000, now_ms))
recent_03_b = read_tif(scan)
Setting
A: connector option
B: Scan method
Rows in one RPC
hbase.spark.query.cachedrows
setCaching(n)
Maximum cells in one result (wide rows)
hbase.spark.query.batchsize
setBatch(n)
Keep a batch scan out of the block cache
hbase.spark.query.cacheblocks
setCacheBlocks(False)
Cell timestamp range
hbase.spark.query.timerange.start / .end
setTimeRange(start, end)
Cell versions
hbase.spark.query.maxVersions
readVersions(n)
Version B trap: when you set hbase.mapreduce.scan, TableInputFormat ignores the separate keys such as hbase.mapreduce.scan.timerange.start. In the test, a time-range key had no effect. Put every setting on the Scan object. A time range uses the HBase cell timestamp, which is the write time, not a business date.
Part 3 · Complex HBase filters
11
AND and OR together
Task. In buckets 01# and 02#, find successful payments for Energy or Travel.
A · hbase-connectorsDataFrame reader. Write DataFrame filters. The connector builds the scan.
A · HBASE-CONNECTORS · DATAFRAME AND (&) WITH OR (|)Spark ≥ 3.5
Regions scanned: 2 of 4Rows read in HBase: 4Rows sent to Spark: 2Spark partitions: 2
MUST_PASS_ALL is AND. MUST_PASS_ONE is OR. You can put a FilterList inside another FilterList. Put the cheapest and most selective filter first in an AND list. Make a new Scan object for each read: the HBase client changes a Scan while it scans.
12
Find a key part in every salt bucket
Task. Find TXN1005. You do not know its salt bucket.
A · hbase-connectorsDataFrame reader. Write DataFrame filters. The connector builds the scan.
A · HBASE-CONNECTORS · ONE KEY FOR EACH BUCKETSpark ≥ 3.5
from functools import reduce
candidates = [f"{bucket:02d}#TXN1005" for bucket in range(4)]
found = payments.filter(
reduce(lambda a, b: a | b, [F.col("row_key") == k for k in candidates]))
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 4 of 4Rows read in HBase: 4 single-row readsRows sent to Spark: 1Spark partitions: 4
B · TableInputFormatBuild a Java Scan. Convert it to a Base64 string. HBase runs exactly that Scan.
B · TABLEINPUTFORMAT · FUZZYROWFILTERSpark ≥ 3.5
# "?" positions can have any byte. Mask: 1 = any byte, 0 = must match.
key = B.toBytes("??#TXN1005")
mask = bytes([1, 1] + [0] * 8)
fuzzy = flt.FuzzyRowFilter([spark._jvm.org.apache.hadoop.hbase.util.Pair(key, mask)])
found_b = read_tif(Scan().setFilter(fuzzy))
R1start–01#R201#–02#R302#–03#R403#–end
Regions scanned: 4 of 4Rows read in HBase: 1 + 1 check in each regionRows sent to Spark: 1Spark partitions: 4
A: you list every possible key, and the connector makes one Get for each. This works when you know all the bucket values. B: FuzzyRowFilter jumps (seeks) to the keys that match the pattern. Each key part must have a fixed length. It also works for a key part followed by more data, for example a date range after the salt.
Part 4 · Test a filter in the HBase shell
The HBase shell is the fastest way to examine a filter before you write Spark code. The FILTER text uses AND, OR, and parentheses. These are the same HBase filters as version B. All results below come from the test table.
HBASE SHELL · START ROW, STOP ROW, AND FILTERSHBase 2.x
# Start row and stop row.
scan 'payments', {STARTROW => '01#', STOPROW => '02#'}
scan 'payments', {ROWPREFIXFILTER => '02#', COLUMNS => ['d:status']}
# AND / OR. The two "true" values are filterIfMissing and latestVersionOnly.
# Keep the filter text on one line, or join the parts with +.
scan 'payments', {COLUMNS => ['d:merchant', 'd:status'],
FILTER => "SingleColumnValueFilter('d','status',=,'binary:SUCCESS',true,true) AND " +
"(SingleColumnValueFilter('d','merchant',=,'binary:Energy',true,true) OR " +
"SingleColumnValueFilter('d','merchant',=,'binary:Travel',true,true))"}
# 4 rows: 01#TXN1003, 02#TXN1005, 03#TXN1007, 03#TXN1008
# Row key regex. HBase reads every row in the range.
scan 'payments', {FILTER => "RowFilter(=,'regexstring:TXN100[37]$')"}
# Keys only: a fast way to list or count row keys.
scan 'payments', {FILTER => "FirstKeyOnlyFilter() AND KeyOnlyFilter()"}
Trap 1: a row without the column passes
Row 01#TXN1009 had no d:status cell. SingleColumnValueFilter('d','status',=,'binary:SUCCESS') returned it. With filterIfMissing set to true, HBase removed it. Always set filterIfMissing to true.
Trap 2: the filter column is not in the scan
With COLUMNS => ['d:merchant'] and a filter on d:status, the scan returned 0 rows. The filter cannot see a column that the scan does not read. Add the filter column, or use addFamily.
Trap 3: PageFilter counts in each region
PageFilter(1) returned 4 rows, one from each region. Use LIMIT => 1 in the shell, Scan.setLimit() in code, or limit() in Spark.
Trap 4: ValueFilter removes cells, not rows
ValueFilter(=,'binary:FAILED') returned only the d:status cell of each failed row. Use SingleColumnValueFilter to keep or remove full rows.
Which method to use
You need
A · hbase-connectors
B · TableInputFormat Scan
HBase read
One row or a list of rows
row_key == k, joined with |
Range [k, next_key(k)), one Scan each
Only those rows
One key range or prefix
>= and <, or startswith()
withStartRow / withStopRow, or setStartStopRowForPrefixScan
Only the range
Several key ranges
Ranges joined with |
MultiTableInputFormat, or MultiRowRangeFilter
Only the ranges
Known key part after a salt
One key or range for each bucket
FuzzyRowFilter
Only matching keys
Rows with a column value
Key range & value test
Start/stop row + SingleColumnValueFilter
The range; sends matches
Value A or value B
(a) | (b)
FilterList(MUST_PASS_ONE)
Full range; sends matches
Not equal, key regex
Spark applies it (full transfer)
NOT_EQUAL, RegexStringComparator
Full range; B sends matches
Numeric comparison
cast() in Spark
cast() in Spark
Full range; sends all
Which version to choose: Use A when you want DataFrame code and simple key ranges and value filters. Use B when you need HBase filters that A cannot make (FuzzyRowFilter, MultiRowRangeFilter, NOT_EQUAL, regex), when you cannot install the connector on the RegionServers, or when you must control the exact Scan.
A: ClassNotFoundException: SparkSQLPushDownFilter
The RegionServers do not have the connector jars. Install them on every RegionServer and restart, or set hbase.spark.pushdown.columnfilter to False. The error NoClassDefFoundError: scala/Enumeration means that the Scala 2.12 library is not on the RegionServer classpath.
hbase-spark 1.0.1 expects SLF4J 1.x. Spark 3.5 uses SLF4J 2.x. In the test, the fix was to add log4j-slf4j-impl from the HBase lib/client-facing-thirdparty folder to --jars.
B: not serializable result: ImmutableBytesWritable
PySpark cannot send HBase objects to Python. Add keyConverter and valueConverter, and put the converter jar in --jars.
B: the last row of a range is missing
The inclusive stop row was lost when the range crossed a region. Use next_key(last_key) as an exclusive stop row.
The filter is in PushedFilters, but the job is slow
PushedFilters shows what Spark offered to connector A. It does not show what HBase used. Examine the read request count of each region in the HBase UI before and after the job.
The result has the wrong rows
HBase compares bytes. Examine the type in hbase.columns.mapping (A) or the comparator (B), and the bytes that the writer stored. Text numbers and negative binary numbers do not sort as numbers.
14 / PRACTICAL
Realistic example: daily payment report
This example uses an imaginary payment service. The values show how the systems work. The payment records are sample data, not live customer data.
Business requirement · Daily settlement
Read payments from HBase. Make a report with Spark.
A payment service stores two million transactions each day. A report must show the total value of successful payments for each merchant. Spark reads the HBase table and makes the report.
Question for the job
How much did each merchant receive from successful payments?
2MDaily transactions in the scenario
2HBase RegionServers
4HBase regions
8Sample rows used below
Diagram 18 — Eight sample payment records
The full table is large. These eight rows make the calculation easy to follow. All values are in AUD.
SAMPLE INPUT DATAHBASE TABLE: PAYMENTS
Region
Row key
Merchant
Amount (AUD)
Status
R1
00#TXN1001
Grocery
120
SUCCESS
R1
00#TXN1002
Travel
80
FAILED
R2
01#TXN1003
Travel
250
SUCCESS
R2
01#TXN1004
Grocery
75
SUCCESS
R3
02#TXN1005
Energy
110
SUCCESS
R3
02#TXN1006
Grocery
60
FAILED
R4
03#TXN1007
Travel
300
SUCCESS
R4
03#TXN1008
Energy
40
SUCCESS
Why do the row keys start with 00, 01, 02, or 03? The application adds a shard prefix to each row key. The four prefixes distribute data across key ranges. In this example, RegionServer A serves R1 and R2. RegionServer B serves R3 and R4. Real ranges have exact start and end keys. HBase does not automatically make these prefixes.
Real system detail: These sample keys carry no date, so a daily report must scan the whole table. Put the date after the salt, for example 00#20261003#TXN1001. Then each salt bucket keeps one day in a contiguous range, and the report reads it with one bounded range scan per bucket. Do not assume a Spark filter always becomes an HBase server-side filter.
Diagram 19 — Follow the records through Spark
This scan uses one InputSplit for each region. Spark makes four initial partitions and four scan tasks.
JOB → STAGES → TASKS
Why shuffle
All partial sums for one merchant must meet in one merge task.
Which task
Spark hashes the merchant to pick the partition. The split shown here is one possible result.
Rows
✓ kept by the SUCCESS filter · ✗ FAILED row, dropped before the shuffle.
Check: Spark reads 8 sample rows. It excludes 2 FAILED rows. It adds 6 SUCCESS rows. The grand total is $895. The two-stage view is a simplified example. An actual Spark physical plan can contain more stages or jobs.
COMPLETE PYSPARK WALKTHROUGH · INCLUDES RESULT CHECKSpark ≥ 3.5
from decimal import Decimal
from pyspark.sql import functions as F
# Run Chapter 02 to create payments_df from the eight sample rows.
# Or replace payments_df with a DataFrame from an approved HBase connector.
spark.conf.set("spark.sql.shuffle.partitions", "2")
spark.conf.set("spark.sql.adaptive.enabled", "false") # Teaching example.
result = (payments_df
.filter(F.col("status") == "SUCCESS")
.groupBy("merchant")
.agg(F.sum("amount_aud").alias("total_aud")))
result.orderBy("merchant").show()
actual = {row["merchant"]: row["total_aud"] for row in result.collect()}
expected = {"Energy": Decimal("150.00"),
"Grocery": Decimal("195.00"),
"Travel": Decimal("550.00")}
assert actual == expected, (actual, expected)
# Restore the defaults so later examples are not affected.
spark.conf.unset("spark.sql.shuffle.partitions")
spark.conf.unset("spark.sql.adaptive.enabled")
This check keeps invalid input out of the payment report. Extend the rules for the needs of a real dataset.
PYSPARK · CHECK DATA QUALITY BEFORE AGGREGATIONSpark ≥ 3.5
from pyspark.sql import functions as F
# Reject empty keys and null amounts before the business calculation.
bad_rows = payments_df.filter(
F.col("row_key").isNull() |
F.col("amount_aud").isNull() |
(F.trim(F.col("row_key")) == ""))
print("Invalid sample rows:", bad_rows.count())
status_counts = (payments_df.groupBy("status")
.agg(F.count("*").alias("rows"))
.orderBy("status"))
status_counts.show()
The scan configuration depends on your HBase connector. The code above starts after the connector loads the HBase rows. In production, use a decimal data type for money. Do not disable adaptive execution only to get two shuffle tasks in a production job.
Diagram 20 — What happens when one region grows?
Assume that Region R2 grows to about 12 GB. The HBase split policy selects a split key.
OPERATIONAL EXAMPLE
Time
A job that is already planned keeps its tasks. Only a later scan sees the new regions.
Two controls
HBase sets the scan partitions. spark.sql.shuffle.partitions sets the merge partitions.
*Assumption: A new scan uses the default rule of TableInputFormat: one InputSplit for each region. Connector settings can change this rule. A region split does not change tasks in a job that Spark already planned. The daughter regions can initially remain on the same RegionServer. HBase can move them later.
Do not confuse these values: The new scan can have five initial tasks. The aggregation can still use two shuffle partitions. HBase decides the storage ranges. Spark decides the later computation partitions.
Diagram 21 — One end-to-end Spark report
Follow the source, Spark processes, shuffle, and output.
COMPLETE WORKFLOW
HBase
Regions decide how Spark splits the scan: here 4 scan tasks.
Spark
The shuffle setting decides the merge stage: here 2 tasks.
Two controls: HBase and the input connector influence the initial scan partitions. Spark controls later partitions and tasks based on the physical plan and its settings.
Example: Low parallelism
Spark has 20 free task slots, but the scan has only 4 partitions.
In this example, Spark runs at most four initial scan tasks at the same time. More task slots alone do not make more input partitions. Check the connector split settings.
Example: One slow task
Task 2 reads much more data than the other tasks.
Check the size of Region R2. Check its row-key distribution. Check the load on its RegionServer. A large region or a hot region can limit read speed.
15 / PERFORMANCE
Spark performance: bad way and better way
These 14 cases use the payment system in this guide. Each case shows a poor pattern and a better pattern. Use the Spark UI to confirm the result on your cluster. The examples show possible costs. They do not claim measured speed improvements.
Version: poor and better code samples use the Spark 3.5.0 API. Use Spark 3.5.9 documentation to check options. Benchmark on your own cluster.
01 · ObserveFind the slow job, stage, and task.
02 · ExplainCheck scans, joins, shuffle, and partitions.
03 · ChangeMake one justified change at a time.
04 · MeasureCompare equal inputs and the same output.
Read this first. The Chapter 02 DataFrame has eight rows. It lets you check syntax and results. It cannot demonstrate production performance. For performance measurements, replace payments_df with a real input of suitable size. Keep the same schema. Use fresh output paths for write tests. Never run destructive write examples against a live production path.
Common example setup
PYSPARK 3.5+ · SHARED EXAMPLE SETUPSpark ≥ 3.5
# Spark 3.5.0+ common setup. Run the Chapter 02 dataset first.
from pathlib import Path
from tempfile import mkdtemp
from pyspark.sql import functions as F
from pyspark import StorageLevel
# For a production comparison, read the same real source for both plans.
# payments_df = spark.read.parquet("s3a://YOUR-BUCKET/warehouse/payments/")
merchant_lookup = spark.createDataFrame([
("Grocery", "Retail"), ("Travel", "Services"),
("Energy", "Utilities"),
], ["merchant", "sector"])
# An offline stand-in for the HBase-scan teaching example.
# Replace this with your approved connector's DataFrame on your cluster.
hbase_df = payments_df # No HBase query is executed in this local demo.
# Build a partitioned LOCAL source for the pruning comparison.
partition_root = str(Path(mkdtemp(prefix="spark-prune-demo-")) / "payments_by_dt")
(payments_df.withColumn("dt", F.date_format("payment_date", "yyyy-MM-dd"))
.write.mode("overwrite").partitionBy("dt").parquet(partition_root))
# Use separate local output directories for each write comparison.
bad_status_out = str(Path(mkdtemp(prefix="spark-bad-status-")) / "status")
good_status_out = str(Path(mkdtemp(prefix="spark-good-status-")) / "status")
Situation. An audit has two million payment rows. The result must be the total amount for each merchant.
✕ Bad way AVOID
PYSPARK · LESS EFFICIENTSpark ≥ 3.5
# Sends every row to the driver. Avoid for large input.
totals = {}
for row in payments_df.collect():
if row.status == "SUCCESS":
key = row.merchant
totals[key] = totals.get(key, 0) + row.amount_aud
print(totals)
Problem. collect() transfers all payment rows to the driver. The driver then does the aggregation. A large result can exhaust driver memory.
✓ Better way PREFER WHEN SUITABLE
PYSPARK · BETTER APPROACHSpark ≥ 3.5
# Compute the totals on the executors.
totals = (payments_df
.filter(F.col("status") == "SUCCESS")
.groupBy("merchant")
.agg(F.sum("amount_aud").alias("total_aud")))
totals.show() # Only a small summary is displayed.
Why it helps. Spark filters rows and calculates partial totals in parallel. It transfers only the small final report to show().
Check in the Spark UI: Watch the driver heap and the SQL aggregation nodes. Compare the amount of data returned to the driver.
Important: collect() is valid when you know that the final result is small. The eight-row sample dataset will not show a meaningful speed difference.
SCENARIO 02PYTHON UDF
Use native Spark functions before a Python UDF
Situation. A payment source contains merchant names with extra spaces and inconsistent letter case.
✕ Bad way AVOID
PYSPARK · LESS EFFICIENTSpark ≥ 3.5
# Python must process values from Spark rows.
@F.udf("string")
def clean_merchant(value):
return value.strip().upper() if value is not None else None
cleaned = payments_df.withColumn(
"merchant_key", clean_merchant(F.col("merchant")))
Problem. A scalar Python UDF adds Python execution and data conversion costs. It can also limit some optimiser changes.
✓ Better way PREFER WHEN SUITABLE
PYSPARK · BETTER APPROACHSpark ≥ 3.5
# Spark has native functions for both operations.
cleaned = payments_df.withColumn(
"merchant_key", F.upper(F.trim(F.col("merchant"))))
cleaned.select("merchant", "merchant_key").show()
Why it helps. The SQL engine executes native functions. Spark can optimise the expression with the rest of the query.
Check in the Spark UI: Inspect the SQL plan. Look for BatchEvalPython in the first version and native Project expressions in the second.
Important: Use a Python UDF when no suitable native expression exists. Check that both versions give the same output, also for null values.
SCENARIO 03SHUFFLE
Do not group all raw values when Spark can aggregate them
Situation. A settlement report must calculate the sum of successful payments for each merchant.
✕ Bad way AVOID
PYSPARK · LESS EFFICIENTSpark ≥ 3.5
# RDD groupByKey keeps the individual values in groups.
from decimal import Decimal
pairs = (payments_df.filter("status = 'SUCCESS'").rdd
.map(lambda row: (row["merchant"], row["amount_aud"])))
slow = (pairs.groupByKey()
.mapValues(lambda values: sum(values, Decimal("0.00"))))
print(slow.collect()) # Small sample result only.
Problem. groupByKey() moves many individual values and holds groups. This can increase shuffle data and memory pressure.
Why it helps. Spark SQL can calculate partial totals before the shuffle. The network then carries fewer intermediate values.
Check in the Spark UI: Compare shuffle write bytes, spill, and the HashAggregate nodes in the SQL plan.
Important: This recommendation is for an aggregate such as SUM. Some algorithms must keep every value. Do not replace them with SUM.
SCENARIO 04JOIN
Broadcast a genuinely small lookup table
Situation. The large payment table needs a three-row merchant-to-sector lookup table.
✕ Bad way AVOID
PYSPARK · LESS EFFICIENTSpark ≥ 3.5
# Force a shuffle-oriented plan for this comparison.
# merchant_lookup is defined in the chapter setup.
joined = (payments_df.hint("MERGE")
.join(merchant_lookup.hint("MERGE"),
on="merchant", how="left"))
joined.explain("formatted")
Problem. The forced merge plan can shuffle and sort the data. This is unnecessary for a tiny dimension table.
✓ Better way PREFER WHEN SUITABLE
PYSPARK · BETTER APPROACHSpark ≥ 3.5
# Send only the small lookup to each executor.
joined = payments_df.join(
F.broadcast(merchant_lookup),
on="merchant", how="left")
joined.explain("formatted")
Why it helps. A broadcast hash join can prevent a shuffle of the large payment table for this join.
Check in the Spark UI: Look for SortMergeJoin and Exchange versus BroadcastHashJoin and BroadcastExchange. Compare shuffle bytes.
Important: Spark can broadcast small tables automatically when statistics permit. Do not force a broadcast for a large table: it can exhaust executor or driver memory.
SCENARIO 05REPARTITION
Remove unnecessary repartition operations
Situation. A developer adds two repartition calls before an ordinary merchant report.
Problem. Unnecessary repartition calls can add shuffle work and scheduler overhead.
✓ Better way PREFER WHEN SUITABLE
PYSPARK · BETTER APPROACHSpark ≥ 3.5
fast = (payments_df
.filter(F.col("status") == "SUCCESS")
.groupBy("merchant")
.agg(F.sum("amount_aud").alias("total_aud")))
fast.explain("formatted")
Why it helps. The simpler query allows Spark to select its own exchanges. Add repartition only when a measured problem needs it.
Check in the Spark UI: Count Exchange operators in the physical plan. Check shuffle bytes and stage duration.
Important: Catalyst can remove or combine some redundant exchanges. Compare the actual plans. Do not assume that each repartition in the code stays in the plan.
SCENARIO 06PARTITION PRUNING
Filter a storage partition by its partition column
Situation. A Parquet dataset uses directories such as dt=2026-10-03. The report needs one day.
✕ Bad way AVOID
PYSPARK · LESS EFFICIENTSpark ≥ 3.5
# Spark 3.5.0+. Use partition_root from the chapter setup.
source = spark.read.parquet(partition_root)
# This filter uses the payload column, not the dt storage partition.
slow = source.filter(F.col("payment_date") == F.to_date(F.lit("2026-10-03")))
slow.explain("formatted") # Inspect PartitionFilters.
Problem. A filter on payment_date does not, by itself, select dt directories. The input scan can examine many dates.
✓ Better way PREFER WHEN SUITABLE
PYSPARK · BETTER APPROACHSpark ≥ 3.5
# Spark 3.5.0+. Use partition_root from the chapter setup.
source = spark.read.parquet(partition_root)
# Filter the actual dt storage partition and select needed columns.
fast = (source.filter(F.col("dt") == "2026-10-03")
.select("merchant", "status", "amount_aud"))
fast.explain("formatted") # Inspect PartitionFilters.
Why it helps. A filter on dt lets a compatible file source prune unrelated directories before Spark reads files. Select only the columns that you need.
Check in the Spark UI: Look for PartitionFilters, PushedFilters, ReadSchema, and input bytes in the SQL file scan.
Important: The code needs a dataset that already has dt partitions. Replace the example S3 path. A data field and a storage partition are different concepts.
SCENARIO 07CACHE
Persist a costly dataset only when you reuse it
Situation. Three separate reports use the same expensive filtered input from S3 or HBase.
✕ Bad way AVOID
PYSPARK · LESS EFFICIENTSpark ≥ 3.5
# Each independent action can start another upstream read.
filtered = payments_df.filter("status = 'SUCCESS'")
filtered.count()
filtered.groupBy("merchant").count().show()
filtered.agg(F.sum("amount_aud")).show()
Problem. The three actions can repeat an expensive input scan and filter.
✓ Better way PREFER WHEN SUITABLE
PYSPARK · BETTER APPROACHSpark ≥ 3.5
from pyspark import StorageLevel
filtered = (payments_df.filter("status = 'SUCCESS'")
.persist(StorageLevel.MEMORY_AND_DISK))
try:
filtered.count() # Populate the cache.
filtered.groupBy("merchant").count().show()
filtered.agg(F.sum("amount_aud")).show()
finally:
filtered.unpersist()
Why it helps. Spark can reuse the persisted filtered records. The first action fills the cache and later actions can read it.
Check in the Spark UI: Check the Storage tab, input scan count, and query plan for InMemoryTableScan.
Important: A cache adds memory pressure and a population cost. Do not cache data that you use once. Test the benefit with the real workload.
SCENARIO 08OUTPUT
Do not force a large output into one file
Situation. A daily export contains many records. The report needs data files, not one single file.
✕ Bad way AVOID
PYSPARK · LESS EFFICIENTSpark ≥ 3.5
# Spark 3.5.0+. One output partition is often a write bottleneck.
out = str(Path(mkdtemp(prefix="spark-one-file-")) / "result")
(payments_df.coalesce(1)
.write.mode("overwrite").parquet(out))
# Try on real data to measure the one-task bottleneck.
Problem. coalesce(1) makes one output partition. One task can become the write bottleneck and hold too much data.
✓ Better way PREFER WHEN SUITABLE
PYSPARK · BETTER APPROACHSpark ≥ 3.5
# Spark 3.5.0+. Keep data distributed for the output write.
out = str(Path(mkdtemp(prefix="spark-parallel-write-")) / "result")
(payments_df.write.mode("overwrite").parquet(out))
# Only tune the output count after you inspect file sizes and task counts.
# payments_df.repartition(24).write.mode("overwrite").parquet(out)
Why it helps. Parallel output partitions let several executors write data. You can tune the target file count later.
Check in the Spark UI: Look at active write tasks, task input sizes, output file count, and stage duration.
Important: Too many partitions also create small files. Choose a file count from measured output sizes. overwrite replaces the named example output location.
SCENARIO 09SMALL FILES
Group rows by the output folder before a partitioned write
Situation. A report writes SUCCESS and FAILED rows into separate status= folders. The DataFrame arrives from an earlier step with many partitions.
✕ Bad way AVOID
PYSPARK · LESS EFFICIENTSpark ≥ 3.5
# Spark 3.5.0+. Run the shared chapter setup to define bad_status_out.
# repartition(8) stands in for an upstream step with many partitions.
(payments_df.repartition(8)
.write.mode("overwrite").partitionBy("status")
.parquet(bad_status_out))
print(len(list(Path(bad_status_out).rglob("*.parquet")))) # 6 to 8 files: depends on local cores
Problem. Every write task holds a mix of statuses, so each task writes one file into every status folder it touches. The file count can increase to tasks × statuses.
✓ Better way PREFER WHEN SUITABLE
PYSPARK · BETTER APPROACHSpark ≥ 3.5
# Spark 3.5.0+. Run the shared chapter setup to define good_status_out.
# Send all rows of one status to the same task before the write.
(payments_df.repartition("status")
.write.mode("overwrite").partitionBy("status")
.parquet(good_status_out))
print(len(list(Path(good_status_out).rglob("*.parquet")))) # 2 files: one per folder
Why it helps.repartition("status") shuffles each status to one task, so each folder gets one file. For a very large status, add a second column or a salt to the repartition, or set maxRecordsPerFile.
Check in the Spark UI: Compare the number of write tasks and the output file count in each folder. Then check the time that later reads use to list files.
Important: The extra shuffle is the cost. It pays off when it removes many small files. For small files that already exist, plan a separate compaction.
SCENARIO 10DATA SKEW
Spread a hot join key over several tasks
Situation. One merchant produces most payment rows. The report joins the payments to a merchant table that is too large to broadcast, so Spark shuffles both sides by merchant.
✕ Bad way AVOID
PYSPARK · LESS EFFICIENTSpark ≥ 3.5
# Spark 3.5.0+. merchant_lookup stands in for a large merchant table;
# the MERGE hints force the shuffle join that a large table would get.
skewed = (payments_df.hint("MERGE")
.join(merchant_lookup.hint("MERGE"), on="merchant"))
skewed.explain("formatted") # SortMergeJoin, Exchange on merchant
Problem. The join shuffles by merchant, so every row of the hot merchant goes to one task. That task controls the stage completion time.
✓ Better way PREFER WHEN SUITABLE
PYSPARK · BETTER APPROACHSpark ≥ 3.5
# Spark 3.5.0+. First check AQE: it splits skewed join partitions.
print(spark.conf.get("spark.sql.adaptive.skewJoin.enabled")) # 'true'
# If the measured skew remains, salt the hot side and copy the other.
N = 8
pay_salted = payments_df.withColumn(
"salt", F.pmod(F.xxhash64("row_key"), F.lit(N)))
lookup_salted = merchant_lookup.crossJoin(
spark.range(N).withColumnRenamed("id", "salt"))
balanced = (pay_salted.hint("MERGE")
.join(lookup_salted.hint("MERGE"), on=["merchant", "salt"])
.drop("salt"))
balanced.explain("formatted")
Why it helps. The salt spreads the hot merchant's rows over up to 8 join tasks. The code copies each merchant row on the other side 8 times, so every salted payment still finds its match.
Check in the Spark UI: Compare maximum and median task duration and shuffle read in the join stage. Confirm that one key causes the slow task.
Important: Do not salt a sum or count. Spark already adds partial sums inside each task before the shuffle, so a hot key sends only one small row per task. A salt suits joins and aggregations that keep every value, such as collect_list.
SCENARIO 11AQE
Do not use one shuffle partition for a large report
Situation. A cluster has many free CPU slots, but one reduce task must process the full shuffle.
✕ Bad way AVOID
PYSPARK · LESS EFFICIENTSpark ≥ 3.5
# A leftover override forces one reducer.
spark.conf.set("spark.sql.adaptive.enabled", "false")
spark.conf.set("spark.sql.shuffle.partitions", "1")
slow = payments_df.groupBy("merchant").count()
slow.explain("formatted") # Exchange hashpartitioning(..., 1)
# Remove the overrides again (the better way shows why that is the fix).
spark.conf.unset("spark.sql.shuffle.partitions")
spark.conf.unset("spark.sql.adaptive.enabled")
Problem. One reducer can become a bottleneck. Other executor slots remain unused during the reduce stage.
✓ Better way PREFER WHEN SUITABLE
PYSPARK · BETTER APPROACHSpark ≥ 3.5
# Remove the overrides. The Spark 3.5 defaults already do the right
# thing: 200 initial shuffle partitions, then AQE merges small ones.
spark.conf.unset("spark.sql.shuffle.partitions") # default 200
spark.conf.unset("spark.sql.adaptive.enabled") # default true
print(spark.conf.get("spark.sql.adaptive.coalescePartitions.enabled"))
fast = payments_df.groupBy("merchant").count()
fast.explain("formatted") # AdaptiveSparkPlan
Why it helps. The fix is to delete the override, not to add settings. With the defaults, Spark starts with enough shuffle partitions, and AQE merges the small ones at runtime. For very large shuffles, tune spark.sql.adaptive.advisoryPartitionSizeInBytes instead of the partition count.
Check in the Spark UI: Look for AdaptiveSparkPlan, shuffle partition size, coalesced partitions, active tasks, and spill.
Important: Look for overrides in spark-defaults.conf, job submit flags and notebook setup cells. The final number of reducers can be lower than 200 under AQE. The eight-row sample will not benefit from this change.
SCENARIO 12MANY ACTIONS
Replace a loop of count actions with one aggregation
Situation. A developer wants the row count for each merchant on a large source.
✕ Bad way AVOID
PYSPARK · LESS EFFICIENTSpark ≥ 3.5
# Three independent count actions.
for name in ["Grocery", "Travel", "Energy"]:
n = payments_df.filter(
F.col("merchant") == name).count()
print(name, n)
Problem. Each loop iteration starts a Spark action and can scan the source again.
✓ Better way PREFER WHEN SUITABLE
PYSPARK · BETTER APPROACHSpark ≥ 3.5
# One distributed aggregation for the same three merchants.
counts = (payments_df
.filter(F.col("merchant").isin(
"Grocery", "Travel", "Energy"))
.groupBy("merchant")
.agg(F.count("*").alias("payment_count")))
counts.orderBy("merchant").show()
Why it helps. One groupBy counts all three merchants in one query.
Check in the Spark UI: Compare the number of Spark jobs, repeated file scans, and total source input bytes.
Important: A merchant with no rows appears as zero in the loop but is absent from the grouped output. Add a lookup and a left join if you need groups with zero values.
SCENARIO 13HBASE
Limit an HBase scan before HBase sends records
Situation. A settlement job needs one row-key range, but the HBase table contains years of payment history.
✕ Bad way AVOID
PYSPARK · LESS EFFICIENTSpark ≥ 3.5
# Spark 3.5.0+.
# The shared setup defines hbase_df = payments_df for an OFFLINE demo.
# On the real cluster, replace it with a genuine connector scan.
full_report = (hbase_df.groupBy("merchant")
.agg(F.sum("amount_aud").alias("total_aud")))
full_report.show()
# An unrestricted real HBase scan can read unrelated row-key ranges.
Problem. A full region scan can transfer many irrelevant rows. A later Spark filter cannot undo the HBase read cost.
✓ Better way PREFER WHEN SUITABLE
PYSPARK · CLUSTER SKETCH, NOT RUN OFFLINESpark ≥ 3.5
# Sketch for the Apache hbase-connectors Spark data source.
# Needs the hbase-spark jar and hbase-site.xml on the cluster.
from functools import reduce
hbase_df = (spark.read.format("org.apache.hadoop.hbase.spark")
.option("hbase.table", "payments")
.option("hbase.columns.mapping",
"row_key STRING :key, merchant STRING d:merchant, "
"amount_aud STRING d:amount_aud, status STRING d:status")
.option("hbase.spark.use.hbasecontext", False)
.load())
# One bounded range per salt bucket (00# to 03#). This connector turns
# comparisons on the :key column into scan start and stop rows.
ranges = [(f"{b:02d}#TXN1001", f"{b:02d}#TXN1005") for b in range(4)]
in_range = reduce(lambda x, y: x | y, [
(F.col("row_key") >= lo) & (F.col("row_key") < hi) for lo, hi in ranges])
selected = (hbase_df.filter(in_range)
.select("row_key", "merchant",
F.col("amount_aud").cast("decimal(12,2)").alias("amount_aud")))
selected.explain("formatted")
Why it helps. Each RegionServer reads only the rows between the start and stop keys of each bucket, and only the mapped columns. With TableInputFormat, set the same bounds with hbase.mapreduce.scan.row.start and hbase.mapreduce.scan.row.stop (one range per job).
Check in the Spark UI: Inspect actual HBase scan settings, RegionServer scan/RPC metrics, and connector-reported pushed filters. Do not rely on a DataFrame filter alone.
Important: There is no universal PySpark HBase connector API, and option names change between connectors and versions. Check how yours turns filters into scan ranges. The key ranges here are illustrative; a date-range report needs the date in the row key after the salt, such as salt#yyyymmdd#txn.
SCENARIO 14GLOBAL SORT
Do not sort a large dataset without a business need
Situation. A pipeline writes an intermediate Parquet dataset. Consumers do not need a global row order.
✕ Bad way AVOID
PYSPARK · LESS EFFICIENTSpark ≥ 3.5
# Spark 3.5.0+. This global order adds work that files may not need.
out = str(Path(mkdtemp(prefix="spark-global-sort-")) / "result")
(payments_df.orderBy(F.col("amount_aud"))
.write.mode("overwrite").parquet(out))
Problem. A global order can introduce a range shuffle and extra sort work. Parquet readers do not need this order for ordinary intermediate steps.
✓ Better way PREFER WHEN SUITABLE
PYSPARK · BETTER APPROACHSpark ≥ 3.5
# Spark 3.5.0+. Write without a global sort.
out = str(Path(mkdtemp(prefix="spark-no-global-sort-")) / "result")
(payments_df.write.mode("overwrite").parquet(out))
# Sort a small final result only when the report needs a rank.
report = payments_df.groupBy("merchant").agg(
F.sum("amount_aud").alias("total_aud"))
report.orderBy(F.desc("total_aud")).show()
Why it helps. The intermediate write avoids an unnecessary sort. You can still sort the small final report for display.
Check in the Spark UI: Compare Sort and Exchange operators, shuffle bytes, and sort spill in the SQL plan.
Important: Keep the global sort when downstream business logic needs ordered rows. Parquet files do not guarantee a global output order for later readers.
Compare the two plans
Run both cases on the same data. Check the result before you compare the time.
MEASURE · DO NOT GUESS
PYSPARK · PLAN AND PARTITION CHECKSpark ≥ 3.5
# Spark 3.5.0+. Define a repeatable comparison from the sample.
slow = payments_df.repartition(48).groupBy("merchant").count()
fast = payments_df.groupBy("merchant").count()
slow.explain("formatted")
fast.explain("formatted")
# To inspect skew, compare rows across input partitions.
from pyspark.sql import functions as F
partition_counts = (payments_df
.withColumn("pid", F.spark_partition_id())
.groupBy("pid").count().orderBy("pid"))
partition_counts.show()
TimeJob and stage duration
NetworkShuffle read and write
MemorySpill and GC time
BalanceMedian and max task time
SourceInput bytes and scan filters
OutputResult rows and file count
Test method. Use equal input data, the same Spark resources, and the same expected output. Run warm-up tests when they are relevant. Compare multiple runs. The Spark UI shows which resource needs attention. A code change can help one workload and harm another.
Use these short definitions when you read Spark code, logs, or the Spark UI. Each example uses the payment system in this guide.
Application and processes
Term
Simple meaning
Payment example
Application
A user program with a driver and executors.
One daily payment-report run.
Driver
A process that plans jobs and schedules tasks.
Plans the report stages.
SparkSession
The entry point for structured Spark operations.
The spark object.
Cluster manager
A service that allocates cluster resources.
YARN can allocate executors.
ResourceManager
The YARN service that gives containers to applications.
Puts the report in a queue and gives it space.
NodeManager
The YARN agent that starts containers on one node.
Starts an executor on a core node.
Container
A fixed quantity of memory and vCPUs on one node.
6 GiB and 2 vCPUs for one executor.
ApplicationMaster
The first container of a YARN application. It asks for the other containers.
Asks YARN for the report executors.
Executor
A process that runs tasks and stores cached data.
Reads partitions and calculates totals.
Core / slot
Task execution capacity in an executor.
Two allocated cores allow about two CPU tasks at once.
Computation and data
Term
Simple meaning
Payment example
DataFrame
A distributed table with a schema.
The payment rows and amount columns.
RDD
A lower-level distributed collection.
A possible low-level input scan.
Partition
A logical part of a dataset.
One of four input partitions.
Transformation
An operation that defines a new dataset.
Filter status = SUCCESS.
Action
An operation that requests a result or output.
show().
Lazy evaluation
Spark delays much of the work until needed.
Build the report plan first.
Job
A computation started to produce a result.
Compute the report.
Stage
A set of tasks separated by dependencies.
Scan stage; merge stage.
Task
One scheduled unit of execution.
Read the partition for region R1.
DAG
The graph of computation dependencies.
Read → filter → group → result.
Lineage
The steps used to recompute lost data.
Read and filter again after a failure.
Shuffles and optimisation
Term
Simple meaning
Payment example
Shuffle
Redistribution of data between partitions.
Move partial totals by merchant.
Wide dependency
An operation that needs multiple parent partitions.
The merchant aggregation.
Narrow dependency
An operation with limited parent partitions.
Filter inside an input partition.
Repartition
Make a new partition layout, usually with a shuffle.
Change to eight partitions.
Coalesce
Usually reduce partitions without a full shuffle.
Reduce eight partitions to four.
Skew
Uneven data or uneven work.
One merchant has most of the records.
Broadcast join
Distribute a small table to executors.
Send a 50-row merchant lookup.
AQE
Use runtime statistics to adjust some plan steps.
Merge small shuffle partitions.
Logical plan
The operations that a query needs.
Filter and aggregate.
Physical plan
The operations Spark selects to execute.
Scan and hash aggregate.
Pushdown
Apply a supported filter in the source.
HBase can filter rows before transfer.
Storage, memory, and streams
Term
Simple meaning
Payment example
Parquet
A column-based file format.
S3 report export.
Storage partition
A file or table layout based on a key.
Folder dt=2026-10-03.
Cache / persist
Keep reusable data in storage.
Reuse successful payment rows.
Spill
Write intermediate data to disk under memory pressure.
A large group can spill.
Checkpoint
Save a recovery point to reliable storage.
Store streaming query progress.
Micro-batch
One small batch of new stream input.
Process recent payment events.
Watermark
A limit for late events in supported stateful operations.
Manage a time-window state.
Spark UI
A web view of jobs, stages, tasks, and metrics.
Find a slow scan task.
HBase and Spark connection
Term
Simple meaning
Payment example
Row key
The ordered identifier for an HBase row.
01#TXN1003.
Region
A row-key range of an HBase table.
Region R2.
RegionServer
A process that serves assigned regions.
RegionServer A.
Region split
An operation that makes two daughter regions.
Split R2 into R2a and R2b.
InputSplit
A description of one unit of input scan work.
Read one region with TableInputFormat in this example.
WAL / MemStore
HBase write log and memory buffer.
Process a payment write.
HFile / compaction
A storage file and an operation that merges storage files.
Organise stored cells.
REMEMBER · SPARKApplication → Jobs → Stages → TasksOne task processes one stage partition.
REMEMBER · HBASETable → Regions → RegionServers
The arrows show the relation between the terms. They do not show that Spark always makes one job or that every connector uses one InputSplit per region.