AlgoViz

Dataflow engines

medium 35 min

A dataflow engine runs a whole program as one graph of operators.

Video lesson · Chapter 1 of 5

The railway planner for a computation

0:00 / 4:11

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

  1. 2009

    Spark begins as a research project at the UC Berkeley AMPLab. It is open-sourced in early 2010.

  2. 2012

    The paper on resilient distributed datasets, which explains recovery by lineage, appears at NSDI.

  3. December 2014

    Flink, which grew out of the Stratosphere research project, becomes an Apache top-level project.

  4. 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.

Step 1 of 3

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.

From the cupboard to passing straight on
CUPBOARDFOLDWINGSPAINT

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

Job 1 filters and writes all rows to HDFS with three copies. Job 2 reads them, groups and writes all rows again with three copies. Job 3 reads those and ranks.
Two of the three writes exist only to be read once by the next job.

What the chain writes

2×100 GB×3 copies=600 GB2 \times 100\ \text{GB} \times 3\ \text{copies} = 600\ \text{GB}
Assume 100 GB between the jobs, twice, with three copies. A dataflow engine writes none of this to replicated storage: only shuffle data, once, on local disks.

MapReduce and dataflow engines

MapReduceDataflow engine
ShapeMap, shuffle, reduceAny DAG of operators
Between steps of a stageNot possible across jobsRows passed in memory
At a shuffleLocal disksLocal disks in Spark; Flink streams it or stores it
Between jobsReplicated filesUsually no separate job
Repeated passesA new job each timeOne program, data kept in memory
OptimisationBy handBy the engine, for SQL and DataFrames
Live questionsPoorPossible on a running cluster
More about the older model on MapReduce.

The model

From code to tasks

  1. 1

    Your code

    Transformations such as filter and groupBy, chained together.

  2. 2

    Logical plan

    What has to be computed, as a tree of operations.

  3. 3

    Optimised plan

    The same result with less work: earlier filters, fewer columns.

  4. 4

    Physical plan

    How: which kind of join, how many partitions.

  5. 5

    Execution

    Stages, and one task per partition in each stage.

A DAG with two inputs

Two sources, one result, no circles. A map and reduce pair could not hold this in one job.

Driver and executors

A driver sends one task to each of three executors. Each executor handles one partition and keeps data in its own cache.
The driver plans and hands out tasks. Data moves between executors, not through the driver, unless you collect it.

Dependencies

Narrow and wide

NarrowWide
Each parent partition feedsAt most one child partitionMany child partitions
Examplesmap, filter, uniongroupByKey, reduceByKey, repartition, most joins
NetworkNoneShuffle
RunPipelined in one taskCuts the stage
After a lossRemake one partitionMay need parts of many
A join is narrow if both sides are already partitioned the same way by the join key.

Two stages, one shuffle

Parquet input is read by three tasks of stage 1, which read, filter and make partial sums. Each sends data to both tasks of stage 2, one for key A and one for keys B and C, which write the totals.
Stage 1 has three tasks, one per input partition. The orange arrows are the shuffle.

Where does a stage end?

Fewer shuffles means fewer stages, and usually a faster job.

How many tasks?

64,000 MB128 MB=500 tasks⌈50040 cores⌉=13 rounds\frac{64{,}000\ \text{MB}}{128\ \text{MB}} = 500\ \text{tasks} \qquad \left\lceil \frac{500}{40\ \text{cores}} \right\rceil = 13\ \text{rounds}
64 GB read in 128 MB partitions with 40 cores. After a shuffle, Spark SQL makes 200 partitions unless you change it or adaptive execution merges small ones.

Lazy

Transformations and actions

Transformations (lazy)WhatActions (start the work)What
mapApply a function to each rowcollectAll rows to the driver
filterKeep matching rowscountNumber of rows
flatMapMap, then flattenfirstThe first row
groupByGroup by key (shuffle)take(n)The first n rows
joinJoin two datasets (usually a shuffle)reduceCombine all rows
selectChoose columnswriteSave to storage
withColumnAdd or change a columnshowPrint 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

Same answer, far fewer rows in the join. Spark's optimiser is called Catalyst. It cannot look inside your own functions, so prefer built-in ones.

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)
KeepsThe recipe for each partitionSnapshots of state and input positions
On failureDetect, trace back, run the steps again, for lost partitions onlyGo back to the last snapshot and continue
Costs when all is wellAlmost nothingWriting snapshots
Costs on failureMore after long chains and shufflesWork since the last snapshot
FitsBatchStreams with large state

A Flink checkpoint

Each operator saves what it had seen before the barrier, so the parts fit together. Savepoints are snapshots you take yourself, for example before an upgrade.

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

10×(60+10)=700 s60+10×10=160 s10 \times (60 + 10) = 700\ \text{s} \qquad 60 + 10 \times 10 = 160\ \text{s}
Assume 60 seconds to read and prepare, and 10 seconds for each pass. Reading again each time costs 700 seconds. Caching after the first read costs 160.
Level in SparkWhereIf it does not fit or a machine is lost
MEMORY_ONLYMemory, as objects. Default for RDD cacheMissing partitions are computed again
MEMORY_AND_DISKMemory, then diskOverflow is read from disk
DISK_ONLYDiskSlower, and computed again after a loss
MEMORY_ONLY_2Memory on two machinesThe second copy is used
Caching does not remove the lineage: a lost cached partition is still rebuilt from it. A checkpoint to reliable storage does cut it, which helps very long chains.

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 SparkApache Flink
Begins fromBatch over datasetsStreams, with a batch as a stream that ends
StreamsSmall batches by defaultEvent by event
APIsRDD, DataFrame and Dataset, SQLDataStream, Table and SQL
LanguagesPython, Scala, Java, R, SQLJava, Python, SQL
AlsoMachine learning and graph librariesEvent time, watermarks, savepoints
Choose forWarehouse loads, analysis, featuresLow delay, long-lived state
Apache Beam is a layer above: one program that several runners, including Flink and Spark, can execute.

Which engine?

If your team already runs one of these well, that is a good reason to use it.

Use

Where they are used

AreaExamples
ETL pipelinesLoading a data lake, changing schemas, quality checks, JSON to Parquet
Machine learningFeatures at scale, distributed training, batch predictions, A/B test analysis
AnalyticsAggregations, user behaviour, funnels, cohorts
Data scienceExploration, 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. 1

    Find the longest stage

    The engine's own web page shows time, input and shuffle size for each stage.

  2. 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. 3

    Shrink the shuffle

    Filter earlier, select fewer columns, broadcast the small table, sum before grouping.

  4. 4

    Fix skew

    Handle the few large keys apart, salt them, or let adaptive execution split them.

  5. 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.

Sources