Execution Model: Intermediate
One action, one job
| Level | Started by | How many | What one of them is |
|---|---|---|---|
| Job | an action: collect, count, write | 1 per action | the whole computation behind that action |
| Stage | a point where rows must move between partitions | shuffles + 1 | code that runs on a partition without needing another |
| Task | a partition inside a stage | partitions in that stage | the stage's code applied to 1 partition on 1 slot |
One program, 3 stages
(orders.filter(F.col("status") == "completed").withColumn("net", F.col("amount") - F.col("discount")).groupBy("region").agg(F.sum("net").alias("revenue")).orderBy(F.col("revenue").desc()).collect())
| Stage | Tasks | Rows in | Shuffle write | Shuffle read | Ends with |
|---|---|---|---|---|---|
| 0 | 2 | 6 from the files | 5 rows | 0 | groupBy on region |
| 1 | 2 | 5 from stage 0 | 3 rows | 5 rows | orderBy on revenue |
| 2 | 2 | 3 from stage 1 | 0 | 3 rows | collect to the driver |
The Jobs tab and the stage page
- ▸First stage: 1 task per input partition, decided by how the input files are split
- ▸Each stage after a shuffle: 1 task per shuffle partition, 200 by default, with adaptive execution off as this lesson assumes
- ▸Whole job: add the stages, so 8 + 200 + 200 = 408 tasks for a read, a groupBy and an orderBy
How many stages does this job run, and where is the boundary?
A task only sees its partition
(events.filter(F.col("kind") == "click").withColumn("ms", F.col("secs") * 1000).collect())
The operation that needs every partition
| Operation | Needs rows from other partitions? | Effect on stages |
|---|---|---|
| filter, select, withColumn, drop | no, each row is handled on its own | stays in the current stage |
| union of 2 DataFrames | no, partitions are stacked end to end | stays in the current stage |
| groupBy, agg, distinct | yes, all rows of a key together | ends the stage with a hash shuffle |
| join on a key, both sides large | yes, matching keys together | ends the stage, both sides shuffled |
| join to a table under 10MB | no, the small table is copied to every task | stays in the current stage |
| orderBy, sort | yes, rows arranged by range | ends the stage with a range shuffle |
| repartition(n) | yes, rows dealt into n new partitions | ends the stage |
Stage boundaries cost time and bytes
- rows flow between operations in memory, 1 row at a time
- a task finishing early frees its slot for the next task of the same stage
- cost scales with the rows in each partition
- nothing is written to disk
- every row is written to local disk and read back over the network
- the next stage waits for the slowest task of this one
- cost scales with the bytes shuffled
- the task count resets to the shuffle partition setting
How many stages does this job run?
Where the task count comes from
The first stage of a job gets 1 task per input partition, and Spark fixes that count when it plans the read. Each input split is at most 128MB, the default of spark.sql.files.maxPartitionBytes, and smaller when the total bytes divided by the cluster's cores is smaller, so a small read is spread across every core. A single 1.2GB file on a 32-core cluster is cut into pieces of roughly 38MB, about 32 of them; the same file on a 4-core laptop is cut into 128MB pieces, 10 of them. A directory of 10 gzip files of 120MB each reads as 10 partitions on any cluster, because a gzip file can't be split and each one becomes 1 task. Every stage after a shuffle gets 1 task per shuffle partition, and that count comes from 1 setting, spark.sql.shuffle.partitions, which is 200 unless you change it. With adaptive execution off, the setting this lesson's examples assume, the data has no vote: a groupBy over 3 distinct keys still runs 200 tasks, and 197 of them open an empty bucket, find nothing, and finish in a few milliseconds each. With adaptive execution on, 200 is the starting count and Spark may merge empty and small buckets into fewer tasks, which a later lesson covers.
spark.conf.set("spark.sql.shuffle.partitions", 4)(page_hits.groupBy("device").agg(F.count("*").alias("hits")).collect())
Tasks, slots and waves
| Stage | Tasks | Slots | Waves | Slots idle in the last wave |
|---|---|---|---|---|
| read, 10 gzip files | 10 | 32 | 1 | 22 |
| groupBy, default setting | 200 | 32 | 7 | 24 |
| groupBy, 64 shuffle partitions | 64 | 32 | 2 | 0 |
| groupBy, 3 keys, default setting | 200 | 32 | 7 | 24, and 197 tasks carry no rows |
Reading it on the stage page
A job reads a directory as 6 input partitions, groups by customer with spark.sql.shuffle.partitions at its default, and collects. The cluster has 12 executors with 4 cores each. How many tasks run in each stage, and in how many waves?
(order_items.filter(F.col("product_id") > 0)
.groupBy("product_id")
.agg(F.sum("quantity").alias("units"))
.orderBy(F.col("units").desc())
.collect())One process, 2 places to run it
In client mode the driver lives in the laptop's spark-submit process and talks to the executors directly, so every task result and every collect() crosses the laptop's link. In cluster mode the cluster manager starts the driver in a container on a worker node beside the executors, and the laptop sends only the script and its flags.
Driver placement and collect()
| Concern | Client mode | Cluster mode |
|---|---|---|
| Where collect() rows land | in the launching machine's memory, over its link to the cluster | in a cluster node's memory, on the datacenter network |
| Closing the laptop or the SSH session | kills the driver, and the job with it | changes nothing, the driver keeps running |
| Driver stdout and print() output | in your terminal or notebook | in the cluster manager's log for the driver container |
| A local file path read by the driver | reads from your disk | reads from the cluster node's disk, where the file may not exist |
| Driver RAM | your machine's, sized with --driver-memory | a cluster node's, sized with --driver-memory |
| Typical use | notebooks and debugging | scheduled production jobs |
The collect() row matters most day to day. An action that returns 800MB of rows sends 800MB to the driver, and in client mode that 800MB crosses whatever link the launching machine has to the cluster: on a 100Mb/s VPN it is around 64 seconds of transfer before a result appears, while in cluster mode the same 800MB stays on a 10Gb/s datacenter link and arrives in under a second. The executors finished their tasks at the same moment in both runs; the job's stages are identical, and only the last hop differs. The driver's memory is the other half of the same story: those 800MB have to fit in the driver's heap wherever it lives, which is what --driver-memory sizes. A collect() larger than 1GB also needs spark.driver.maxResultSize raised, because at its default of 1g Spark aborts the job once the serialized results pass that size.
Local mode, started with --master local[4], runs the driver and 4 task threads in one process on your machine, with no separate executor processes and no cluster. It's the right setting for a unit test on sample data and the wrong one for anything you time.
- ▸Does closing your terminal kill the job? Then the driver is in client mode on your machine
- ▸Does print() output appear in the cluster manager's log instead of your screen? Then it's cluster mode
- ▸Does a local path in the script read a file that only exists on your laptop? Only in client mode
A nightly job is launched from a gateway host with --deploy-mode client. The gateway reboots for patches at 03:00 and the job dies every time. The job's last step calls collect() on an 800MB result. What does switching to --deploy-mode cluster change?
The flags that shape a job
| Flag | Property | What it sets |
|---|---|---|
| --master | spark.master | which cluster manager runs the job, or local[N] for one machine |
| --deploy-mode | spark.submit.deployMode | client or cluster: where the driver process runs |
| --num-executors | spark.executor.instances | how many executor processes to request |
| --executor-cores | spark.executor.cores | slots per executor |
| --executor-memory | spark.executor.memory | heap per executor, such as 8g |
| --driver-memory | spark.driver.memory | heap for the driver, where collect() results must fit |
| --conf key=value | that key | any property, such as spark.sql.shuffle.partitions=64 |
| --py-files | spark.submit.pyFiles | extra Python modules shipped to every executor |
A full command for a nightly report reads spark-submit --master yarn --deploy-mode cluster --num-executors 8 --executor-cores 4 --executor-memory 8g --driver-memory 4g --conf spark.sql.shuffle.partitions=64 daily_report.py. Written as properties, which is how a defaults file and the Environment tab both show it:
Code beats flag beats defaults file
A property can be set in 3 places, and when they disagree the order is fixed: a value set in code through SparkSession.builder.config beats a spark-submit flag, which beats the cluster's defaults file. One exception matters more than the rule. Driver settings in code arrive too late, because the driver process they describe is already running by the time your script executes, so --driver-memory and --deploy-mode take effect only on the command line or in the defaults file. Executor settings and spark.sql.shuffle.partitions in code do take effect, since executors are requested and plans are built after the session exists. The Environment tab shows the value in force, so a stage with 200 tasks after you asked for 64 on the command line means a value set in code overrode the flag, and the tab shows which value won.
- Set spark.sql.shuffle.partitions to a multiple of your slot count, so the last wave is full
- Put --driver-memory and --deploy-mode on the command line, where they take effect
- Open the Environment tab after launch to confirm which value won
- Submit scheduled jobs in cluster mode and keep client mode for notebooks
- Don't leave 200 shuffle partitions for a groupBy over 3 keys and then read 197 empty tasks
- Don't set spark.driver.memory in builder.config and expect the driver to grow
- Don't request more slots than your biggest stage has tasks; the extras idle
- Don't change 3 flags at once; change 1, rerun, and read the stage page again
A job is submitted with --num-executors 6 --executor-cores 5 --conf spark.sql.shuffle.partitions=90, and its script sets nothing. Its groupBy stage: how many tasks, how many slots, how many waves?
> Back at Netflix, the engineer opens the Jobs tab for the 3-hour viewing report: 1 job, 3 stages, and stage 1 holds 2 hours 40 minutes of it. Its page reads Tasks: 200/200 on 8 executors with 4 cores, so 7 waves, and the Event Timeline shows 197 tasks finishing in under a second while 3 tasks read most of the shuffle bytes and run for hours. The launch command says --deploy-mode client from a gateway host, and the final 800MB collect() crawls over that gateway's link. She sets shuffle partitions to 64, which trims a few seconds of empty-task scheduling and tidies the timeline, and resubmits in cluster mode with --driver-memory 6g, which takes the gateway out of the last hop. Neither change touches the 2 hours 40 minutes: the 3 heavy tasks still set the stage's time, and the stage page has now isolated them as the one problem left.
collect() moved from the gateway's link to a cluster node once the driver did, and --driver-memory grew so the result fits in its heap.spark.sql.shuffle.partitions tasks, 200 by default, whatever the data holds.collect() results and driver logs follow the driver.Count stages before you run, read task counts against slots, and know where the driver lives before you tune.
- Category
- Spark
- Difficulty
- intermediate
- Duration
- 12 minutes
- Challenges
- 12 hands-on challenges
Topics covered: Job, Stage, Task, Why Stages Exist, Reading Parallelism, Where the Driver Lives, The spark-submit Config Surface
Lesson Sections
- Job, Stage, Task (concepts: Spark Execution Model)
One action, one job Every action you call sends 1 job to the cluster. Spark walks back through the transformations that feed the action, cuts the chain wherever rows have to move between partitions, and calls each piece a stage. Inside a stage the work is a set of tasks, 1 task per partition, every task running the same code on its own slice of the data. A job of 3 stages whose stages hold 8, 200 and 200 partitions is 408 tasks, and the Jobs tab counts them exactly that way. A task is the unit t
- Why Stages Exist (concepts: Spark Execution Model)
A task only sees its partition A task runs on 1 slot with 1 partition in hand, and it can see nothing else. It reads a row, tests it, computes a new column from it, and passes it on, because everything those operations need is in that row. Spark chains such operations so a row flows through filter, then withColumn, then select without being written anywhere in between. A partition of 500,000 rows passes through 4 such operations in a single sweep, producing 1 output partition from 1 input partit
- Reading Parallelism
Where the task count comes from The program below sets 4 shuffle partitions and groups 9 hits read as 3 partitions. Stage 0 runs 3 tasks, 1 per input partition. Stage 1 runs 4 tasks, 1 per shuffle partition, and because only 3 devices exist, at least 1 of the 4 tasks reads an empty bucket and contributes nothing. The driver receives mobile 4, desktop 3, tv 2. Tasks, slots and waves The cluster offers a fixed number of slots: executors times cores per executor. A stage with more tasks than slots
- Where the Driver Lives
One process, 2 places to run it The driver is the process that owns your SparkSession: it turns the code into stages, hands tasks to executors, and receives whatever an action returns. spark-submit can put that process in 2 places. In client mode the driver runs inside the process that ran spark-submit, on the machine where you typed the command: a laptop, a gateway host, or the kernel behind a notebook. In cluster mode spark-submit hands the application to the cluster manager and returns, and t
- The spark-submit Config Surface (concepts: Configuration Tuning)
The flags that shape a job spark-submit is the command that ships your script to a cluster, picks where the driver runs, and asks the cluster manager for executors. Everything the earlier sections counted, slots, waves and the driver's address, is decided by a handful of its flags, and each flag is also a property you can set in a defaults file or in code. The table maps one to the other, because the Environment tab of the UI shows the property name, never the flag. The command describes a clust