# The cluster went away. The shuffle did not.

> EMR Serverless went into preview at re:Invent, so I finally sat down with Apache Spark. Notes from the first fortnight: why nothing runs until something has to return, why the partition is the unit of parallelism, and a default of 200 that has nothing to do with your data.

- Author: Deyan Peev (https://deyanpeev.com)
- Published: 2022-01-23
- Tags: AWS, Amazon EMR, Apache Spark, Serverless, Python, Docker, Data Engineering
- URL: https://deyanpeev.com/posts/the-cluster-went-away-the-shuffle-did-not

My working days at the moment are a
[Windows agent for Jenkins](https://deyanpeev.com/posts/a-windows-agent-for-jenkins) and a build that
signs things, which is about as far from distributed data processing as you can
get while still using a computer. So this is a weekend post, and a beginner's
one. I've read about Apache Spark for years, the way you read about a city you
haven't visited. Until this month I had never written a job in it.

What finally moved me was
[Amazon EMR Serverless](https://aws.amazon.com/about-aws/whats-new/2021/11/amazon-emr-serverless-preview),
announced in preview at re:Invent at the end of November. The pitch is that you
stop provisioning a cluster. I've watched enough people spend a fortnight on
node counts and instance families to find that interesting. It also raised the
question I wanted answered. If the cluster stops being my problem, what's left
that still is?

# Applications and job runs

The model has two nouns. An **application** is the long-lived thing you create,
and it pins two choices, the open-source framework and the Amazon EMR release
that fixes its version. A **job run** is a request you submit to that
application (a PySpark script, a Hive query), which it executes asynchronously
and tracks to completion. You can have many job runs against one application,
running concurrently, each with its own runtime IAM role for reaching S3.

Underneath, the application uses workers. EMR Serverless works out what a job
needs, provisions workers, scales them up and down through the stages of the
job, and decommissions them at the end. There's an optional pre-initialized
capacity setting that keeps a warm pool ready so jobs start in seconds instead
of waiting for provisioning. It is aimed at the iterative case, where you're
running the same job over and over with small changes.

Compared with EMR on EC2, a long list of questions goes away. How many core
nodes, which instance family, task nodes on spot and what happens when they go
away, whether the cluster is long-lived or transient, and if transient, what
terminates it when a job hangs. I don't think any of those have good answers
available in advance, and they're all things I would rather not become good at.

In January this is still a preview. You put your name on a form, it runs in
N. Virginia only, and the frameworks are Spark 3.1.2 and Hive 2.0. I signed up
and have been waiting, and the wait was the useful bit of the month, because it
sent me off to learn the thing the service runs.

# So I pinned a local Spark to the version in the preview

There's no point learning Spark 3.2 semantics for a preview that runs 3.1.2, so
I matched it and kept the loop on my laptop:

```bash
docker run --rm -it \
  -v "$PWD":/work -w /work \
  -p 4040:4040 \
  apache/spark-py:v3.1.2 /opt/spark/bin/pyspark
```

Port 4040 is what I'd tell a past version of myself to open first. The Spark UI
while a job is running is the only reason the rest of this post makes sense to
me. It shows jobs, stages, tasks and the time each one took, and it's a far
better teacher than the documentation.

The dataset is dull. A few hundred megabytes of CSV that I already had, with a
category column and an amount column.

```python
from pyspark.sql import functions as F

events = spark.read.csv("/work/data/", header=True, inferSchema=True)

recent = events.filter(F.col("amount") > 100).select("category", "amount")
totals = recent.groupBy("category").agg(F.sum("amount").alias("total"))

totals.show()
```

Six lines, and three things in them that I had wrong.

# Nothing runs until something has to come back

The `filter` and the `select` don't filter or select anything. They build a
plan. Spark separates transformations, which are lazy and only describe work,
from actions, which force it (`show`, `count`, `collect`, writing to storage).
Until `totals.show()`, nothing has read a byte.

This sounds like trivia, but it means that what you time is almost never what
is slow. My first instinct was to measure line by line, and every line took no
time at all until one of them took all of it.

It's more useful to ask for the plan than to guess at it:

```python
totals.explain()
```

The physical plan it prints has the `Exchange` steps in it, and those are the
ones that cost.

# The partition is the unit of parallelism, not the machine

I had a vague picture of Spark spreading work across machines, and that picture
is wrong right where it matters. Work is spread across **partitions**, and a
task processes one partition. How many partitions you have is decided by how
your data is laid out. How many workers you asked for doesn't come into it.

```python
events.rdd.getNumPartitions()
```

You hit this straight away with compressed files. A gzipped CSV can't be split,
because nothing can start reading it from the middle, so however large it is,
it's one partition, and it is one task on one core while everything else in
your expensive cluster watches. My first run used gzipped input and was
perfectly, uniformly slow no matter what I gave it. Snappy-compressed Parquet
doesn't have that problem, so the fix was a format change and had nothing to do
with capacity.

Ten thousand tiny files are the same mistake the other way round. Thousands of
partitions, each with real scheduling overhead, each doing almost nothing.

# Some operations have to move data, and those are the ones that hurt

The distinction that made the rest fall into place for me is narrow against
wide. A narrow transformation (`filter`, `select`, a per-row function) can be
done inside a partition, no coordination needed. A wide one, like `groupBy`,
`join`, `distinct` or `repartition`, needs rows that share a key to end up in
the same place, and the rows aren't in the same place. So they get written out,
moved across the network, and read back in. That's a shuffle, and it is a stage
boundary.

My six-line job has one, at the `groupBy`. Everything before it is free in
comparison. Once I started reading a plan by looking for `Exchange` first and
ignoring the rest, the Spark UI stopped being a wall of numbers and became a
short list of things to care about.

# The default of 200

When Spark shuffles, the number of partitions it shuffles into comes from
`spark.sql.shuffle.partitions`, and the default is 200, whatever my data, my
cluster or my job.

On the few hundred megabytes I was playing with, that's 200 tasks, most of
them processing a trivial amount of data, each paying scheduling cost, and 200
output files if I write the result. My aggregation over a small dataset spent
most of its wall-clock time on the overhead of pretending to be big. Setting it
sensibly:

```python
spark.conf.set("spark.sql.shuffle.partitions", 8)
```

took the job from tens of seconds to a few. On a large dataset the
same default is the opposite mistake, and 200 is far too few.

8 is right for my laptop and my toy file and that's all. The proper answer
depends on data volume and available cores. What does generalise is that this
knob has a fixed default, and that default has no relationship at all to the
the problem. It also sits on the critical path of most jobs anyone writes.

# What serverless automates, and what it does not

EMR Serverless scales workers to the parallelism a job asks for at each stage,
which is useful, but it can't change what the job asks for. It won't choose a
shuffle partition count for me, or notice that one key holds forty per cent of
the rows, or pick a different join strategy, or object that I've pointed it at
ten thousand small files.

And there is a sting in that which I hadn't thought about before this month.
On a cluster I have already paid for, a badly partitioned job wastes capacity
that was sitting there anyway, and the cost is my afternoon. On a service that
provisions and meters resources per job, the same inefficiency goes straight
onto a bill. Two hundred near-empty tasks occupy real workers for real seconds.
So serverless still needs Spark tuning. It moves it from a capacity problem,
where the waste is invisible, to a cost problem, where it is itemised.

I get to stop having opinions about instance families, and in exchange I pay
for what I don't know about partitioning.

# A fortnight in

I haven't got far. I can write a PySpark job, read its plan, find the shuffle,
and explain why it is there. I have no production experience of Spark at all,
and everything above is a fortnight of weekends against a small file on one
machine, which is about the setting where distributed systems tell you the
least.

The plan for when the preview opens up is unglamorous. Take one job that means
something, run it on a small EMR cluster and on EMR Serverless with the same
input, and compare the wall-clock and the bill instead of the adjectives. Use
pre-initialized capacity for the iteration loop, because waiting on provisioning
between attempts is how people stop iterating. And keep the local 3.1.2 container
for learning. I still think the fastest way to understand a shuffle is to cause
one on a laptop and watch it happen on port 4040.
