Ch.1: How Apache Spark Actually Works
Outline
- 0:00 Same job, bigger data
- 0:41 Move 1: partitions
- 1:29 Move 2: the driver and executors
- 2:33 Move 3: nothing runs until an action
- 3:47 Where Spark came from
- 5:05 Memory is a fast lane, not a wall
- 6:14 Move 4: the shuffle
- 7:36 One job, stage by stage
- 9:02 What PySpark really runs
- 10:34 DataFrames vs RDDs
- 11:43 Learn Spark or Databricks?
- 12:39 Do you even need Spark?
- 14:05 When to reach for Spark
Transcript
0:00 Say you've got a pandas job that handled last month's page-view events in under a minute. This month the data is a few hundred times bigger, and the same job dies with a memory error before it prints anything. And the advice you usually get next is, just use Apache Spark. Which can work, but most people then treat Spark like a magic box. Code goes in, answers come out, and when it's slow or it crashes, nobody can really say why. So let's open the box. We'll walk one job from a laptop to a cluster, and you'll see the four moves Spark makes.
0:35 Once you know them, a lot of slow jobs and crashes stop looking random. First move, and it's one pandas doesn't make for you: Spark cuts the data into pieces called partitions. A partition is basically a slice of the rows that one task can handle on its own. Pieces meaning files? Or does Spark get to pick where it cuts? Spark picks. When it reads files, it packs at most 128 megabytes into each partition by default, so this month's 500 gigabytes lands in roughly 4,000 pieces. Then it runs one task, a single unit of work, per partition.
1:11 Okay, but nobody's renting 4,000 machines just to count a month of page views. No, and you don't have to. A few dozen machines each take a share and run several tasks at once, which means the whole pile gets chewed through side by side. Next, someone has to hand out all those tasks, and that's move two. Spark's own docs call your main program the driver program, and it builds the plan and sends the tasks out. Sends them to what, though? Copies of my Python script on every machine? Not your whole script, no.
1:46 They go to executors, which are long-running processes on the worker machines. Each one runs tasks and holds data for your application, and a cluster manager, Kubernetes for example, kind of hands out the machines in the first place. Oh, so the driver is the only one who sees the whole plan, and each executor just gets its own slice of the work. Right. And anything you pull back, like calling collect to grab every row, funnels into that one driver machine. So if the result is huge, that one machine is in trouble?
2:19 Yep. Spark's programming guide warns that collect can make the driver run out of memory, and the links are in the description. Pull back too much, and that leaves one machine holding what took a whole cluster to compute. That's crash number 1. Then there's move three, which trips up most people coming from pandas. Let's say you write events dot filter to drop the bot traffic, then a group by on product ID. Both lines come back instantly. Wait, so none of that has actually run yet? Nothing has run.
2:51 Those are transformations, and they only add steps to a plan. Work starts when you call an action, something that needs a real result, like show, which prints some rows, or writing the output somewhere. People expect each line to run as they type it, but Spark writes a plan first, then runs it all at once. Okay, that explains a notebook I've seen. Every cell finishes in a blink, you feel brilliant, and then the cell that says show just sits there. Yep, all the waiting moves to the action, which makes debugging feel weird at first.
3:28 But it pays off: Spark sees every step first, so it can optimize everything together instead of one line at a time. So the first habit to unlearn is blaming the slow cell. The slow line in your notebook is where the work finally ran, not the line where you described it. That plan-first design goes back to where Spark came from: a research project at UC Berkeley. The very first Spark paper, from 2010, starts with a complaint about Hadoop MapReduce, the older way to run jobs across a cluster. Honestly, I only know MapReduce as the name people mention right before Spark.
4:05 What was wrong with it? Machine-learning jobs loop over the same data again and again. In MapReduce each pass was its own separate job, and the paper says each job "must reload the data from disk." So every loop paid that cost all over again. Oh, man. That's brutal for anything that loops. So they just stopped rereading it? Yeah, that's the core of it. Load the data into memory across the cluster once, then query it as often as you like. But memory vanishes when a machine dies. Did they just keep copies of everything?
4:39 That would bring back the cost they were escaping. They kept the recipe instead. Spark remembers how every piece was built, so if a machine goes down, it rebuilds just the lost pieces by replaying those steps. Hold on, so the plan from move three is also the backup? Same idea underneath. They called it lineage, the record of how each dataset was made, and it becomes the safety net: no copies, just the recipe. That keep-it-in-memory idea raises a question about our crash, though. The pandas job died because the data outgrew one machine's memory.
5:14 If Spark's whole idea is keeping data in memory, doesn't it just hit the same wall with more machines? Not the way pandas does, and I mean, it's a really common misconception. Spark's FAQ says its operators, the steps like sorting and grouping, "spill data to disk if it does not fit in memory." Memory is the fast lane, not a wall. Okay, that's the opposite of what happened in our opener. Pandas' own docs say it's built for in-memory analytics and call bigger-than-memory data "somewhat tricky." So with the same pile of views, Spark mostly just gets slower where pandas crashed.
5:49 Usually, but not always. Spark's tuning guide says you can still get an out-of-memory error when one task's own share of the work is too large. For example, say a job gathers every view of each product into one big list, and one product is wildly popular. The single task holding that product's list can drown. So crash number 2 comes from the next move. That second crash leads to move four, the one that really costs you: the shuffle. Some steps, like a filter, let each executor chew through its own pieces without talking to anyone. A follow-up Spark research paper in 2012 calls those narrow.
6:30 And a group by is the opposite, because the views for one product are scattered across lots of executors. Right, those are wide steps. To finish one product's answer, everything about that product has to end up in the same place. Think of four friends splitting a deck of cards. Counting your own pile is narrow: nobody moves. But if each of you collects one suit, everyone has to hand cards to everyone else across the table. Yeah, and the table's the network. Every card that crosses it gets written down, packed up, and sent.
7:05 That's why Spark's docs call the shuffle "an expensive operation": it hits the disk, it packs rows into bytes, and it goes over the network. And if half the deck is hearts, the friend collecting hearts gets swamped. There's crash number 2, right there on the table. Exactly, one hot product, one overloaded task. And now you can spot where stages split, too: Spark draws a stage boundary wherever cards have to cross the table, so each stage is work the executors do alone. Now put all four moves on our one job, because I want to see it end to end.
7:41 How does half a terabyte of views turn into one small table of counts per product? Sure. It kicks off when you call write on the result. The driver looks over the entire plan and cuts it at the one spot where rows must change machines, the group by. That gives it two stages. Stage one is about 4,000 tasks. Each task reads its piece, drops the bots, and then does something sneaky: it counts its own views per product first and writes just those running tallies to local disk. Wait, really? It adds up before the trade?
8:19 It does. And then... ...every executor fetches the tallies for its products from everybody else. Right, the cards crossing the table, except they're mostly little tallies, not individual views. So even the hearts friend only gets tallies, which is why a plain count dodges crash number 2. And how would I check that on my own job? Call explain on the DataFrame. It shows every step, and you read it from the bottom up: a partial count, then an exchange, which is Spark's name for the shuffle, then the final count.
8:51 Stage two adds those tallies up per product and writes its slice of the answer. So the whole job is just: everyone works alone, everyone trades, then everyone's on their own again. Yep, that's it. And one more layer sits under all of that if you write Python: PySpark itself. The PySpark docs say it "uses Spark as an engine," and when you start a session, it launches a JVM, the Java runtime Spark itself runs on. A Java runtime? But I'm writing Python. Right, because Spark was written in Scala from the very start, and Scala runs on the JVM.
9:26 So in classic PySpark, your Python is a remote control: your DataFrame code describes the plan, and the engine runs it. Newer setups can even keep that engine on a remote server, but the split stays the same. Okay, but I've definitely written my own little Python functions inside Spark jobs. Where does that code actually run? On the executors. So your guess about copies was half right: your function travels, the rest of your script doesn't. Hang on, aren't executors Java processes? How do they run my Python?
9:58 They start separate Python worker processes, only when your own Python code has to touch the data. So every row it sees crosses from the JVM over to Python and back. In Spark's newest release, a data format called, Arrow is on by default to make that crossing cheaper, but it's still a crossing. Which is why the functions that come with Spark itself are the cheap path: they never leave the engine. Put your own Python function in the hot path, the code that runs on every row, and you're paying for the trip rather than for your one line of logic.
10:34 Now, if you search for help with those Python functions, you'll trip over an acronym in a lot of old answers: RDD. Oh, I've scrolled past plenty of those. That's the old interface, right? Right, same engine underneath. An RDD, a resilient distributed dataset, was the main way to program Spark before Spark two point oh, and the resilient part is that recipe idea from earlier. It sounds lower-level, though. Wouldn't that make it faster? You'd think so. But the docs now flat-out recommend DataFrames, because they perform better.
11:07 Is that because a DataFrame is a table with named columns, so Spark knows what you're doing to the data? That's it. Spark can plan around a table it understands. With an RDD, it mostly sees a pile of objects and your functions. And plain SQL gets that same full picture, so if SQL is what you know, you can write the group by as a query. That sets up an easy habit, too: when an answer opens with RDD code, it's probably from the old days, so reach for the DataFrame or SQL version. Next, the vendor question, because people constantly ask whether to learn Spark or Databricks. Databricks' documentation says Apache Spark is "the technology powering" its compute clusters. So Spark is the engine, and Databricks is one way to rent it.
11:58 And the cloud versions, like Amazon EMR or AWS Glue? Those run Spark too, and Google has its own managed Spark service. They differ in how much of the machinery you see: on classic EMR clusters you manage the machines, while Glue hides them entirely. So it's one engine dropped into four different cars. Different badge, different invoice. One catch, though: what you rent can trail Apache's releases. For example, Amazon's latest EMR release still ships Spark 3.5, while Apache is already on 4.2. A whole major version behind?
12:32 Yep, so check the version your platform actually runs in production, not the one on the newest docs page. Before you rent any of that, though, honestly, I think a lot of jobs that went to Spark 10 years ago don't need it anymore. Okay, but I'm not totally sold. Our pandas job literally crashed. What would you run instead? Pandas isn't the only single-machine tool anymore. For example, Polars is a DataFrame library that spreads work across all your CPU cores and can stream data instead of holding all of it in memory.
13:06 DuckDB is an analytical SQL database that runs inside your own process and spills to disk when data outgrows memory. Sure, but one machine still has a ceiling, right? It does, but the ceiling moved. AWS now sells single instances with more than 30 terabytes of memory, built for giant in-memory databases. That's over 60 times our whole month of views. Oh, wow, that changes the math. There's a well-known essay making this case, too. Jordan Tigani, a founding engineer on Google's BigQuery analytics database, wrote in 2023 that "the era of Big Data is over," and says most BigQuery customers he saw stored under a terabyte in total.
13:50 To be fair, he now runs a DuckDB-based company, and he says he can't share the real numbers. But his point is that most workloads fit on one good machine, which leads to a rule you can actually use. So picture this: a data platform lead hears all of that and says, we already run everything on Spark, so why would I approve a second tool for one team? Fair point, and that's one of the good reasons to stick with Spark. So here's a rule for Monday: start on one machine, with pandas, Polars, or DuckDB, and reach for Spark when one of three things is true.
14:28 Let's hear it. First, the data or the work truly outgrows the biggest machine you can get. Second, your platform already runs on Spark, so a small job, say a daily report on yesterday's traffic, just rides along. 3rd, and this one's more my judgment call: when many teams share one giant pile of files in cloud storage, it's simpler if they all use the same engine on it. And when one of those is true, you know the real tradeoff now: you'll know where the time and memory go, mostly the shuffle and whatever you drag back to the driver.
15:03 Right, so the box is open. Spark is your job cut into pieces, run on many machines, and stitched back together. Thanks for listening to Learning Podcasts.