Sina Vafadar

Batch Processing

Dec 2, 2026 · 30 min

Designing Data-Intensive Applications · Chapter 10 · Recall lab

Part III of the book is about systems that derive data: take what is in one or more systems of record and turn it into caches, indexes, recommendations and analytics. This chapter starts with the oldest way of doing that. Not a request and a response, not an event the moment it happens, but a large pile of input, a job that chews through it, and output at the end.

Where batch fits § Chapter 10 introduction

Services, batch jobs and streams

Services: online

Wait for a request, handle it as quickly as possible, send a response. Response time is the measure, and availability matters, because a human is usually waiting.

Batch processing: offline

Take a large, bounded input, run a job over it, produce output. Jobs take minutes to days and nobody waits on them; they are scheduled. Throughput is the measure.

Stream processing: near-real-time

Like batch, it consumes inputs and produces outputs rather than answering requests, but it operates on events shortly after they happen, on input that never ends. That is chapter 11.

Batch processing is old: punch-card tabulating machines, such as the Hollerith machines of the 1890 US census, computed aggregate statistics over large inputs. MapReduce, published by Google in 2004 and reimplemented as Hadoop, made it the way to process data at scale for a decade, and its ideas outlived it. To understand it, the chapter starts somewhere much smaller.

This chapter builds on Dean and Ghemawat’s MapReduce paper. The MapReduce lab runs that paper in depth: a job through all seven steps of its Figure 1, the combiner, backup tasks against stragglers. This chapter takes the model as given and asks what you do with it.

Where the ideas come from § Batch Processing with Unix Tools

Five tools and a pipe

Say you run a website and want the five most popular pages. The web server appends a line to an access log for every request. One line of shell answers the question: read the log, pull out the URL, sort, count, sort by count, take the top five. Here it is on 14 log lines, one stage at a time, with each stage’s output computed by doing what the tool does.

cat | awk | sort | uniq -c | sort -r -n | head

cat /var/log/nginx/access.log|awk '{print $7}'|sort|uniq -c|sort -r -n|head -n 5
216.58.223.198 - - [27/Feb/2015:17:55:11 +0000] "GET /js/main.js HTTP/1.1" 200 8917 "-" "Mozilla/5.0"
216.58.216.172 - - [27/Feb/2015:17:55:18 +0000] "GET /favicon.ico HTTP/1.1" 200 3580 "-" "Mozilla/5.0"
216.58.233.131 - - [27/Feb/2015:17:55:25 +0000] "GET /js/main.js HTTP/1.1" 200 8485 "-" "Mozilla/5.0"
216.58.226.2 - - [27/Feb/2015:17:55:32 +0000] "GET /img/logo.png HTTP/1.1" 200 8896 "-" "Mozilla/5.0"
216.58.215.234 - - [27/Feb/2015:17:55:39 +0000] "GET /css/typography.css HTTP/1.1" 200 7924 "-" "Mozilla/5.0"
216.58.221.178 - - [27/Feb/2015:17:55:46 +0000] "GET /index.html HTTP/1.1" 200 2388 "-" "Mozilla/5.0"
216.58.218.180 - - [27/Feb/2015:17:55:53 +0000] "GET /css/typography.css HTTP/1.1" 200 1012 "-" "Mozilla/5.0"
216.58.200.119 - - [27/Feb/2015:17:56:00 +0000] "GET /css/typography.css HTTP/1.1" 200 8767 "-" "Mozilla/5.0"
216.58.230.170 - - [27/Feb/2015:17:56:07 +0000] "GET /index.html HTTP/1.1" 200 8076 "-" "Mozilla/5.0"
216.58.229.145 - - [27/Feb/2015:17:56:14 +0000] "GET /js/main.js HTTP/1.1" 200 1638 "-" "Mozilla/5.0"
216.58.218.132 - - [27/Feb/2015:17:56:21 +0000] "GET /about.html HTTP/1.1" 200 8546 "-" "Mozilla/5.0"
216.58.220.115 - - [27/Feb/2015:17:56:28 +0000] "GET /index.html HTTP/1.1" 200 5470 "-" "Mozilla/5.0"
216.58.228.194 - - [27/Feb/2015:17:56:35 +0000] "GET /css/typography.css HTTP/1.1" 200 8698 "-" "Mozilla/5.0"
216.58.233.93 - - [27/Feb/2015:17:56:42 +0000] "GET /favicon.ico HTTP/1.1" 200 7200 "-" "Mozilla/5.0"
Stage 1: cat /var/log/nginx/access.log

Read the log file. Each line is one request in nginx’s default format: client IP, timestamp, request line, status, size, referrer and user agent. 14 lines here; a real site has millions.

The same job could be a short program that keeps a hash table from URL to count. Which is better depends on the working set: how much must be in memory at once. If the distinct URLs fit, a hash table is fine; with 1 GB of memory and about 100 bytes per entry, that is about 10 million URLs. Beyond that, sorting wins: GNU sort spills sorted runs to disk and merges them, and spreads the work over CPU cores. The pipeline scales to datasets far larger than memory without changing a character, limited by how fast the disk can read.

The Unix philosophy

Doug McIlroy, 1978: make each program do one thing well; expect the output of every program to become the input of another, as yet unknown; design software to be tried early; and use tools rather than unskilled help to lighten a programming task. Automation, rapid prototyping, incremental iteration, experiments: it reads like Agile and DevOps, decades earlier.

A uniform interface

Programs can be plugged together because they share one interface: a file, an ordered sequence of bytes. By convention it is ASCII text, one record per line, fields separated by whitespace, and tools as different as awk, sort and uniq all understand it. Programs with their own data models cannot be composed this easily.

Separating logic from wiring

A program reads standard input and writes standard output; it does not know or care where they lead. The shell connects them. That loose coupling lets each tool stay small, and lets you rearrange them without touching their code. It stops being easy when a program needs several inputs or outputs.

Transparency and experimentation

Inputs are treated as immutable: run a pipeline as often as you like, nothing is damaged. Pipe any stage into less to see what it produces. Write a stage’s output to a file and restart from there. Unix tools are great for this, and their one big limit is that they run on a single machine. That is where Hadoop comes in.

The same ideas, on thousands of machines § MapReduce and Distributed Filesystems

A Unix process spread across a cluster

A MapReduce job is like a Unix process: it takes one or more inputs and produces one or more outputs, and it does not modify its input. Its files live in a distributed filesystem, HDFS, Hadoop’s open source version of the Google File System. HDFS is shared-nothing: a daemon on each machine serves its own disks, a central NameNode tracks which blocks are where, and every block is replicated on several machines, or protected by erasure coding such as Reed–Solomon codes, to survive machine and disk failures. The largest deployments run on tens of thousands of machines, holding hundreds of petabytes.

A job runs in the same four steps as the Unix pipeline above, and only two of them are code you write. The input files are broken into records; your mapper extracts a key and value from each, as awk '{print $7}' did; the framework sorts all pairs by key, as sort did; your reducer iterates over each key’s values, as uniq -c did. Mappers run one task per input block, on a machine that holds a replica when possible, to put the computation near the data. The author chooses the number of reducers, and each key goes to reducer hash(key) mod R. Each map task sorts its output partitions and writes them to local disk; each reducer fetches its partition from every mapper and merges them: the shuffle.

Workflows

One job can only do so much, so jobs are chained: one job’s output directory is the next one’s input. A recommendation system can be 50 to 100 MapReduce jobs. A job starts only when the previous one has completed successfully, and schedulers such as Oozie, Azkaban, Luigi, Airflow and Pinball manage those dependencies.

Higher-level tools

Writing raw MapReduce is laborious, so layers appeared on top: Pig, Hive, Cascading, Crunch and Google’s FlumeJava set up workflows of jobs automatically from a description of the stages. They come back at the end of the chapter, running on engines other than MapReduce.

Bringing related records together § Reduce-Side Joins and Grouping

A join with no indexes

A database answers a join that touches a few records by looking them up in an index. MapReduce has no indexes: a job reads the entire content of its input files, like a full table scan. That is wasteful for one user and exactly right for analytics, which joins everything with everything. The book’s example is a log of what users did on a website, joined with the user database to find which pages are popular with which age group.

A reduce-side sort-merge join, figures 10-2 and 10-3

User database
1041989-01-121731978-09-302151995-04-02
Activity events
215/sign-up104/home173/cart104/search?q=boots215/home104/product/77173/checkout
Two inputs

A log of what logged-in users did, and the user database. The question needs both: which pages are popular with which age group. Looking up each event’s user over the network would be slow and would hammer the database, so the batch job joins a copy of the user table, extracted into the distributed filesystem, with the log.

The pattern generalizes. The mapper’s choice of key is like an address: every record with the same key is delivered to the same reducer, and MapReduce separates the network communication from the application logic completely. The same machinery runs a GROUP BY: key by the grouping column and the reducer sees each group whole, whether it is counting, summing, taking the top k, or collecting all of one user’s activity into a session to see what they did and in what order.

Skew: when one key is huge

Bringing a key’s records together breaks down when one key has far more than the rest: a celebrity with millions of followers. Such hot keys, or linchpin objects, land on one reducer, and the whole job waits for it. Pig’s skewed join samples to find hot keys and spreads their records over several reducers, replicating the other side to each. Crunch’s sharded join does the same with the hot keys named in advance. Hive’s skewed join keeps the hot keys in table metadata and joins them map-side.

Grouping hot keys in two stages

For a GROUP BY on a hot key, the first job sends records to reducers at random, so each reducer computes a partial result for a share of the hot key, a count, say. A second job then combines the partial results into one value per key. The work is spread, at the cost of an extra pass.

Reduce-side joins need nothing from their inputs, which is their strength; they pay by sorting, copying and merging everything. If you can assume something about the inputs, a join can happen in the mappers, with no reducers and no sort at all: the map-side joins. Which one applies depends on what you know about the data, so the next section tests them all.

The joins as an experiment § Reduce-Side Joins · § Map-Side Joins

Five situations, five join algorithms, twenty-five runs

Each row is a situation: the same two inputs, activity events and users, laid out differently or shaped differently. Each column is one of the chapter’s join algorithms. A small join engine runs each one with 8 mappers, 8 reducers and room for 2,500 user records in a mapper’s memory, counts every record that crosses the network, and checks the output against the true join. Click any cell for how the column works and the load on each task.

Every cell is a run: click one to see what happened

Reduce-side sort-merge join works on any input Broadcast hash join small table fits in memory Partitioned hash join Hive’s bucketed map join Map-side merge join inputs partitioned and sorted alike Skewed join Pig’s skewed join, Crunch’s sharded join
Small user table fits in memory
Both inputs large arbitrary layout
Partitioned alike same key, same hash, same count
Partitioned and sorted the output of an earlier job
One celebrity user a hot key

works correct, with what it moved hot reducer correct, but one task does far more out of memory the hash table does not fit not applicable the inputs are not laid out for it

How the column works Mappers emit every record from both inputs keyed by user ID; the shuffle sends each key to one reducer and sorts it, with the user record first; the reducer joins one user at a time. It makes no assumptions about the inputs, which is its strength, and it pays for that by shuffling and sorting everything. A key with far more records than the rest lands on one reducer.

One celebrity user under Reduce-side sort-merge joinLarge inputs again, but one user, a celebrity, accounts for 40% of all activity: a linchpin object, or hot key.

Records handled by each reducer:

reducer 03,529reducer 13,456reducer 23,587reducer 33,480reducer 43,504reducer 53,559reducer 611,411reducer 73,474

Works, slowly It works, but the busiest reducer gets 11,411 records, 2.5 times the average: the celebrity’s events all hash to one place. The whole job waits for that one task. All 20,000 joined rows are correct.

The grid is the chapter’s advice in one picture. With a small table, a broadcast hash join wins: nothing moves. When both inputs are large, only the joins that make no assumptions apply, unless earlier jobs wrote the inputs partitioned alike, which opens the partitioned hash join, or partitioned and sorted alike, which opens the merge join. With a celebrity in the data, the plain sort-merge join gives one reducer 2.5 times the average work, and the skewed join brings it down to 1.1. Notice what the map-side joins depend on: the physical layout of datasets written by earlier jobs. That is why the partitioning and sort order of outputs is recorded in metadata, as in HCatalog and the Hive metastore.

Two variants worth knowing. A broadcast hash join’s small input can live in a read-only index on the mapper’s local disk instead of in memory, as long as the frequently used parts stay in the operating system’s page cache. And the broadcast join goes by many names: Pig’s replicated join, Hive’s MapJoin, and the same idea in Cascading, Crunch and MPP engines such as Impala.

What a batch job is for § The Output of Batch Workflows

Not reports: indexes, models and databases

A batch job’s output is rarely a report. It is something an application uses. Google’s original use of MapReduce was to build the indexes for its search engine, a workflow of five to ten jobs, and Lucene and Solr indexes are still built this way: mappers partition the documents, reducers build each partition’s index, and the index files are written once and never changed. Another common output is a database for an online service: the features for a classifier, or the recommendations a website looks up for each user.

Two ways to get a job’s output into a serving database

Task 1Task 2Serving databaselive: users see a half-written jobinsert …insert …retry: insert from the starttask fails halfway
Each task writes straight into the live database

A network request per record is orders of magnitude slower than a batch task’s normal throughput, and many tasks writing at once can overwhelm the database and hurt the online system that shares it. Worse, a retried task repeats writes the failed attempt already made, and other jobs see partial results.

Two tasks of 1,000 rows each, one failing halfway: the database ends with 2,500 rows, 500 of them duplicates.

Why immutable output is the right default

Buggy code that ran on a database leaves corrupted data behind; buggy code that wrote new files can be rolled back to the previous output and rerun. That is human fault tolerance, and Agile teams call it minimizing irreversibility. A failed task is retried automatically, because its inputs are unchanged and its partial output is discarded. The same files can feed many different jobs, including monitoring jobs that compare a run’s output with the last one.

Logic and wiring again

As in Unix, a MapReduce job’s code does not know where its inputs come from or its outputs go. The input directory, the output directory and the scheduling are configured separately. One team can write a job that does one thing well while another decides where and when it runs: the same reuse that made sort and uniq useful.

Two lineages of parallel processing § Comparing Hadoop to Distributed Databases

An operating system, not a database

Massively parallel processing (MPP) databases, from Teradata onward, had run analytic SQL across clusters for over a decade before MapReduce. The biggest difference is that an MPP database is a database, tightly integrated around SQL, while MapReduce and a distributed filesystem are more like a general-purpose operating system that can run arbitrary programs.

Diversity of storage

A database requires you to model data before importing it. Hadoop lets you dump data into HDFS as it is, and work out how to interpret it later: a data lake, or enterprise data hub. The burden of interpretation moves to the consumer, a schema-on-read approach, and collecting data becomes fast. The sushi principle: raw data is better.

Diversity of processing models

SQL is a great fit for many queries, not for all: machine learning, recommendation, full-text indexes and image analysis need code. Hadoop runs SQL engines such as Hive and Impala and arbitrary programs, and HBase for random-access OLTP, side by side on the same cluster, over the same files. Each system can bring its own processing model.

The two also make opposite assumptions about failure. When a node crashes mid-query, an MPP database aborts the whole query and runs it again, which is fine for queries of seconds or minutes on dedicated hardware. MapReduce retries the failed task, and writes data to disk eagerly so that it can. That design comes from Google’s mixed-use datacenters, where batch tasks run at low priority and are preempted when online services need the machines: a task that runs for an hour has about a 5% chance of being killed. Choose a job’s size and see what each approach costs:

Restart the query, or retry the task

MPP: restart queryover 20×MapReduce: retry task1.05×
200 tasks of 1 hour each

Each task is killed with probability 5%. An MPP database, which reruns the whole query when anything fails, finishes on average after about 28,529 attempts, since each attempt survives only about one time in 28,529. MapReduce reruns only the killed tasks, so the job costs about 1.05× the work, 5% extra.

Where machines are rarely preempted, task failures are rare too, and the cost of MapReduce’s caution is less obviously worth paying. Which leads to the engines that came after it.

The next generation § Beyond MapReduce

Stop writing everything down

MapReduce is one programming model among many, and a fairly low-level one. Its biggest cost is materialization: every job writes its whole output to the distributed filesystem before the next can start. Unix pipes stream; MapReduce writes everything down. Here is the same three-stage workflow both ways.

One workflow, two engines

stage 1stage 2stage 3
Three MapReduce jobs, each materializing its output

Every job waits for all tasks of the job before it, so the slowest task of each stage holds up the next. Each job writes its whole output to the distributed filesystem, 3 replicas of every block, and the next job begins with mappers that only read it back. Finished at 52, with 3,456 MB written to replicated storage.

Spark, Tez and Flink are dataflow engines: they model a whole workflow as one job, a graph of operators, and choose how to connect them. An operator’s output can be repartitioned and sorted, like MapReduce’s shuffle; partitioned without sorting, enough for a partitioned hash join; or broadcast to every partition of the next operator, for a broadcast hash join. Sorting happens only where it is actually needed, there are no redundant map tasks, operators start as soon as their input is ready, and existing processes are reused rather than started for each task. In the exhibit the dataflow version finishes 34% sooner. Pig, Hive and Cascading can switch from MapReduce to Tez or Spark with a configuration change.

Fault tolerance without materialization

With nothing written down, a lost partition must be recomputed from whatever earlier data is still available. Spark tracks each dataset’s ancestry with the resilient distributed dataset (RDD) abstraction; Flink checkpoints operator state. Recomputation is only safe if operators are deterministic, which the next exhibit tests. When intermediate data is much smaller than its source, or expensive to compute, materializing it is cheaper than recomputing it.

Some writing remains

A sorting operator must consume its entire input before it can output anything, so any stage that sorts still accumulates state, if only in memory or on local disk. And the final output of the job is still written to the distributed filesystem, as with MapReduce.

Recomputing a lost partition

records sampled
first run, already consumed downstream102
recomputed after a failure102
in both102
Sampling with a fixed seed

An operator keeps a random 10% of its input. Part of its output has already gone downstream when a machine fails, and the engine recomputes the lost partition from the input, as Spark does from an RDD’s lineage. The same seed gives the same sample, so the recomputed output is identical: recovery is invisible. Iteration order of hash tables, random numbers and the system clock are the usual sources of nondeterminism.

When the data is a graph § Graphs and Iterative Processing

Think like a vertex

Some algorithms, such as PageRank, which estimates how important a web page is from the pages that link to it, repeat a step until it stops changing. Running each iteration as a MapReduce job rereads and rewrites the entire graph every time, even when only a small part has changed. The bulk synchronous parallel model, popularized by Google’s Pregel and implemented in Apache Giraph, Spark’s GraphX and Flink’s Gelly, does it differently: each vertex keeps its state in memory and sends messages to other vertices along the edges, in rounds called supersteps.

PageRank on five pages, 12 supersteps

A0.200B0.200C0.200D0.200E0.200
Superstep 0: everyone starts equal

Each of the 5 pages starts with rank 1/5. In every superstep, each vertex sends its rank divided by its number of outgoing links along each link, 8 messages in all, and the framework delivers them all before the next superstep begins.

How Pregel survives failures

Messages are delivered exactly once in each superstep, after all of the previous superstep’s messages; the framework batches them and retries lost ones. For machine failures, it checkpoints the state of every vertex at the end of an iteration, and on a failure rolls the whole computation back to the last checkpoint and restarts from there.

When a distributed graph is slower

A vertex does not know which machine it runs on, so the graph is usually partitioned by vertex ID, with no attempt to keep connected vertices together. Most messages then cross the network, and that overhead can dominate. If the graph fits in one machine’s memory, a single-machine algorithm can beat a distributed one; GraphChi even works from local disk.

Where batch processing went § High-Level APIs and Languages

Declarative again

Engineers wrote raw MapReduce for a few years, then moved to higher-level languages: Hive, Pig, Cascading and Crunch, now running on Tez, Spark and Flink. Less code, and the same code runs on whichever engine is best. And because relational operators say what to compute rather than how, an engine can choose for itself.

Letting the optimizer choose the join

Spell out a join in code and you pick the algorithm. Declare it, and a cost-based optimizer in Hive, Spark or Flink can choose from the grid above by looking at the inputs: their sizes, how they are partitioned and sorted. Engines also adopted the MPP tricks of columnar storage, vectorized execution and generating code at runtime. Batch systems still let you call arbitrary code where you need it.

Specialized domains

Some algorithms are needed again and again, so they get reusable implementations: machine learning in Mahout and Spark’s MLlib, and MADlib inside MPP databases; k-nearest-neighbor search; approximate search; spatial algorithms; genome analysis, with approximate string matching. Batch processing engines and MPP databases are becoming more alike.

Recall check 12 questions

Did it stick?

One attempt per question; the explanation appears either way.

1. How does the book distinguish batch processing from services and stream processing?

2. In the log pipeline, why must the input be sorted before `uniq -c`?

3. When does sorting beat an in-memory hash table for counting URLs?

4. Which idea from Unix does MapReduce share most directly?

5. In a reduce-side sort-merge join, why does the secondary sort put the user record first?

6. When is a broadcast hash join possible?

7. What does a map-side merge join require of its inputs?

8. In the grid, how much more work does the busiest reducer get in a plain sort-merge join with one celebrity user?

9. Why should a batch job not write directly into the production database from its tasks?

10. Why does MapReduce retry individual tasks while MPP databases abort the whole query?

11. What do dataflow engines like Spark, Tez and Flink avoid compared with chains of MapReduce jobs?

12. In the Pregel model, what happens in one superstep?

Answered 0 of 12 · 0 correct

Vocabulary Click to flip

The terms this chapter installs


Chapter 10 in one breath. Batch processing takes a bounded input and produces output, and its best ideas came from Unix: small programs that do one thing, a uniform interface, logic separated from wiring, inputs that are never modified. MapReduce spread that over thousands of machines: the mapper extracts keys, the framework partitions and sorts, the reducer sees each key’s values together, and a distributed filesystem plays the part of the file. Joins happen by bringing related records to the same place, in the reducer when you know nothing about the inputs, in the mappers when you know their size or layout, with sampling to cope with hot keys. Output is best written as new immutable files, so a failed or buggy job can simply be discarded and rerun. MapReduce retries tasks rather than queries because it was built for clusters where tasks get preempted. Dataflow engines keep the model and drop the materialization; Pregel handles iterative graph algorithms in supersteps; declarative languages let the engine pick the algorithm. All of it works on bounded input. The next chapter removes that assumption.

← all lab notes