Spark hands-on: processing massive data without burning the cluster
Hands-on Apache Spark guide: architecture, DataFrames, partitions, shuffles, joins, caching, AQE, Parquet and Iceberg, and when not to use it.
Table of Contents
It is 11:30 p.m., and the job that feeds the sales report has been stuck at 87% for four hours. On your laptop, with a two-million-row sample, the same code finishes in forty seconds. On the cluster, with three hundred GB, it looks like someone turned off the lights.
Spark did not suddenly get slow. The data volume changed, and with it the way the engine moves data around. A harmless groupBy that runs fine locally becomes a terabyte exchange between machines in production, with one giant partition dragging everything behind it.
This guide is hands-on: each section explains one piece of the engine and grounds it in runnable code. By the end you will know how to read a plan, spot the shuffle that is killing your job, and decide when Spark is actually the right tool.
What Spark is and what it actually solves
Apache Spark is a distributed processing engine. It splits a computation across several processes, each with its own memory, and coordinates the result as if it were a single operation. It started with batch workloads, but today it covers SQL, structured streaming, machine learning, and graphs through one API.
It is not a database. It does not store your tables transactionally or compete with PostgreSQL to serve an API. It is a compute layer that reads from external storage, transforms data, and writes somewhere else.
| Tool | Scale | When to use it |
|---|---|---|
| DuckDB or Polars | One machine | Data that fits on local disk, ad hoc analysis |
| Spark | Cluster | Terabytes, batch pipelines, joins across large datasets |
| Managed warehouse | Managed cluster | Concurrent BI, governance, business SQL |
The real question is not “how much data do I have?” but “is distributing this computation cheaper than doing it on one machine?” If the answer is no, Spark adds complexity without giving anything back.
Driver, executors, and the cluster manager
The architecture has three pieces. The driver runs your main(), creates the SparkSession, and builds the plan. Executors are processes on worker nodes that run tasks and keep data in memory or on disk. The cluster manager —YARN, Kubernetes, or standalone mode— hands out resources.
flowchart LR
D[Driver] --> CM[Cluster manager]
CM --> E1[Executor 1]
CM --> E2[Executor 2]
E1 --> S[(External storage)]
E2 --> S
Each application gets its own executors and shares no memory with others; exchanging data means going through an external system. The driver must be reachable from the nodes, so in production it lives inside the cluster, not on your laptop.
from pyspark.sql import SparkSession
spark = (
SparkSession.builder
.appName("daily-sales")
.master("local[*]")
.config("spark.sql.shuffle.partitions", "8")
.getOrCreate()
)
That master("local[*]") is for your machine. In a cluster you do not hardcode it: spark-submit passes it, and the driver negotiates executors with the cluster manager.
RDDs, DataFrames, and Spark SQL
An RDD is a distributed collection of objects with no schema. You get full control over transformations, but the engine knows nothing about your columns and cannot optimize the plan.
A DataFrame is a table with a schema. Catalyst, the optimizer, reorders filters, picks joins, and drops unused columns. Tungsten generates Java code underneath and avoids allocating one object per row. Spark SQL is the same path, expressed as SQL.
from pyspark.sql import functions as F
events = spark.read.json("s3://bucket/events/2026-12-*/")
summary = (
events
.filter(F.col("event_type") == "purchase")
.groupBy("country")
.agg(
F.count("*").alias("purchases"),
F.sum("amount").alias("revenue"),
)
)
summary.show(10, truncate=False)
The code declares three operations and executes none of them yet. show() is the action that triggers the job. That detail, lazy evaluation, is the foundation for everything that follows.
Lazy evaluation: the plan before the action
When you write transformations, Spark builds a logical plan. Catalyst optimizes it: pushes filters down, prunes columns, reorders joins, and chooses the exchange type. Only when you ask for a materialized result does Spark produce a physical plan and split it into tasks.
summary.explain("formatted")
The output shows operators such as Scan json, Filter, HashAggregate, and Exchange. Exchange is the signal to look for: it means Spark will redistribute data across executors. A plan with several nested Exchange nodes is a plan with several shuffles, and each one costs disk, network, and serialization.
Narrow transformations —select, filter, withColumn— process each partition without moving data. Wide transformations —groupBy, join, distinct, repartition— force an exchange. That is the difference between a twenty-minute job and a four-hour one.
Partitions: the unit of parallelism
Each partition runs as one task. With twenty partitions and a hundred cores, eighty cores watch the other twenty work. With ten thousand tiny partitions, scheduling overhead eats the compute time.
When reading files, Spark splits the input according to spark.sql.files.maxPartitionBytes, which defaults to 128 MB. On a shuffle it uses spark.sql.shuffle.partitions, defaulting to 200. That 200 is wrong for almost everything: too many for a small job, too few for a multi-TB one.
print("current partitions:", summary.rdd.getNumPartitions())
by_country = summary.repartition(16, "country")
compact = summary.coalesce(4)
repartition performs a full shuffle; coalesce only merges adjacent partitions and avoids the shuffle, but it can create imbalance if you shrink too aggressively. Aim for 100 to 200 MB per partition and two to three tasks per core.
Shuffles: the cost of moving data
A shuffle writes intermediate data to local disk, groups it by key, and sends it over the network to the right executor. It is the most expensive operation in Spark and the cause of most slow jobs.
# Join first, filter later: the shuffle moves the whole dataset
joined_bad = sales.join(customers, "customer_id").filter(F.col("country") == "MX")
# Filter and project before the join: the shuffle moves much less
sales_mx = sales.filter(F.col("country") == "MX").select("customer_id", "amount")
customers_mx = customers.select("customer_id", "segment")
joined_good = sales_mx.join(customers_mx, "customer_id")
Both plans return the same rows. The second moves only the columns and rows it needs; Catalyst pushes some filters for you, but it cannot guess that country correlates with customer_id.
It also helps to aggregate before joining, avoid distinct on wide rows, use reduceByKey instead of groupByKey with RDDs, and skip repartitioning for no reason.
Joins: broadcast, sort-merge, and skew
Spark chooses between several algorithms. A broadcast hash join copies the small table to every executor and avoids shuffling the large one. It activates only when the table fits under spark.sql.autoBroadcastJoinThreshold, 10 MB by default, or when you force it with a hint.
A sort-merge join is the general path: both sides are partitioned by key, sorted, and merged. A shuffled hash join builds a hash table per partition and is often faster when the build side fits in memory. AQE can turn a sort-merge join into a shuffled hash join when it detects a small build side.
customers = spark.read.parquet("s3://lake/dim/customers/")
joined = (
sales
.join(F.broadcast(customers), "customer_id")
.groupBy("segment")
.agg(F.sum("amount").alias("revenue"))
)
Broadcast is powerful and dangerous: if the table is not small, every executor tries to materialize it and the job dies from memory pressure. Raise the threshold only when you know the dimension’s size after filtering.
Skew is the other enemy. If one key holds 40% of the rows, one task processes 40% of the shuffle while the rest finish. AQE splits abnormally large partitions; when skew is structural, salting —a random suffix on the key plus a replicated dimension— is still the manual escape hatch.
Caching: the shortcut that also charges you
cache() stores a DataFrame’s result in memory and on disk so it can be reused. It pays off when the same dataset is consumed several times: training multiple models, computing different metrics, or feeding several dashboards inside one job.
clean_sales = (
sales
.filter(F.col("status") == "paid")
.select("customer_id", "date", "amount")
.cache()
)
clean_sales.count() # materializes the cache
total = clean_sales.agg(F.sum("amount")).first()[0]
by_month = clean_sales.groupBy(F.month("date")).sum("amount")
clean_sales.unpersist()
cache() is lazy: nothing is stored until the first action. count() forces that materialization. Without it, the first real computation fills the cache and the second benefits, but the first gains nothing.
Do not cache by reflex: the cache competes with shuffles and can evict blocks that mattered. If the DataFrame is computed only once, you just added overhead.
Tuning: executors, memory, and AQE
Executor sizing is a trade-off between parallelism and memory. Many small executors waste resources; a few huge ones trigger GC pauses. A reasonable starting point is four or five cores per executor and 8 to 16 GB of heap.
Spark uses a unified region for execution and storage. spark.memory.fraction controls the percentage of heap minus 300 MB assigned to that region (0.6 by default), and spark.memory.storageFraction reserves a slice for caching (0.5). Raising them without measuring usually makes GC worse.
spark-submit \
--master yarn \
--deploy-mode cluster \
--conf spark.executor.instances=10 \
--conf spark.executor.cores=4 \
--conf spark.executor.memory=8g \
--conf spark.executor.memoryOverhead=1g \
--conf spark.sql.shuffle.partitions=400 \
--conf spark.sql.adaptive.enabled=true \
--conf spark.sql.adaptive.coalescePartitions.enabled=true \
--conf spark.sql.adaptive.advisoryPartitionSizeInBytes=128m \
jobs/daily_sales.py
spark.executor.memoryOverhead covers native memory, network buffers, and Python containers. It defaults to the larger of 384 MB and 10% of executor memory; coming up short produces container kills that look like logic errors.
AQE has been enabled by default since Spark 3.2. It coalesces partitions based on actual size, converts joins, and splits skewed partitions. With AQE, set a high initial partition count and let the engine adjust to spark.sql.adaptive.advisoryPartitionSizeInBytes.
Parquet and Iceberg: persisting without regret
Parquet is columnar, compressed, and self-describing. It stores per-row-group statistics —min, max, null counts— and lets a filter skip entire blocks. It is the default analytical format for a reason.
(
summary
.repartition(8, "country")
.write
.mode("overwrite")
.partitionBy("country")
.option("compression", "zstd")
.parquet("s3://lake/sales/summary/")
)
Partitioning by a low-cardinality, frequently filtered column such as country or date reduces what a query reads. Doing it by customer_id creates thousands of tiny folders. A thousand 2 MB files are worse than ten 200 MB files.
Iceberg adds transactions, schema evolution, time travel, and hidden partitioning on top of Parquet. The table stops being a folder and becomes a set of snapshots with consistent metadata.
spark = (
SparkSession.builder
.appName("sales-iceberg")
.config(
"spark.sql.extensions",
"org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions",
)
.config("spark.sql.catalog.lake", "org.apache.iceberg.spark.SparkCatalog")
.config("spark.sql.catalog.lake.type", "hadoop")
.config("spark.sql.catalog.lake.warehouse", "/tmp/warehouse")
.getOrCreate()
)
With the Iceberg runtime on the classpath and the catalog configured, the DataFrame writes as an Iceberg table partitioned by date. The advantage shows up when you need a MERGE, read an older version, or add a column without rewriting everything.
spark.sql("CREATE SCHEMA IF NOT EXISTS lake.db")
(
clean_sales.writeTo("lake.db.sales")
.using("iceberg")
.partitionedBy("date")
.createOrReplace()
)
In production the catalog is usually REST, Hive Metastore, or a managed service, not hadoop over a local directory. The mental model does not change: the table is logical, files are immutable, and maintenance —compaction, snapshot expiry— is part of the job.
Real scenarios and common mistakes
A ninety-day backfill
A daily pipeline failed for three months and now needs reprocessing. The pattern is to iterate by date, filter early, and write each partition separately. A single job that reads ninety days and runs a global groupBy will shuffle everything at once.
for day in days:
(
spark.read.parquet(f"s3://lake/events/dt={day}/")
.filter(F.col("event_type") == "purchase")
.groupBy("country")
.agg(F.count("*").alias("purchases"))
.write
.mode("overwrite")
.parquet(f"s3://lake/summary/dt={day}/")
)
Daily granularity lets you retry only the date that failed. It also prevents a skew problem on one day from contaminating the whole run.
Event ingestion
Read raw JSON, validate the schema, flatten structs, and write Parquet partitioned by date. Data quality matters more than speed here: a schema inferred from a sample can turn a numeric field into a string and break every downstream aggregation. Declare the schema explicitly.
Mistakes that keep coming back
- Driver OutOfMemory from
collect()on a large dataset. The driver is not a compute node; usewriteor aggregations. - Executor OutOfMemory from skew or an oversized broadcast. Check the real size, not the estimate.
- Thousands of small files from writing with too many partitions. Compact before publishing.
- Python UDFs where a native function exists. A UDF serializes row by row and disables part of the optimization.
coalesce(1)to produce a single file. It works, but it funnels all output through one task.- ANSI errors after upgrading to Spark 4. ANSI mode is on by default and turns invalid casts into exceptions; review implicit conversions.
- Joins on keys with different types. An
intagainst astringforces a cast and can ruin pushdown.
When not to use Spark, and a checklist
Spark is not the answer to everything. If your data fits on one machine, DuckDB or Polars will give you the same answer in seconds with no infrastructure. If you need millisecond latency per request, this is a batch engine, not a database. If the work is a SELECT on a warehouse, the warehouse already does it better.
Do not use it as an orchestrator either. Spark runs computation; job dependencies, retries, and alerts belong to Airflow, Dagster, or Temporal.
Before you submit the next job, run this checklist:
- Does the dataset really not fit on one machine?
- Did you declare the schema instead of inferring it?
- Did you filter and project before joins?
- Did you read
explainand count theExchangenodes? - Does the partition count match the data size?
- Is the broadcast side actually small?
- Is there skew in the join key?
- Is the cache reused more than once?
- Do output files land between 100 and 200 MB?
- Can the job be retried per partition without reprocessing everything?
Spark does not spread magic across machines. It spreads work, and it charges you every time a row changes location. The difference between a comfortable team and one that keeps putting out fires is knowing when that trip is worth it.
Related articles
By relevance
The modern data analytics stack in 2026: from giant Excel files to the AI-powered lakehouse
Informative guide to the 2026 data stack: DuckDB, Polars, Iceberg, Parquet, AI, log observability, and how to read large files fast.
Parquet deep dive: a hands-on guide to the format behind the modern data stack
Hands-on Parquet guide: row groups, compression, partitions, metadata, Polars, DuckDB, and how to read large files with real speed.
Data Extraction, SQL & Automation in Go: Building Scalable Data Systems
Master data engineering in pure Go. Learn SQL querying, data extraction from multiple sources, transformation pipelines, automation workflows, and scientific data processing—all without external dependencies.
Full Stack Go: Notes and Todos App with HTMX, Templ and SQLite
Build a complete Notes and Todos app in Go: markdown notes with tags, todo checklists, full-text search, auth, HTMX reactivity, Templ templates, and SQLite.