Dataflow engines
medium 35 minA dataflow engine runs a whole program as one graph of operators.
Video lesson · Chapter 1 of 5
The railway planner for a computation
Theory
Read or listen first. About 2 min.
What it is
A dataflow engine is a system that processes large data as a flow through operators such as filter, join and sum. The operators form a directed acyclic graph, or DAG: data moves forward along arrows and never in a circle.
You write a program in terms of whole datasets. The engine turns it into a plan, cuts the plan into stages and runs many small tasks on many machines. Apache Spark and Apache Flink are two such engines.
Why it exists
A MapReduce job has one map and one reduce. A real program needs many steps, so it becomes a chain of jobs, and each job writes all its results to replicated files before the next may start. Most of the time goes into writing and reading what is needed only once.
An engine that knows the whole program can do better. It joins steps into one, passes rows along without storing them, reads only the columns it needs and keeps data in memory when it is used again. If a machine fails, it uses the plan to make the missing part again.
A short history
2009
Spark begins as a research project at the UC Berkeley AMPLab. It is open-sourced in early 2010.
2012
The paper on resilient distributed datasets, which explains recovery by lineage, appears at NSDI.
December 2014
Flink, which grew out of the Stratosphere research project, becomes an Apache top-level project.
2015
Google engineers publish the Dataflow Model at VLDB: one way to describe batch and streaming programs.
Words to know
- Operator
- One step of the program, such as filter or sum.
- DAG
- A graph of steps with a direction and no circles.
- Partition
- One piece of a dataset, handled by one task.
- Transformation
- Describes a new dataset. Nothing runs yet.
- Action
- Asks for a result, which starts the work.
- Narrow dependency
- Each input partition feeds at most one output partition.
- Wide dependency
- Each output partition needs many input partitions: a shuffle.
- Stage
- Steps that run together without a shuffle between them.
- Lineage
- The recipe for a partition: which steps made it from which input.
- Checkpoint
- A saved copy to continue from.
- Driver
- The process that plans and hands out tasks.
How it works
Step through the idea, or press Play.
Describe. Transformations build a graph of steps, and nothing runs
Understand it
Start here
The paper-plane workshop
Three people make paper planes: one folds, one adds wings, one paints. How they pass pieces along decides how fast it goes.
The cupboard did not vanish for every step: sorting into baskets is still a moment when all planes have to move.
Why
What was slow before
A chain of jobs
What the chain writes
MapReduce and dataflow engines
| MapReduce | Dataflow engine | |
|---|---|---|
| Shape | Map, shuffle, reduce | Any DAG of operators |
| Between steps of a stage | Not possible across jobs | Rows passed in memory |
| At a shuffle | Local disks | Local disks in Spark; Flink streams it or stores it |
| Between jobs | Replicated files | Usually no separate job |
| Repeated passes | A new job each time | One program, data kept in memory |
| Optimisation | By hand | By the engine, for SQL and DataFrames |
| Live questions | Poor | Possible on a running cluster |
The model
From code to tasks
- 1
Your code
Transformations such as filter and groupBy, chained together.
- 2
Logical plan
What has to be computed, as a tree of operations.
- 3
Optimised plan
The same result with less work: earlier filters, fewer columns.
- 4
Physical plan
How: which kind of join, how many partitions.
- 5
Execution
Stages, and one task per partition in each stage.
A DAG with two inputs
Driver and executors
Dependencies
Narrow and wide
| Narrow | Wide | |
|---|---|---|
| Each parent partition feeds | At most one child partition | Many child partitions |
| Examples | map, filter, union | groupByKey, reduceByKey, repartition, most joins |
| Network | None | Shuffle |
| Run | Pipelined in one task | Cuts the stage |
| After a loss | Remake one partition | May need parts of many |
Two stages, one shuffle
Where does a stage end?
How many tasks?
Lazy
Transformations and actions
| Transformations (lazy) | What | Actions (start the work) | What |
|---|---|---|---|
| map | Apply a function to each row | collect | All rows to the driver |
| filter | Keep matching rows | count | Number of rows |
| flatMap | Map, then flatten | first | The first row |
| groupBy | Group by key (shuffle) | take(n) | The first n rows |
| join | Join two datasets (usually a shuffle) | reduce | Combine all rows |
| select | Choose columns | write | Save to storage |
| withColumn | Add or change a column | show | Print some rows |
Waiting has a purpose: when the action comes, the engine sees the whole chain and can change it. It has a trap too. Each action runs the chain again from the start, unless you cache a dataset that several actions use. An error in a filter may also appear only at the action, far from the line that caused it.
Optimise
What the optimiser does
Predicate pushdown
A filter moves into the file reader, so rows are skipped before they are loaded.
Column pruning
Only the columns that are used are read. Column files such as Parquet make this cheap.
Partition pruning
If folders are by date, a date filter skips whole folders.
Broadcast join
A small table is sent to every machine, so the large one need not be shuffled. Spark does it by itself under 10 MB by default.
Partial sums
Sums are made before the shuffle, like a combiner.
Adaptive execution
After a stage, real sizes are known and the rest of the plan can change. On by default in Spark since version 3.2.
Before and after
Say what you want
- SQL and DataFrames: the optimiser can help
- Built-in functions
- Filter as early as you can
- Look at the plan with explain
Hide it from the engine
- Custom functions for simple sums
- Reading every column
- groupByKey and then a sum: it ships every row
- Collecting a large dataset to the driver
Failures
Two ways to recover
| Lineage (Spark batch) | Checkpoints (Flink) | |
|---|---|---|
| Keeps | The recipe for each partition | Snapshots of state and input positions |
| On failure | Detect, trace back, run the steps again, for lost partitions only | Go back to the last snapshot and continue |
| Costs when all is well | Almost nothing | Writing snapshots |
| Costs on failure | More after long chains and shuffles | Work since the last snapshot |
| Fits | Batch | Streams with large state |
A Flink checkpoint
Exactly once here means that state is counted once. If a sink is outside, the effect appears once only if the source can be read again and the sink is transactional or idempotent. Time, windows and watermarks belong to stream processing.
Memory
Caching and persistence
Ten passes over the same data
| Level in Spark | Where | If it does not fit or a machine is lost |
|---|---|---|
| MEMORY_ONLY | Memory, as objects. Default for RDD cache | Missing partitions are computed again |
| MEMORY_AND_DISK | Memory, then disk | Overflow is read from disk |
| DISK_ONLY | Disk | Slower, and computed again after a loss |
| MEMORY_ONLY_2 | Memory on two machines | The second copy is used |
Cache only what is used more than once, and release it afterwards. Caching everything fills memory, pushes out useful data and makes jobs slower.
Engines
Spark and Flink
| Apache Spark | Apache Flink | |
|---|---|---|
| Begins from | Batch over datasets | Streams, with a batch as a stream that ends |
| Streams | Small batches by default | Event by event |
| APIs | RDD, DataFrame and Dataset, SQL | DataStream, Table and SQL |
| Languages | Python, Scala, Java, R, SQL | Java, Python, SQL |
| Also | Machine learning and graph libraries | Event time, watermarks, savepoints |
| Choose for | Warehouse loads, analysis, features | Low delay, long-lived state |
Which engine?
Use
Where they are used
| Area | Examples |
|---|---|
| ETL pipelines | Loading a data lake, changing schemas, quality checks, JSON to Parquet |
| Machine learning | Features at scale, distributed training, batch predictions, A/B test analysis |
| Analytics | Aggregations, user behaviour, funnels, cohorts |
| Data science | Exploration, statistics, graphs, time series |
Comparing a nightly batch with a continuous job: batch and stream. Splitting one live request over services: fan-out and fan-in.
Tune
When a job is slow
- 1
Find the longest stage
The engine's own web page shows time, input and shuffle size for each stage.
- 2
Compare its tasks
If one task is far longer, the data is skewed. If all are long, there is too much data or too few cores.
- 3
Shrink the shuffle
Filter earlier, select fewer columns, broadcast the small table, sum before grouping.
- 4
Fix skew
Handle the few large keys apart, salt them, or let adaptive execution split them.
- 5
Size the partitions
Very many tiny tasks waste time on starting. A few huge ones spill to disk or run out of memory.
Summary
The whole topic in one minute.
A dataflow engine waits until it has the whole program, improves the plan, cuts it into stages at each shuffle and runs a task per partition. Within a stage, rows pass straight from step to step.
Spark recovers by lineage: it makes lost partitions again. Flink restores a checkpoint and continues. Memory helps when data is used more than once, but shuffles still go over the network and, in Spark, through files on disk. Most tuning is about shuffles and skew.
- The engine sees the whole DAG before it runs.
- Transformations are lazy; actions start work.
- Stages end at shuffles; tasks are one per partition.
- Lineage remakes lost partitions; checkpoints restore state.
- Cache only what is used again. It does not cut lineage.
- Shuffles and skew decide the running time.