Batch Processing
Offline systems that take a large, bounded input, run a job over it and produce derived output: from Unix pipelines to MapReduce on a distributed filesystem to modern dataflow engines.
Key takeaways
- Batch jobs are measured by throughput, not response time. Input is bounded, so a job knows when it is finished.
- The Unix ideas carry over: immutable inputs, output that becomes another program's input, small tools composed through a uniform interface, logic separated from wiring.
- MapReduce = mapper extracts key/value, framework partitions, sorts and shuffles by key, reducer processes all values for one key. HDFS plays the role of the filesystem.
- Joins in batch: sort-merge (reduce-side, no assumptions about inputs), broadcast hash (small side in memory), partitioned hash and map-side merge (inputs already partitioned/sorted alike).
- Write batch output as fresh immutable files (search indexes, key-value store files), never record-by-record into a live database. This gives easy rollback and human fault tolerance.
- Hadoop vs MPP databases: Hadoop offers diversity of storage (raw data, schema-on-read), diversity of processing (arbitrary code), and task-level retry built for frequent preemption.
- Dataflow engines (Spark, Tez, Flink) run a whole workflow as one job, skip needless sorts and avoid materializing intermediate state to HDFS; they recompute lost data, so operators should be deterministic.
- Graph algorithms use the Pregel / BSP model; high-level declarative APIs let optimizers pick join algorithms and use columnar, vectorized execution, so batch engines and MPP databases are converging.
Introduction
Parts I and II assumed request/response. The book distinguishes three kinds of system:
- Services (online systems): wait for a request, answer quickly. Measured by response time; availability matters.
- Batch processing systems (offline systems): take a large input, run a job, produce output. Jobs take minutes to days, usually run on a schedule (e.g. daily). Measured by throughput.
- Stream processing systems (near-real-time / nearline): consume inputs and produce outputs like batch, but act on events shortly after they happen, so latency is lower. Built on batch ideas; covered in Chapter 11.
- MapReduce (published 2004) was called "the algorithm that makes Google so massively scalable" and was reimplemented in Hadoop, CouchDB and MongoDB.
- Lower-level than older warehouse parallel systems, but a big step in scale on commodity hardware. Its importance is declining; it still shows why and how batch processing is useful.
Batch Processing with Unix Tools
Running example: a web server appends one line per request to an access log (nginx default format). Each line holds client IP, time, request line, status, bytes sent, referrer and user agent.
$remote_addr - $remote_user [$time_local] "$request"
$status $body_bytes_sent "$http_referer" "$http_user_agent"
Simple Log Analysis
Goal: the five most popular pages. A Unix pipeline does it:
cat /var/log/nginx/access.log |
awk '{print $7}' |
sort |
uniq -c |
sort -r -n |
head -n 5
awk '{print $7}'takes the 7th whitespace field, the requested URL.sortmakes repeated URLs adjacent;uniq -ccollapses adjacent duplicates and prefixes a count.sort -r -norders by count, largest first;head -n 5keeps the top five.- Processes gigabytes in seconds and is easy to tweak (e.g.
$1ranks client IPs instead).
Chain of commands versus custom program
- The same job can be a short Ruby program: a hash table
counts(default 0), split each line and take field index 6, increment, then sort by count and print the top five. - Less concise than the pipeline but readable; preference is partly taste. The real difference is the execution flow, visible on large inputs.
Sorting versus in-memory aggregation
- The working set (memory needing random access) depends only on the number of distinct URLs. For most small to mid-sized sites it fits in about 1 GB, so a hash table works even on a laptop.
- If the working set exceeds memory, sorting wins: sort chunks in memory, write sorted segment files, merge them (as in SSTables and LSM-trees). Mergesort's sequential access suits disks.
- GNU
sortspills to disk automatically and parallelizes across CPU cores, so the pipeline scales without running out of memory. The bottleneck becomes reading the input from disk.
The Unix Philosophy
- The 1978 statement of the Unix philosophy, paraphrased: (1) make each program do one thing well, and build new tools rather than bloating old ones; (2) expect output to feed some unknown next program, so keep it clean, avoid rigid columnar or binary formats and interactive input; (3) build and try software early, within weeks, and rebuild clumsy parts; (4) build tools to lighten work, even throwaway ones.
sortdoes one thing well (arguably better than most standard libraries, which neither spill to disk nor use multiple threads), yet is barely useful alone; it gains power combined with tools likeuniq.
A uniform interface
- To plug any output into any input, every program must share one I/O interface. In Unix it is the file (file descriptor): an ordered sequence of bytes.
- The same interface represents real files, pipes and Unix sockets, stdin/stdout, device drivers (
/dev/audio,/dev/lp0) and TCP sockets. - By convention many tools treat bytes as ASCII text with records separated by
\n. The choice is arbitrary (ASCII record separator0x1Ewould arguably be better); what matters is everyone agreed. - Field parsing is vaguer (whitespace, tabs, CSV);
{print $7}is less readable than a named field would be. - Few systems compose this well; even same-model databases rarely exchange data easily (Balkanization of data).
Separation of logic and wiring
- Programs read
stdinand writestdout; the shell user decides where those connect. Pipes link one process's stdout to the next's stdin through a small in-memory buffer, without writing the stream to disk. - The program does not know or care where data comes from or goes: loose coupling, late binding, inversion of control. Your own tool (e.g. user-agent to browser name, IP to country code) can join a pipeline just by using stdin/stdout.
- Limits: multiple inputs/outputs are tricky, and you cannot pipe output into a network connection.
Transparency and experimentation
- Inputs are treated as immutable, so you can rerun commands with different options without damage.
- You can stop the pipeline anywhere and pipe into
lessto inspect it, which helps debugging. - You can write one stage's output to a file and restart later stages from it without rerunning everything.
- Biggest limitation: Unix tools run on a single machine. That is where Hadoop comes in.
MapReduce and Distributed Filesystems
- MapReduce is like Unix tools spread over potentially thousands of machines: blunt, brute-force, surprisingly effective. One job is comparable to one Unix process: one or more inputs, one or more outputs.
- A job normally does not modify its input and has no side effects beyond its output. Output files are written once, sequentially, never modified in place.
- Instead of stdin/stdout, jobs read and write files on a distributed filesystem. In Hadoop it is HDFS (Hadoop Distributed File System), an open source reimplementation of Google File System (GFS).
- Others: GlusterFS, QFS; object stores (S3, Azure Blob Storage, OpenStack Swift) are similar, but usually separate storage from compute, while HDFS can run tasks where the data lives.
- HDFS is shared-nothing (ordinary machines on a datacenter network), unlike shared-disk NAS/SAN appliances with custom hardware.
- A daemon on each machine exposes its local disks over the network. A central NameNode tracks which file blocks live on which machine, creating one big filesystem across all disks.
- Blocks are replicated across machines, either full copies or erasure coding (e.g. Reed–Solomon), which recovers lost data with less storage overhead. Like RAID, but over a normal network without special hardware.
- Largest deployments: tens of thousands of machines, hundreds of petabytes, because commodity hardware is far cheaper than storage appliances.
MapReduce Job Execution
MapReduce follows the same four steps as the log example:
- Read input files and split them into records (one log line,
\nseparator). Done by the input format parser. - Call the mapper to extract a key and value from each record (
awk '{print $7}': URL as key, empty value). - Sort all key-value pairs by key (the first
sort). Implicit: mapper output is always sorted before reaching the reducer. - Call the reducer over the sorted pairs; equal keys are adjacent, so values combine with little state (
uniq -c).
- Mapper: called once per input record; emits zero or more key-value pairs; keeps no state between records, so each record is independent.
- Reducer: the framework collects all values for one key and calls the reducer with an iterator over them; it emits output records.
- A second sort (the ranking step) needs a second MapReduce job reading the first job's output. The mapper prepares data for sorting; the reducer processes sorted data.
Distributed execution of MapReduce
- MapReduce parallelizes across machines without parallel code from you; mappers and reducers see one record at a time.
- Mappers/reducers are usually code: Java classes in Hadoop, JavaScript in MongoDB and CouchDB.
- Parallelism comes from partitioning: the input is an HDFS directory and each file or block is a partition handled by its own map task. Input files are typically hundreds of megabytes.
- The scheduler tries to run each mapper on a machine holding a replica of its input (if it has spare RAM and CPU): putting the computation near the data, saving network transfer.
- Number of map tasks = number of input blocks; number of reduce tasks is set by the job author. A hash of the key picks the reducer, so equal keys meet in one place.
- Sorting is staged: each map task partitions its output by reducer and writes each partition as a sorted file on its local disk (SSTable-like).
- When a mapper finishes, reducers download their partition's sorted files from it. Partitioning by reducer, sorting and copying is the shuffle (no randomness involved, despite the name).
- The reducer merges these files in sort order, is called with a key and an iterator over its records, and writes output to the distributed filesystem.
MapReduce workflows
- One job is limited: it can count views per URL but not rank the most popular, which needs a second sort. So jobs are chained into workflows.
- Hadoop has no special workflow support: chaining is by directory name (job 1 writes a directory, job 2 reads it). To the framework they are two independent jobs.
- More like writing each command's output to a temp file than like a Unix pipe.
- A job's output counts only when the job succeeds (partial output of failed jobs is discarded), so a job starts only after the jobs producing its inputs finish.
- Workflow schedulers handle these dependencies: Oozie, Azkaban, Luigi, Airflow, Pinball. Workflows of 50 to 100 jobs are common for recommendation systems, and many teams read each other's output.
- Higher-level tools (Pig, Hive, Cascading, Crunch, FlumeJava) set up multi-stage workflows and wire them automatically.
Reduce-Side Joins and Grouping
- Joins are needed for foreign keys, document references and graph edges; denormalization reduces but rarely removes them (book covers equi-joins).
- Databases use indexes for queries touching few records. MapReduce has no indexes in the usual sense: it reads all input files, a full table scan.
- That is outrageously expensive for a few records but reasonable for analytic aggregates over many records, especially in parallel.
- In batch, a join means resolving every occurrence of an association in the dataset (all users at once), not looking up one user.
Example: analysis of user activity events
- Left: a log of activity events (clickstream) of logged-in users. Right: a database of user profiles. In star-schema terms, events are the fact table and users a dimension.
- Task: correlate activity with profile data, e.g. which pages are popular with which age groups. Events hold only the user ID; embedding full profiles in every event would be wasteful.
- Naive: query the remote user DB per event. Throughput is capped by round-trip time and parallel queries could overwhelm the DB.
- Good batch throughput needs computation local to one machine. Remote queries also make the job nondeterministic, since the remote data may change.
- Better: copy the user database (e.g. from a backup via ETL) into the same distributed filesystem as the events, then let MapReduce bring related records together.
Sort-merge joins
- One set of mappers reads events (key = user ID, value = event); another reads the user database (key = user ID, value = date of birth).
- Partitioning and sorting by key puts a user's record and all their events adjacent in one reducer's input.
- Secondary sort: arrange for the user record to come first, then events in timestamp order.
- The reducer runs once per user ID: store the date of birth in a local variable, then iterate the events emitting (viewed-url, viewer-age). Later jobs can compute age distributions per URL.
- Only one user record is in memory at a time and no network requests are made. Called a sort-merge join: mapper output is sorted by key, reducers merge both sorted sides.
Bringing related data together in the same place
- Mappers and sorting gather everything needed for one user ID into a single reducer call, so the reducer can be simple, single-threaded, high-throughput and low-memory.
- Think of mappers as "sending messages" to reducers: the key acts as a destination address. All pairs with the same key reach the same destination.
- MapReduce separates network communication (getting data to the right machine) from application logic. Contrast databases, where fetches often happen deep inside application code.
GROUP BY
- The same pattern implements grouping, usually followed by aggregation: count records (
COUNT(*)), sum a field (SUM(fieldname)), or pick the top k by a ranking function. - Mappers emit the grouping key; partitioning and sorting gather each group in one reducer. Grouping and joining look very similar on MapReduce.
- Sessionization: collate all events of one user session to see the sequence of actions, e.g. for A/B testing (did users on the new site version buy more?) or judging marketing.
- A user's events are scattered over many servers' logs; group by session cookie or user ID.
Handling skew
- The pattern breaks down when one key has huge amounts of data. In a social network most users have a few hundred connections but a few celebrities have millions of followers. Such records are linchpin objects or hot keys.
- One reducer gets far more work (skew / hot spot). A job finishes only when all tasks do, so later jobs wait for the slowest reducer.
- Pig skewed join: a sampling job first finds hot keys. During the join, mappers send hot-key records to one of several reducers chosen at random; the other input's records for that key are replicated to all those reducers. Spreads work at the cost of replication.
- Crunch sharded join: similar, but hot keys are specified explicitly.
- Hive skewed join: hot keys declared in table metadata, stored in separate files, and joined with a map-side join.
- For grouping with a hot key, aggregate in two stages: stage 1 sends records to random reducers that each output a compact partial aggregate; stage 2 combines them into one value per key.
Map-Side Joins
- The joins above do the join logic in reducers: reduce-side joins. Mappers just prepare input (extract key/value, assign partition, sort).
- Upside: no assumptions about the input. Downside: sorting, copying to reducers and merging are expensive, and data may hit disk several times depending on memory buffers.
- If you can make assumptions about the input, a map-side join is faster: a cut-down job with no reducers and no sorting; each mapper reads one input block and writes one output file.
Broadcast hash joins
- For a large dataset joined with one small enough to fit entirely in memory in each mapper.
- If the user database in Figure 10-2 were small, each mapper loads it into an in-memory hash table at startup, then scans activity events and looks up each user ID.
- There is one map task per block of the large input, and each loads the whole small input. "Broadcast": the small input goes to every partition of the large one; "hash": it uses a hash table.
- Supported by Pig ("replicated join"), Hive ("MapJoin"), Cascading and Crunch; also used in warehouse query engines such as Impala.
- Alternative: a read-only index on local disk; hot parts stay in the page cache, nearly as fast without fitting in memory.
Partitioned hash joins
- If both inputs are partitioned the same way, apply the hash join to each partition independently. Example: partition events and users by the last decimal digit of user ID (10 partitions each); mapper 3 loads users ending in 3 and scans events for those users.
- Each mapper reads one partition from each input, so each hash table is smaller.
- Works only if both inputs have the same number of partitions, the same key and the same hash function, which is reasonable when earlier MapReduce jobs produced them. Hive calls these bucketed map joins.
Map-side merge joins
- If inputs are partitioned the same way and sorted by the same key, size no longer matters: a mapper reads both files incrementally in ascending key order and matches equal keys, as a reducer would.
- Usually earlier jobs produced that layout; a separate map-only join still makes sense if the sorted data serves other purposes too.
MapReduce workflows with map-side joins
- The join type shapes the output: reduce-side output is partitioned and sorted by the join key; map-side output is partitioned and sorted like the large input (one map task per block of it, for broadcast or partitioned joins).
- Map-side joins assume more about size, sorting and partitioning, so you must know the dataset's physical layout: not just encoding and directory, but number of partitions and the keys used for partitioning and sorting.
- In Hadoop this metadata is often kept in HCatalog and the Hive metastore.
| Join | Where | Requires | Output layout |
|---|---|---|---|
| Sort-merge | Reducers | Nothing about inputs | By join key |
| Broadcast hash | Mappers | Small side fits in memory (or local read-only index) | Like large input |
| Partitioned hash | Mappers | Same partition count, key, hash function | Like large input |
| Map-side merge | Mappers | Same partitioning and sorted by same key | Like large input |
The Output of Batch Workflows
- Batch is neither OLTP (index lookups) nor analytics (reports). It scans large inputs like analytics, but its output is often a structure, not a report.
Building search indexes
- Google's original use of MapReduce: building search-engine indexes with a workflow of 5 to 10 jobs. Google later moved away from it, but Hadoop MapReduce remains a good way to build Lucene/Solr indexes.
- A full-text index (simplified): a term dictionary mapping each keyword to its postings list of document IDs. Real ones also need data for relevance ranking, misspellings and synonyms.
- For a fixed document set: mappers partition documents, each reducer builds its partition's index, index files go to the distributed filesystem. Document-partitioned indexes parallelize very well.
- Querying is read-only, so index files are immutable once built.
- On change: rerun everything and swap files (costly but simple: documents in, indexes out), or build incrementally with Lucene segment files and merging.
Key-value stores as batch process output
- Batch jobs build classifiers (spam filters, anomaly detection) and recommenders (people you may know, related products). Output is often a database the web app queries by user or product ID.
- Writing to the production database record by record from mappers/reducers works but is a bad idea:
- A network request per record is orders of magnitude slower than batch throughput, even with client batching.
- Many parallel tasks writing at batch rates can overwhelm the database and hurt its query performance, causing operational problems elsewhere.
- It breaks MapReduce's clean all-or-nothing output guarantee: externally visible side effects expose partial results and must cope with task retries and speculative execution.
- Better: build a brand-new database inside the job, write it as files to the output directory, then bulk-load them into read-only serving servers. Supported by Voldemort, Terrapin, ElephantDB and HBase bulk loading.
- Extracting a key and sorting by it is most of the work of building an index anyway. Read-only, write-once files need simple data structures, e.g. no WAL.
- Voldemort keeps serving the old files while copying new ones to local disk, then atomically switches; on trouble it switches back, since the old files are still there and immutable.
Philosophy of batch process outputs
- As in Unix, dataflow is explicit: input unchanged, previous output fully replaced, no other side effects. You can rerun freely while tweaking or debugging. MapReduce output follows the same philosophy, which aids performance and maintenance:
- Buggy code producing bad output? Roll back the code and rerun, or switch back to the old output kept in another directory. Databases with read-write transactions lack this: rolling back code does not repair bad data. This is human fault tolerance.
- Easy rollback lets features move faster than where mistakes are irreversible (minimizing irreversibility, good for Agile).
- Failed map/reduce tasks are rescheduled on the same input. A code bug fails the job after a few attempts; a transient fault is tolerated. Safe only because inputs are immutable and failed tasks' output is discarded.
- The same files can feed many jobs, including monitoring jobs comparing output to the previous run.
- Like Unix, logic is separated from wiring (input/output directories), so one team writes a job that does one thing well and others decide where and when it runs.
- Difference from Unix: Unix tools parse untyped text (
{print $7}); Hadoop cuts such low-value parsing by using structured formats such as Avro and Parquet, with schema-based encoding and schema evolution.
Comparing Hadoop to Distributed Databases
- Hadoop is a bit like a distributed Unix: HDFS is the filesystem, MapReduce a quirky process that always runs
sortbetween map and reduce. - The algorithms were not new: massively parallel processing (MPP) databases (Gamma database machine, Teradata, Tandem NonStop SQL) had them over a decade earlier.
- Biggest difference: MPP databases run analytic SQL in parallel; MapReduce plus a distributed filesystem is more like a general-purpose OS that runs arbitrary programs.
Diversity of storage
- Databases force a data model; distributed filesystem files are just bytes in any model and encoding: records, text, images, video, sensor readings, sparse matrices, feature vectors, genome sequences.
- Hadoop made it possible to dump data into HDFS indiscriminately and decide how to process it later. MPP databases need careful up-front modeling and import into proprietary storage.
- In practice, making data available quickly, even raw, is often worth more than ideal up-front modeling.
- Like a data warehouse, collecting an organization's data in one place enables joins across previously separate datasets. Raw collection with schema design later speeds this up: a data lake or enterprise data hub.
- Interpretation shifts from producer to consumer (schema-on-read), helpful when they are different teams. There may be no single ideal model, only different views; raw data allows many transformations: the sushi principle, "raw data is better".
- So Hadoop is often used for ETL: dump raw OLTP data, clean and transform it with MapReduce into relational form, import into an MPP warehouse. Modeling still happens, decoupled from collection.
Diversity of processing models
- MPP databases are monolithic: storage layout, query planning, scheduling and execution tuned together, giving very good performance for their target queries. SQL is expressive and usable from graphical tools (e.g. Tableau) without code.
- Not everything fits SQL: ML and recommendation systems, full-text indexes with relevance ranking, image analysis, feature engineering, translation models, fraud risk functions. These need code.
- MapReduce lets engineers run their own code over large datasets. You can build SQL on top (Hive) or write batch processes that are not SQL at all.
- Hadoop's openness allowed further models when MapReduce proved limiting, all sharing one cluster and the same HDFS files, so no data moves between specialized systems.
- The ecosystem includes OLTP databases like HBase and MPP-style analytic databases like Impala; neither uses MapReduce, but both store data on HDFS.
Designing for frequent faults
- Batch jobs are less fault-sensitive than online systems: failures do not hit users immediately and jobs can be rerun.
- MPP databases usually abort the whole query on a node crash and resubmit; fine for queries of seconds to minutes. They also keep as much as possible in memory (e.g. hash joins).
- MapReduce retries at the granularity of a single task and eagerly writes to disk, partly for fault tolerance, partly assuming data will not fit in memory. Suited to large, long jobs likely to hit at least one task failure, where rerunning the whole job would be wasteful.
- Why, if hardware rarely fails? Google's mixed-use datacenters run online services and batch on the same machines, with container-enforced allocations and priced priorities.
- Low-priority work is overcommitted and reclaimed by preemption, improving utilization; low-priority MapReduce tasks can be killed at any time.
- At Google, an hour-long MapReduce task has about a 5% chance of being terminated for a higher-priority process, over an order of magnitude more than hardware failures, reboots and similar. A job of 100 tasks of 10 minutes each has a greater than 50% risk that at least one task is killed.
- So frequent termination is tolerated for utilization, not because hardware is unreliable.
- Open source schedulers preempt less: YARN's CapacityScheduler preempts to balance queues, but general priority preemption was not supported in YARN, Mesos or Kubernetes at the time of writing. Without frequent termination, MapReduce's design choices make less sense.
| MPP databases | Hadoop / MapReduce | |
|---|---|---|
| Storage | Up-front modeling, proprietary format | Any bytes; schema-on-read, data lake |
| Processing | SQL, tightly integrated optimizer | Arbitrary code; many models on one cluster |
| Faults | Abort and rerun whole query | Retry individual tasks |
| Memory/disk | Keep data in memory (hash joins) | Write eagerly to disk |
| Best for | Seconds-to-minutes analytic queries | Huge, long jobs under frequent preemption |
Beyond MapReduce
- MapReduce was hugely hyped in the late 2000s but is only one programming model; data volume, structure and processing type may favour other tools.
- A good learning tool: simple to understand, not to use (you implement joins from scratch), hence Pig, Hive, Cascading and Crunch on top.
- The execution model itself has problems that extra abstraction does not fix. MapReduce is very robust (huge data, unreliable multi-tenant clusters, frequent terminations, it finishes, slowly), but other tools can be orders of magnitude faster for some work.
- Stream processing (Chapter 11) can be seen as another way of speeding up batch processing.
Materialization of Intermediate State
- Each MapReduce job is independent; its only contact points are input and output directories, and an external scheduler starts job 2 after job 1 finishes.
- Fine for widely published datasets: a well-known location gives loose coupling.
- But often one job's output feeds exactly one other job by the same team. Those files are just intermediate state, and 50–100-job recommendation workflows have lots of it.
- Writing intermediate state out to files is materialization (eagerly computing and writing a result rather than computing on demand). Unix pipes instead stream it incrementally through a small buffer.
Downsides of fully materializing, compared with pipes:
- A job starts only when all tasks of preceding jobs finish; piped processes run concurrently. Straggler tasks, from skew or uneven load, delay the whole workflow.
- Mappers are often redundant: they reread a file a reducer just wrote and prepare it for the next partition/sort. If reducer output were partitioned and sorted like mapper output, reducers could chain directly.
- Intermediate files in a distributed filesystem are replicated across nodes, often overkill for temporary data.
Dataflow engines
- Spark, Tez and Flink handle a whole workflow as one job rather than independent subjobs. Because they model the flow of data through stages explicitly, they are dataflow engines.
- Functions, called operators, need not alternate map and reduce. Ways to connect operators:
- Repartition and sort by key, as in the shuffle: enables sort-merge joins and grouping.
- Partition several inputs the same way but skip sorting: saves effort for partitioned hash joins, where order is irrelevant.
- Send one operator's output to all partitions of the join operator: broadcast hash joins.
- Based on research systems Dryad and Nephele. Advantages over MapReduce:
- Expensive work like sorting happens only where required, not by default between every stage.
- No unnecessary map tasks: mapper work can fold into the previous reduce operator, since a mapper does not change partitioning.
- All joins and dependencies are declared, so the scheduler can optimize locality, e.g. place consumer next to producer and exchange data via a shared memory buffer instead of the network.
- Intermediate state usually lives in memory or local disk, not replicated HDFS. MapReduce did this for mapper output; dataflow engines generalize it.
- Operators start as soon as their input is ready, without waiting for the whole previous stage.
- Existing JVM processes are reused for new operators, unlike MapReduce's new JVM per task.
- They compute the same things as MapReduce workflows, usually significantly faster. Pig, Hive or Cascading workflows can switch from MapReduce to Tez or Spark by configuration, without code changes.
- Tez is a thin library on the YARN shuffle service; Spark and Flink have their own network layer, scheduler and APIs.
Fault tolerance
- Materializing to a distributed filesystem makes intermediate state durable, so MapReduce simply restarts a failed task elsewhere on the same input.
- Spark, Flink and Tez avoid writing intermediate state to HDFS, so if a machine dies its lost state is recomputed from data still available (an earlier stage, or the original HDFS input).
- The framework must track how each piece of data was computed: input partitions and operators applied. Spark uses the resilient distributed dataset (RDD) to track ancestry; Flink checkpoints operator state to resume a failed operator.
- Recomputation needs to know if operators are deterministic. If lost data was already sent downstream and the recomputed version differs, downstream cannot reconcile; with nondeterministic operators the usual fix is to kill and rerun downstream operators too.
- Avoid such cascading faults by making operators deterministic. Nondeterminism creeps in easily: hash-table iteration order, random numbers in probabilistic algorithms, the system clock, external data sources. Fix e.g. with pseudorandom numbers from a fixed seed.
- If intermediate data is much smaller than the source, or very CPU-intensive to compute, materializing is cheaper.
Discussion of materialization
- MapReduce is like writing each command's output to a temp file; dataflow engines look like Unix pipes. Flink especially is built around pipelined execution: pass output incrementally without waiting for complete input.
- Sorting must consume its whole input before emitting anything (the last record may have the lowest key), so sort operators accumulate state at least temporarily. Much else can be pipelined.
- Final output must go somewhere durable, usually the distributed filesystem. So inputs and final outputs remain materialized on HDFS; inputs are immutable and output fully replaced. The gain is skipping intermediate writes.
Graphs and Iterative Processing
- Batch graph processing analyses a whole graph offline, common in recommendation engines and ranking.
- Example: PageRank estimates a web page's popularity from the pages linking to it; it feeds the ordering of web search results.
- Naming confusion: dataflow engines arrange operators as a DAG (the flow is a graph, data is relational tuples). In graph processing, the data is a graph.
- Many graph algorithms traverse one edge at a time, joining a vertex with its neighbour to propagate information, repeating until no edges remain or a metric converges. Example: listing all North American locations by following "within" edges (Figure 2-6), a transitive closure.
- A graph can be stored as vertex and edge files, but "repeat until done" cannot be expressed in plain MapReduce (one pass). So it is run iteratively: a scheduler runs one batch step, checks the completion condition (no more edges, or change below a threshold), and repeats if not done.
- This is very inefficient in MapReduce: each iteration reads the entire input and writes an entirely new output, even if little of the graph changed.
The Pregel processing model
- The bulk synchronous parallel (BSP) model optimizes batch graph processing. Implemented by Apache Giraph, Spark's GraphX and Flink's Gelly; also called the Pregel model after Google's Pregel paper.
- As mappers "send messages" to reducers by key, in Pregel one vertex sends messages to another, typically along edges.
- Each iteration calls a function for each vertex with all messages sent to it, like a reducer call. The difference: a vertex keeps its state in memory across iterations, so it handles only new messages. Parts of the graph with no messages do no work.
- Resembles the actor model (vertex = actor), except vertex state and messages are fault-tolerant and durable, and communication runs in fixed rounds: every iteration delivers all messages from the previous one.
Fault tolerance
- Vertices communicate only by messages, not direct queries, so messages can be batched and there is less waiting. The only wait is between iterations: all messages of one iteration must be delivered before the next starts.
- Even if the network drops, duplicates or delays messages, Pregel implementations guarantee each message is processed exactly once at its destination in the next iteration, and recover from faults transparently.
- Achieved by checkpointing all vertex state to durable storage at the end of an iteration. On node failure, roll the whole computation back to the last checkpoint; if the algorithm is deterministic and messages are logged, only the lost partition need be recovered.
Parallel execution
- A vertex sends to a vertex ID without knowing its machine; the framework partitions the graph and routes messages.
- Because code deals with one vertex at a time ("thinking like a vertex"), partitioning can be arbitrary. Ideally chatty vertices are colocated, but that is hard, so graphs are often just partitioned by arbitrary vertex ID.
- Result: heavy cross-machine communication; intermediate state (messages) is often bigger than the graph, and network overhead can slow distributed graph algorithms significantly.
- So if the graph fits in one machine's memory, a single-machine (maybe single-threaded) algorithm will likely beat a distributed batch job. If it fits on one machine's disks, single-machine frameworks such as GraphChi are viable. Only when it exceeds one machine is a distributed approach like Pregel unavoidable; efficient parallel graph algorithms are ongoing research.
High-Level APIs and Languages
- Execution engines have matured to store and process many petabytes on clusters of over 10,000 machines. With operations at that scale considered more or less solved, focus moved to the programming model, efficiency, and broader problem coverage.
- Hive, Pig, Cascading and Crunch became popular because hand-written MapReduce is laborious; with Tez they could move to a dataflow engine without rewriting jobs. Spark and Flink have their own high-level dataflow APIs, often inspired by FlumeJava.
- These APIs use relational-style building blocks: join on a field, group by key, filter, aggregate (count, sum, etc.), implemented internally with the join and grouping algorithms of this chapter.
- They also allow interactive, incremental use in a shell, echoing the Unix philosophy.
The move toward declarative query languages
- With joins expressed as relational operators, the framework can analyse inputs and pick the best join algorithm itself. Hive, Spark and Flink have cost-based query optimizers that do this and can reorder joins to minimize intermediate state.
- Otherwise MapReduce and its successors differ from fully declarative SQL: they are built on function callbacks that can run arbitrary code, letting you use libraries for parsing, natural language, image analysis, numerical and statistical algorithms.
- MPP databases' user-defined functions are often cumbersome and poorly integrated with package managers (Maven, npm, Rubygems).
- Declarative features help beyond joins too. Calling a callback per record just to filter or select fields costs significant CPU. Expressed declaratively, the optimizer can use column-oriented storage and read only needed columns.
- Hive, Spark DataFrames and Impala use vectorized execution: tight, cache-friendly inner loops without function calls. Spark generates JVM bytecode; Impala uses LLVM to generate native code.
- With declarative APIs and optimizers, batch frameworks look more like MPP databases and reach comparable performance, while keeping the flexibility of arbitrary code and arbitrary data formats.
Specialization for different domains
- Recurring patterns deserve reusable building blocks; business reporting is only one domain.
- Statistical and numerical algorithms for ML (classification, recommendation): Mahout implements ML on MapReduce, Spark and Flink; MADlib does similar inside a relational MPP database (Apache HAWQ).
- Spatial algorithms such as k-nearest neighbors (similarity search in multi-dimensional space); approximate search for genome analysis (similar but not identical strings).
- As batch systems gain built-in functionality and declarative operators, and MPP databases become more programmable, the two converge: all are systems for storing and processing data.
Summary
- Unix design principles carry into MapReduce and dataflow engines: immutable inputs, outputs meant for an unknown next program, small tools that "do one thing well".
- Uniform interface: files and pipes in Unix, the distributed filesystem in MapReduce. Dataflow engines add pipe-like transport, but job input and final output usually stay on HDFS.
- Partitioning: mappers follow input blocks; their output is repartitioned, sorted and merged into reducer partitions to bring records with the same key together. Dataflow engines sort only when required.
- Fault tolerance: MapReduce writes to disk often, so single tasks recover easily but fault-free runs are slower. Dataflow engines keep more in memory and recompute more on failure; deterministic operators limit that.
- Joins: sort-merge (same key reaches one reducer call), broadcast hash (small input as a hash table in every mapper), partitioned hash (same key, hash function and partition count, joined per partition).
- Callbacks are assumed stateless with no external side effects, so tasks retry safely, failed output is discarded and only one successful attempt per partition becomes visible. Output equals a fault-free run, far stronger than online services writing to databases as a side effect.
- A batch job derives output from bounded input without modifying it, so it knows when it is done. Stream processing (Chapter 11) handles unbounded input, where a job never completes.
Condensed from Designing Data-Intensive Applications by Martin Kleppmann (O'Reilly, 2017). Parts I-III (complete book), 12 chapters.