这讲要解决什么
- 解释为什么需要分布式系统的核心问题
- 按协议顺序推演Map、Shuffle、Reduce
- 评估工程取舍:MapReduce 牺牲交互式和任意通信模型,换取调度、并行化与失败恢复的统一框架。
先建立整门课的坐标系:系统究竟在和什么对抗
假设你要为一个搜索引擎每天处理 20 TB 网页。单机程序本身并不神秘:逐页解析、发射单词、聚合计数即可。困难来自规模。一块磁盘顺序读 20 TB 需要很久,一台机器的 CPU、内存和网络也有硬上限,于是我们把输入分给上千台机器。但机器一多,新的问题会同时出现:任务并发执行、数据分散在不同位置、慢机器拖住全局、机器和网络持续发生部分失败。
这就是本课反复使用的三个坐标。性能问的是增加 N 台机器能否接近获得 N 倍吞吐;容错问的是一部分组件失败时服务能否继续;一致性问的是并发与复制之后,应用看到的结果还能否用清楚的规则解释。三者并不独立:复制改善容错,却增加通信;等待更多副本改善一致性,却抬高延迟;跳过等待提高速度,却可能读到旧数据。
MapReduce 是第一讲最合适的入口,因为它没有试图解决任意分布式程序。它先限制应用只能写两个近似纯函数,再由框架接管切分、调度、shuffle、重试和输出发布。学习这一讲时不要先背组件名,而要反复问:框架从程序员手里拿走了哪种自由,因此获得了哪种可自动化的保证?
老师 notes 先介绍课程,再用 MapReduce 把整门课的主题压缩成一个案例;论文则把这个案例展开为可实现、可测量的系统。下面的顺序也遵循这个教学意图:先亲手执行一个小作业,再扩到 M×R 文件矩阵,随后加入故障和性能,最后连接 Lab 1。
为什么需要分布式系统
分布式系统是一组通过网络协作、共同提供服务的计算机。把计算分散出去可以扩展容量、贴近物理设备并利用隔离提升安全性,但也引入并发、部分失败和不可预测延迟。所谓“部分失败”是关键:某台机器或某条链路可能坏掉,而其余组件仍然正常,因此观察者很难区分对方宕机和消息只是很慢。
Map、Shuffle、Reduce
MapReduce 把作业限制为三段:Map 独立处理输入分片并产生中间键值对;Shuffle 按 key 分区、拉取和排序;Reduce 聚合同一 key 的所有值。协调器负责分配任务、跟踪完成状态并把 Map 输出位置告诉 Reduce。限制程序结构换来了可调度性:Map 任务互不依赖,Reduce 任务在输入齐备后也能并行执行。
不用框架术语,亲手把 WordCount 跑完一次
取三份输入:D1=a b a,D2=b c,D3=a c c,并设置两个 Reduce 分区。Map 并不是“输出一个计数表”,而是为每次出现发射键值对:D1 产生 (a,1),(b,1),(a,1)。随后 partitioner 对每个 key 计算固定分区;假设 a、c 进入分区 0,b 进入分区 1,那么每个 Map task 都会留下两个逻辑桶,即便其中一个为空。
Shuffle 做两件容易混淆的事。第一件是按分区搬运:Reduce-0 从三个 Map 执行位置分别取走桶 0。第二件是在分区内按 key 分组和排序:它把所有 a 的值放到一起,把所有 c 的值放到一起。只有这时用户的 Reduce 函数才看到 a,[1,1,1]。框架保证相同 key 到同一个 Reduce,但不同 key 的全局顺序、不同输出文件之间的顺序并不是应用契约。
现在把机器概念加回来。输入分片是逻辑任务,worker 是一次执行任务的物理进程;两者不能混为一谈。一个 worker 可以连续执行多个 task,一个 task 也可能因超时被多个 worker 先后甚至同时尝试。协调器追踪的必须是逻辑 task 的状态和当前被接受的执行结果,而不是把“机器完成了”当作永久事实。
这一步手算完成后,论文 Figure 1 的所有箭头都有了意义:输入来自 GFS,Map 结果留在本地,位置回报给 coordinator,Reduce 主动拉取属于自己的桶,最终输出重新进入 GFS。先掌握数据如何移动,再谈调度和恢复,否则“shuffle”只会变成一个没有内容的名词。
数据本地性与负载均衡
输入和最终输出放在 GFS,中间结果先落到 Map worker 本地磁盘。协调器尽量把 Map 安排到持有输入副本的机器上,从而减少穿过机架交换机的流量。任务数量远多于 worker 数量,较快的机器自然领取更多任务;尾部阶段还可对慢任务启动备份执行,降低 straggler 对总完成时间的影响。
失败恢复为什么依赖确定性
worker 失败时,协调器只重跑丢失的 Map 或 Reduce。若同一 Map 被执行两次,不同 Reduce 可能看到不同副本;因此用户函数应当近似纯函数:同一输入生成同一输出,不依赖随机数、外部可变状态或不可重复 I/O。Reduce 的输出通过临时文件加原子 rename 发布,避免两个尝试把半成品混在一起。
从一个作业追到每一份中间文件
不要把 MapReduce 只记成 Map → Reduce 两个函数。运行时首先把输入文件切成 M 个逻辑分片,协调器为每个分片创建 Map task;worker 领取任务后读取分片,调用用户的 Map 函数,并把中间键值对按 hash(key) mod R 分成 R 个桶。每个 Map task 因而产生 R 份本地文件,而不是一份“统一的中间结果”。
当某个 Map 完成时,worker 向协调器报告这些本地文件的位置。第 r 个 Reduce task 从全部 M 个 Map worker 拉取第 r 个桶,所以它的输入是 M 份文件的并集。Reduce 端先归并、按 key 排序,再对每个 key 调用一次 Reduce。最终形成 R 个独立的 GFS 输出文件;框架不会自动把它们合成一个文件。
这个 M×R 文件矩阵解释了许多工程现象:M 或 R 太小会失去并行度,过大则增加调度、文件和网络连接开销;Map worker 崩溃会让其本地中间文件全部丢失,即使对应 Map 曾经报告完成,也必须重跑;Reduce 输出在 GFS 上,因此完成后通常不因 worker 崩溃而重算。
理解任务状态时要区分“计算完成”和“结果仍可访问”。协调器记录 Map/Reduce 的 idle、in-progress、completed 状态,却不能仅凭 completed 永久相信本地中间结果。真正的不变量是:一个 Reduce 被允许完成之前,它必须从每个逻辑 Map task 选定的一次成功执行中取得自己的分区。
失败恢复不是一句“重跑”
MapReduce 假设机器与进程呈现 fail-stop:要么正确执行,要么停止响应;它不处理 worker 悄悄算错结果的拜占庭故障。协调器通过 RPC、超时或周期性探测推断 worker 失效,但“没有回复”只说明当前无法通信,不能证明对方已经停止。因此同一逻辑 task 可能同时存在多个执行尝试。
重复 Map 尝试相对容易处理:协调器选定其中一次完成结果,把位置通知给 Reduce。前提是用户函数确定性足够强,使不同尝试产生等价分区内容。重复 Reduce 更敏感,因为多个尝试可能同时发布同一个最终文件;框架让每次尝试先写临时文件,再用 GFS 的原子 rename 把一份完整结果暴露出来,避免半份 A 与半份 B 混合。
“看起来 exactly-once”来自确定性计算与原子发布的组合,并不覆盖外部副作用。如果 Map 在数据库里扣款、发邮件或调用第三方 API,重试会重复副作用,MapReduce 没有事务替你撤销。课程后面的客户端序列号、去重表与分布式事务,正是在补这条边界。
协调器自身是论文设计中的单点。论文允许周期性 checkpoint 并在失败后重新启动,也可能直接让作业失败、由用户重交。它没有用共识协议复制协调状态;因此 MapReduce 展示了一个常见取舍:先让大规模数据面可恢复,而不是让所有控制面状态都具备自动容错。
用字节流量解释数据本地性与拖尾
论文时代的瓶颈不是抽象的“网络慢”,而是 shuffle 的 all-to-all 流量集中穿过根交换机。1800 台机器挂在两级网络下,只有同一接入交换机内的少量流量不经过上层;排序作业的中间数据又接近输入规模,所以根交换机的总带宽会被所有 worker 共享。优化必须从“哪些字节跨越哪条链路”开始,而不是只数 RPC 次数。
数据本地性让 Map 尽量在持有对应 GFS chunk 副本的机器上运行,输入从本地磁盘读取;机架本地是次优选择。中间结果只写 Map worker 本地盘,随后由 Reduce 跨网读取一次。如果把中间结果写入三副本 GFS,会为了短命、可重算的数据付出额外复制流量。这里的原则是根据重建成本选择持久性:输入和最终输出需要复制,中间数据可以丢失后重算。
负载均衡靠“任务远多于 worker”实现动态分配。若一台机器快,它自然连续领取更多小任务;若某些分片难处理,其余机器完成自己的任务后仍可帮忙。接近作业尾声时,少数 straggler 决定总时长,框架对最后几个任务启动备份执行,以额外资源换取更低的尾延迟。
但备份执行不应从作业一开始就泛滥,否则会让正常任务争抢 CPU、磁盘和网络。判断优化是否有效要区分吞吐、平均完成时间和尾部完成时间:更多副本通常不增加逻辑工作吞吐,却可能显著缩短最后一个任务的等待。
把上面的机制落到消息、状态与失败路径中。
输入尽量位于执行 Map 的机器
产生 M×R 份本地中间文件
Shuffle 的主要瓶颈
拉取同一分区并写最终结果
论文不是装饰:怎样用 Figure 2 和实验表验证设计
读 MapReduce 论文时,先用 §3 的实现细节解释机制,再用 §5 的实验回答“这些机制真的改变了什么”。Figure 2 的正常排序曲线应被拆成输入读取、Map、shuffle、Reduce 和输出几个阶段观察;横轴是时间,纵轴是累计数据率,而不是简单的 CPU 利用率。开始阶段输入读取快速上升,随后网络 shuffle 成为主要数据移动,Reduce 输出比输入小或大取决于应用。
论文的故障实验在运行中杀死 200 个 worker,曲线出现短暂停顿后继续。这里验证的不是“故障没有成本”,而是协调器能重新分配未完成 task、能让已完成但中间文件丢失的 Map 重新执行,并且剩余 worker 能吸收工作。若重算机制错误,曲线不会只是变慢,而会永久缺输入或生成不完整输出。
备份任务实验把总时间从没有 backup 的较长尾部显著缩短。证据对应的是尾延迟,不应被误读成所有任务都更快。论文还报告 master 在每个 task 只保存少量状态,因此可以管理数十万 task;但 M×R 中间文件位置会带来更大的元数据量,这也是任务粒度不能无限缩小的原因。
把论文数据放回课堂问题:数据本地性减少输入跨网,分区函数决定 shuffle 均衡,备份执行对抗 straggler,原子 rename 处理重复 Reduce 发布。论文中的每个优化都应该能在执行图中指向具体字节、具体等待或具体失败窗口。这样阅读论文才是在检验系统设计,而不是摘录结论。
限制编程模型,换取框架可推理性
MapReduce 的力量来自约束,而不是通用性。Map task 之间不能交互,Reduce 在 shuffle 边界之后才开始使用完整分区数据;应用的持久状态只通过输入、中间键值对和最终输出表达。正因为依赖图固定,框架才能自由移动任务、重试执行、按 key 分区并估算完成状态。
代价是它不适合低延迟请求、持续流、迭代算法和需要细粒度共享状态的程序。一次 MapReduce 迭代要把阶段边界物化到磁盘;图算法或机器学习若迭代几十次,就会反复承担调度与 I/O。后来系统如 Spark 保留数据并行思想,却加入内存数据集和更丰富的依赖图。
学习本讲时,应把“性能、容错、一致性”放在同一张账上:纯函数与重算降低恢复复杂度;本地中间结果节省网络与复制,却让 Map worker 故障触发重算;大任务数量改善均衡,却增加调度开销;弱化应用表达能力,换来框架能自动完成大部分分布式工程。
因此 MapReduce 不是“所有分布式计算的答案”,而是一个清晰范例:先找出可被固定数据流表达的工作负载,再把调度、失败恢复与数据移动统一交给运行时。后续每个系统都可以用同一问题审视:它限制了什么,因此获得了什么自动化保证?
把论文模型落到 Lab 1:你真正要实现的不是两个函数
Lab 1 的 coordinator/worker 是论文架构的缩小版。先写出 coordinator 的状态机:每个 Map/Reduce task 至少有 idle、in-progress、done;领取任务令 idle→in-progress,成功报告令 in-progress→done,超时令 in-progress→idle。状态迁移必须在锁内完成,否则两个 worker 会同时领到同一编号而 coordinator 自己却不知道存在两个尝试。
执行顺序有一道硬门槛:所有逻辑 Map task 完成后才能发放 Reduce。原因不是风格,而是 Reduce 的输入集合由全部 M 个 Map 的分区文件组成。worker 写中间文件时应先写临时文件,再原子 rename 到稳定名字;Reduce 输出同理。这样协调器即使重复分配,读者也不会看到半写文件。
超时回收不能依赖 handler 永远返回。更稳妥的结构是领取时记录开始时间,后台定期扫描;旧执行稍后报告成功时,要验证当前任务是否仍属于它或接受幂等完成,不能把已经重新分配后的状态倒退。测试失败时打印 task kind / id / attempt / old state / new state,从第一条非法迁移找问题。
学完本讲,你应该能独立讲清完整因果链:受限函数使 task 可重跑;M×R 切分使计算可并行;本地中间数据降低开销但要求 Map 故障重算;原子发布吸收重复尝试;大量小 task 与 backup execution 改善负载和尾延迟。能讲清这条链,再开始写 Lab,代码结构会自然得多。
教案覆盖地图
覆盖口径:教师 notes/讲义原文逐行完整保留;中文教学单元覆盖课堂机制、失败路径与工程取舍;1/1 个显式板书占位已重绘;论文另设“问题—机制—证据—边界”阅读导航。覆盖不是用摘要替代原文,任何细节都可在页面末尾回查。
316 行 · 1,654 词 · 完整可搜索文本
1,278 行 · 9,235 词 · 完整可搜索文本
展开中文教学单元映射(12 项)
- 01先建立整门课的坐标系:系统究竟在和什么对抗
- 02为什么需要分布式系统
- 03Map、Shuffle、Reduce
- 04不用框架术语,亲手把 WordCount 跑完一次
- 05数据本地性与负载均衡
- 06失败恢复为什么依赖确定性
- 07从一个作业追到每一份中间文件
- 08失败恢复不是一句“重跑”
- 09用字节流量解释数据本地性与拖尾
- 10论文不是装饰:怎样用 Figure 2 和实验表验证设计
- 11限制编程模型,换取框架可推理性
- 12把论文模型落到 Lab 1:你真正要实现的不是两个函数
论文要读到哪里
如何让普通程序员使用上千台不可靠机器完成批处理?
把程序约束成 Map、Shuffle、Reduce,并由运行时负责切分、调度、数据本地性、备份执行与失败重算。
重点读论文 §2 执行模型、§3 实现、§5 性能;用 M×R 中间文件矩阵解释网络流量和恢复代价。
确定性与原子文件发布只能约束框架内结果;外部副作用、交互式计算和迭代工作负载不在保证内。
把直觉校准成不变量
重跑任务天然等价于 exactly-once。
重跑只在确定性计算和原子发布边界内表现得像一次;外部副作用仍需额外的幂等或事务机制。
只记住正常路径就足以实现协议。
分布式协议的正确性主要由超时、重试、重排、崩溃恢复和旧消息路径决定。
知识检查
Shuffle 阶段的核心职责是什么?
下列哪项最准确概括本讲的主要工程取舍?
为什么“重跑任务天然等价于 exactly-once。”是错误的?
离开本讲前,你应能复述
- 分布式系统是一组通过网络协作、共同提供服务的计算机。
- MapReduce 牺牲交互式和任意通信模型,换取调度、并行化与失败恢复的统一框架。
- 重跑只在确定性计算和原子发布边界内表现得像一次;外部副作用仍需额外的幂等或事务机制。
完整官方资料附录
以下是本讲对应官方材料的可搜索离线文本。中文精读负责解释;资料附录保留原始细节、例子、问答与代码,不以摘要替代原文。
课堂讲义notes/l01.txt316 行 · 1,654 词 · 完整收录
6.5840 2026 Lecture 1: Introduction
6.5840: Distributed Systems Engineering
A "distributed system":
a group of computers cooperating to provide a service
Examples:
popular apps' back-ends, e.g. for messaging
big web sites
cloud providers
Focus here is distributed infrastructure:
storage
transaction systems
"big data" processing frameworks
Hard to build:
concurrency
complex interactions
performance bottlenecks
partial failure
Why useful?
to increase capacity via parallel processing
to tolerate faults via replication
to match distribution of physical devices e.g. sensors
to increase security via isolation
Why take this course?
interesting -- hard problems, powerful solutions
big demand -- driven by the rise of big Web sites
active research area -- important unsolved problems
challenging -- the labs
COURSE STRUCTURE
http://pdos.csail.mit.edu/6.5840
Course staff:
Frans Kaashoek and Robert Morris, lecturers
Baltasar Dinis, TA
Ayana Alemayehu, TA
Upamanyu Sharma, TA
Yun-Sheng Chang, TA
Danny Villanueva, TA
Brian Shi, TA
Nour Massri, TA
Beshr Islam Bouli, TA
Lectures:
paper discussion, context, lab guidance
Papers:
one per lecture
research papers, some classic, some new
ideas, problems, implementation details, evaluation
please read papers before class!
web site has a question about each paper
submit your answer before start of lecture
optionally, submit a question for us
Exams:
Mid-term exam in class
Final exam during finals week
papers, lectures, and labs
You must attend the exams!
Labs:
goal: deeper grasp of some important techniques
goal: experience with distributed programming
first lab is due a week from Friday
one per week after that for a while
Lab 1: distributed big-data framework (like MapReduce)
Lab 2: client/server vs unreliable network
Lab 3: fault tolerance using replication (Raft)
Lab 4: a fault-tolerant database
Lab 5: scalable database performance via sharding
We grade the labs using a set of tests
we give you all the tests; none are secret
Optional final project at the end, in groups of 2 or 3.
The final project substitutes for Lab 5.
You think of a project and clear it with us.
Code, short write-up, demo on last day.
Warning: debugging the labs can be time-consuming
start early
ask questions on Piazza
TA office hours
MAIN TOPICS
This is a course about infrastructure.
* Storage.
* Communication.
* Computation.
A big goal: hide the complexity of distribution from applications.
Topic: fault tolerance
1000s of servers, big network -> constant failures
We'd like to hide these failures.
"High availability": service continues despite failures
Big idea: replication.
If one server crashes, can proceed using the other(s).
Topic: consistency
General-purpose infrastructure needs well-defined behavior.
E.g. "read(x) yields the value from the most recent write(x)."
Guaranteeing specified behavior is hard!
e.g. "replica" servers are hard to keep identical.
Topic: performance
A common goal: scalable throughput
Nx servers -> Nx total throughput via parallel CPU, RAM, disk, net.
Scaling gets harder as N grows
e.g. load imbalance.
Topic: tradeoffs
Fault-tolerance, consistency, and performance are enemies.
Fault tolerance and consistency require communication
e.g., send data to backup server
e.g., check if cached data is up-to-date
but communication is often slow and hard to scale up
Many designs sacrifice consistency to gain speed.
e.g. read(x) might *not* yield the latest write(x)!
Painful for application programmers (or users).
We'll see many consistency/performance design points.
Topic: implementation
RPC, threads, concurrency control.
The labs...
CASE STUDY: MapReduce
Let's talk about MapReduce (MR)
a good illustration of 6.5840's main topics
hugely influential
the focus of Lab 1
Context: multi-hour computations on multi-terabyte data-sets
e.g. build search index, or sort, or analyze structure of web
only practical with 1000s of computers
A big goal: easy for non-specialist programmers
programmer just defines Map and Reduce functions
often simple sequential code
MR manages, and hides, all aspects of distribution!
MR is a framework / library; "application" is just Map()/Reduce()
Abstract view of a MapReduce job -- word count
Input1 -> Map -> a,1 b,1
Input2 -> Map -> b,1
Input3 -> Map -> a,1 c,1
| | |
| | -> Reduce -> c,1
| -----> Reduce -> b,2
---------> Reduce -> a,2
1) input is (already) split into M pieces
2) MR calls Map() for each input split, produces list of k,v pairs
"intermediate" data
each Map() call is a "task"
3) when Maps are done,
MR gathers all intermediate v's for each k,
and passes each key + values to a Reduce call
4) final output is set of <k,v> pairs from Reduce()s
Word-count code
Map(d)
chop d into words
for each word w
emit(w, "1")
Reduce(k, v[])
emit(len(v[]))
MapReduce scales well:
N "worker" computers (might) get you Nx throughput.
Maps()s can run in parallel, since they don't interact.
Same for Reduce()s.
Thus more computers -> more throughput -- very nice!
MapReduce hides much complexity:
sending map+reduce code to servers
tracking which tasks have finished
"shuffling" intermediate data from Maps to Reduces
balancing load over servers
recovering from crashed servers
To get these benefits, MapReduce restricts applications:
Only one pattern (Map -> shuffle -> Reduce).
No interaction or state (other than via intermediate output).
Only batch: no real-time or streaming processing.
Some details (paper's Figure 1)
Input and output are stored on the GFS cluster file system
MR needs huge parallel input and output throughput.
GFS splits files over many servers, many disks, in 64 MB chunks
Maps read in parallel
Reduces write in parallel
GFS replicates data on 2 or 3 servers, for fault tolerance
GFS is a big win for MapReduce
MR writes Map() output to local disk
MR splits into files by hash(key) mod R
each "hash bucket" contains multiple keys
The map workers all hash the same way
The shuffle
each Reduce task processes one hash bucket
MR fetches each Reduce tasks' bucket from every Map worker
merge, sort by key, call Reduce() for each key
each Reduce task writes a separate output file on GFS
The "Coordinator" manages all the steps in a job.
tracks state of each task
hands out tasks to worker machines
What will limit performance?
We care since that limit is the thing to optimize.
CPU? memory? disk? network?
In 2004 authors were limited by network speed.
What does MR send over the network?
Maps read input from GFS.
Reduces fetch Map intermediate output.
Often as large as input, e.g. for sorting.
Reduces write output files to GFS.
How fast was the paper's network?
Section 5.1: 1800 machines, two-level switched network
[diagram: root switch, 2nd level of switches, machines]
each switch must have had ~42 ports (square root of 1800)
MR's shuffle requires every worker to fetch data from every other
Only 1/42nd stays in local switch
So MR's shuffle sends most data through root switch.
Paper's root switch: 100 to 200 gigabits/second, total
1800 machines, so ~55 megabits/second/machine.
55 is small: less than disk or RAM speed.
How does MR minimize network use?
Coordinator tries to run each Map task on GFS server that stores its input.
All computers run both GFS and MR workers
So Map input is usually read from GFS data on local disk, not over network.
Intermediate data goes over network just once.
Map worker writes to local disk.
Reduce workers read from Map worker disks over the network.
(Storing it in GFS would require at least two trips over the network.)
How does MR get good load balance?
Why do we care about load balance?
If one server has more work than others, or is slower,
then other servers will lie idle (wasted) at the end, waiting.
So ideally MR divides work so that all workers finish at same time.
But tasks vary in size, and computers vary in speed.
Solution: many more tasks than worker machines.
Coordinator hands out new tasks to workers who finish previous tasks.
So faster servers do more tasks than slower ones.
And slow servers are given less work, reducing impact on total time.
What about fault tolerance?
What if a worker computer crashes?
We want MR framework to hide failures.
Does MR have to re-run the whole job from the beginning?
Why not?
Coordinator re-runs just the failed Map()s and Reduce()s.
Suppose MR runs a Map task twice, one Reduce sees first run's output,
but another Reduce sees the second run's output?
The two Map executions had better produce identical intermediate output!
Map and Reduce should be pure deterministic functions:
they are only allowed to look at their arguments/input.
no state, no file I/O, no interaction, no external communication,
no random numbers.
Programmer is responsible for ensuring this determinism.
Other failures/problems:
* What if the coordinator gives two workers the same Map() task?
perhaps the coordinator incorrectly thinks one worker died.
it will tell Reduce workers about only one of them.
* What if the coordinator gives two workers the same Reduce() task?
they will both try to write the same output file on GFS!
atomic GFS rename prevents mixing; one complete file will be visible.
* What if a single worker is very slow -- a "straggler"?
perhaps due to flakey hardware.
coordinator starts a second copy of last few tasks.
* What if a worker computes incorrect output, due to broken h/w or s/w?
too bad! MR assumes "fail-stop" CPUs and software.
* What if the coordinator crashes?
Performance?
Figure 2
X-Axis is time
Y-Axis is total rate at which a "grep"-style job reads its input
A terabyte (1000 GB) of input
1764 workers
30,000 MB/s (30 GB/s) is huge!
Why 30,000 MB/s?
17 MB/s per worker machine -- 140 megabits/second
more than our guess (55 mbit/s) of net bandwidth
input probably read direct from two local GFS disks
so each disk probably could read at about 9 MB/second
Why is the main period of activity about 30 seconds?
Why does it take 50 seconds for throughput to reach maximum?
Current status?
Hugely influential (Hadoop, Spark, Lab 1, &c).
Probably no longer in use at Google.
Replaced by Flume / FlumeJava (see paper by Chambers et al).
GFS replaced by Colossus (no good description), and BigTable.
Next lecture:
Programming: Go, Threads, RPCPDF 文本转录papers/mapreduce.pdf1,278 行 · 9,235 词 · 完整收录
MapReduce: Simplified Data Processing on Large Clusters
Jeffrey Dean and Sanjay Ghemawat
jeff@google.com, sanjay@google.com
Google, Inc.
Abstract
MapReduce is a programming model and an associ-
ated implementation for processing and generating large
data sets. Users specify a map function that processes a
key/value pair to generate a set of intermediate key/value
pairs, and a reduce function that merges all intermediate
values associated with the same intermediate key. Many
real world tasks are expressible in this model, as shown
in the paper.
Programs written in this functional style are automati-
cally parallelized and executed on a large cluster of com-
modity machines. The run-time system takes care of the
details of partitioning the input data, scheduling the pro-
gram’s execution across a set of machines, handling ma-
chine failures, and managing the required inter-machine
communication. This allows programmers without any
experience with parallel and distributed systems to eas-
ily utilize the resources of a large distributed system.
Our implementation of MapReduce runs on a large
cluster of commodity machines and is highly scalable:
a typical MapReduce computation processes many ter-
abytes of data on thousands of machines. Programmers
find the system easy to use: hundreds of MapReduce pro-
grams have been implemented and upwards of one thou-
sand MapReduce jobs are executed on Google’s clusters
every day.
1 Introduction
Over the past five years, the authors and many others at
Google have implemented hundreds of special-purpose
computations that process large amounts of raw data,
such as crawled documents, web request logs, etc., to
compute various kinds of derived data, such as inverted
indices, various representations of the graph structure
of web documents, summaries of the number of pages
crawled per host, the set of most frequent queries in a
given day, etc. Most such computations are conceptu-
ally straightforward. However, the input data is usually
large and the computations have to be distributed across
hundreds or thousands of machines in order to finish in
a reasonable amount of time. The issues of how to par-
allelize the computation, distribute the data, and handle
failures conspire to obscure the original simple compu-
tation with large amounts of complex code to deal with
these issues.
As a reaction to this complexity, we designed a new
abstraction that allows us to express the simple computa-
tions we were trying to perform but hides the messy de-
tails of parallelization, fault-tolerance, data distribution
and load balancing in a library. Our abstraction is in-
spired by the map and reduce primitives present in Lisp
and many other functional languages. We realized that
most of our computations involved applying a map op-
eration to each logical “record” in our input in order to
compute a set of intermediate key/value pairs, and then
applying a reduce operation to all the values that shared
the same key, in order to combine the derived data ap-
propriately. Our use of a functional model with user-
specified map and reduce operations allows us to paral-
lelize large computations easily and to use re-execution
as the primary mechanism for fault tolerance.
The major contributions of this work are a simple and
powerful interface that enables automatic parallelization
and distribution of large-scale computations, combined
with an implementation of this interface that achieves
high performance on large clusters of commodity PCs.
Section 2 describes the basic programming model and
gives several examples. Section 3 describes an imple-
mentation of the MapReduce interface tailored towards
our cluster-based computing environment. Section 4 de-
scribes several refinements of the programming model
that we have found useful. Section 5 has performance
measurements of our implementation for a variety of
tasks. Section 6 explores the use of MapReduce within
Google including our experiences in using it as the basis
OSDI ’04: 6th Symposium on Operating Systems Design and ImplementationUSENIX Association 137
for a rewrite of our production indexing system. Sec-
tion 7 discusses related and future work.
2 Programming Model
The computation takes a set of input key/value pairs, and
produces a set of output key/value pairs. The user of
the MapReduce library expresses the computation as two
functions: Map and Reduce.
Map, written by the user, takes an input pair and pro-
duces a set of intermediate key/value pairs. The MapRe-
duce library groups together all intermediate values asso-
ciated with the same intermediate key I and passes them
to the Reduce function.
The Reduce function, also written by the user, accepts
an intermediate key I and a set of values for that key. It
merges together these values to form a possibly smaller
set of values. Typically just zero or one output value is
produced per Reduce invocation. The intermediate val-
ues are supplied to the user’s reduce function via an iter-
ator. This allows us to handle lists of values that are too
large to fit in memory.
2.1 Example
Consider the problem of counting the number of oc-
currences of each word in a large collection of docu-
ments. The user would write code similar to the follow-
ing pseudo-code:
map(String key, String value):
// key: document name
// value: document contents
for each word w in value:
EmitIntermediate(w, "1");
reduce(String key, Iterator values):
// key: a word
// values: a list of counts
int result = 0;
for each v in values:
result += ParseInt(v);
Emit(AsString(result));
The map function emits each word plus an associated
count of occurrences (just ‘1’ in this simple example).
The reduce function sums together all counts emitted
for a particular word.
In addition, the user writes code to fill in a mapreduce
specification object with the names of the input and out-
put files, and optional tuning parameters. The user then
invokes the MapReduce function, passing it the specifi-
cation object. The user’s code is linked together with the
MapReduce library (implemented in C++). Appendix A
contains the full program text for this example.
2.2 Types
Even though the previous pseudo-code is written in terms
of string inputs and outputs, conceptually the map and
reduce functions supplied by the user have associated
types:
map (k1,v1) → list(k2,v2)
reduce (k2,list(v2)) → list(v2)
I.e., the input keys and values are drawn from a different
domain than the output keys and values. Furthermore,
the intermediate keys and values are from the same do-
main as the output keys and values.
Our C++ implementation passes strings to and from
the user-defined functions and leaves it to the user code
to convert between strings and appropriate types.
2.3 More Examples
Here are a few simple examples of interesting programs
that can be easily expressed as MapReduce computa-
tions.
Distributed Grep: The map function emits a line if it
matches a supplied pattern. The reduce function is an
identity function that just copies the supplied intermedi-
ate data to the output.
Count of URL Access Frequency: The map func-
tion processes logs of web page requests and outputs
⟨URL, 1⟩. The reduce function adds together all values
for the same URL and emits a ⟨URL, total count ⟩
pair.
Reverse Web-Link Graph: The map function outputs
⟨target, source⟩ pairs for each link to a target
URL found in a page named source. The reduce
function concatenates the list of all source URLs as-
sociated with a given target URL and emits the pair:
⟨target, list(source)⟩
T erm-Vector per Host: A term vector summarizes the
most important words that occur in a document or a set
of documents as a list of ⟨word, f requency⟩ pairs. The
map function emits a ⟨hostname, term vector ⟩
pair for each input document (where the hostname is
extracted from the URL of the document). The re-
duce function is passed all per-document term vectors
for a given host. It adds these term vectors together,
throwing away infrequent terms, and then emits a final
⟨hostname, term vector ⟩ pair.
OSDI ’04: 6th Symposium on Operating Systems Design and Implementation USENIX Association138
User
Program
Master
(1) fork
worker
(1) fork
worker
(1) fork
(2)
assign
map
(2)
assign
reduce
split 0
split 1
split 2
split 3
split 4
output
file 0
(6) write
worker
(3) read
worker
(4) local write
Map
phase
Intermediate files
(on local disks)
worker output
file 1
Input
files
(5) remote read
Reduce
phase
Output
files
Figure 1: Execution overview
Inverted Index: The map function parses each docu-
ment, and emits a sequence of ⟨word, document ID ⟩
pairs. The reduce function accepts all pairs for a given
word, sorts the corresponding document IDs and emits a
⟨word, list(document ID )⟩ pair. The set of all output
pairs forms a simple inverted index. It is easy to augment
this computation to keep track of word positions.
Distributed Sort: The map function extracts the key
from each record, and emits a ⟨key, record⟩ pair. The
reduce function emits all pairs unchanged. This compu-
tation depends on the partitioning facilities described in
Section 4.1 and the ordering properties described in Sec-
tion 4.2.
3 Implementation
Many different implementations of the MapReduce in-
terface are possible. The right choice depends on the
environment. For example, one implementation may be
suitable for a small shared-memory machine, another for
a large NUMA multi-processor, and yet another for an
even larger collection of networked machines.
This section describes an implementation targeted
to the computing environment in wide use at Google:
large clusters of commodity PCs connected together with
switched Ethernet [4]. In our environment:
(1) Machines are typically dual-processor x86 processors
running Linux, with 2-4 GB of memory per machine.
(2) Commodity networking hardware is used – typically
either 100 megabits/second or 1 gigabit/second at the
machine level, but averaging considerably less in over-
all bisection bandwidth.
(3) A cluster consists of hundreds or thousands of ma-
chines, and therefore machine failures are common.
(4) Storage is provided by inexpensive IDE disks at-
tached directly to individual machines. A distributed file
system [8] developed in-house is used to manage the data
stored on these disks. The file system uses replication to
provide availability and reliability on top of unreliable
hardware.
(5) Users submit jobs to a scheduling system. Each job
consists of a set of tasks, and is mapped by the scheduler
to a set of available machines within a cluster.
3.1 Execution Overview
The Map invocations are distributed across multiple
machines by automatically partitioning the input data
OSDI ’04: 6th Symposium on Operating Systems Design and ImplementationUSENIX Association 139
into a set of M splits. The input splits can be pro-
cessed in parallel by different machines. Reduce invoca-
tions are distributed by partitioning the intermediate key
space into R pieces using a partitioning function (e.g.,
hash(key) mod R). The number of partitions ( R) and
the partitioning function are specified by the user.
Figure 1 shows the overall flow of a MapReduce op-
eration in our implementation. When the user program
calls the MapReduce function, the following sequence
of actions occurs (the numbered labels in Figure 1 corre-
spond to the numbers in the list below):
1. The MapReduce library in the user program first
splits the input files into M pieces of typically 16
megabytes to 64 megabytes (MB) per piece (con-
trollable by the user via an optional parameter). It
then starts up many copies of the program on a clus-
ter of machines.
2. One of the copies of the program is special – the
master. The rest are workers that are assigned work
by the master. There are M map tasks and R reduce
tasks to assign. The master picks idle workers and
assigns each one a map task or a reduce task.
3. A worker who is assigned a map task reads the
contents of the corresponding input split. It parses
key/value pairs out of the input data and passes each
pair to the user-defined Map function. The interme-
diate key/value pairs produced by the Map function
are buffered in memory.
4. Periodically, the buffered pairs are written to local
disk, partitioned into R regions by the partitioning
function. The locations of these buffered pairs on
the local disk are passed back to the master, who
is responsible for forwarding these locations to the
reduce workers.
5. When a reduce worker is notified by the master
about these locations, it uses remote procedure calls
to read the buffered data from the local disks of the
map workers. When a reduce worker has read all in-
termediate data, it sorts it by the intermediate keys
so that all occurrences of the same key are grouped
together. The sorting is needed because typically
many different keys map to the same reduce task. If
the amount of intermediate data is too large to fit in
memory, an external sort is used.
6. The reduce worker iterates over the sorted interme-
diate data and for each unique intermediate key en-
countered, it passes the key and the corresponding
set of intermediate values to the user’s Reduce func-
tion. The output of the Reduce function is appended
to a final output file for this reduce partition.
7. When all map tasks and reduce tasks have been
completed, the master wakes up the user program.
At this point, the MapReduce call in the user pro-
gram returns back to the user code.
After successful completion, the output of the mapre-
duce execution is available in the R output files (one per
reduce task, with file names as specified by the user).
Typically, users do not need to combine these R output
files into one file – they often pass these files as input to
another MapReduce call, or use them from another dis-
tributed application that is able to deal with input that is
partitioned into multiple files.
3.2 Master Data Structures
The master keeps several data structures. For each map
task and reduce task, it stores the state ( idle, in-progress,
or completed), and the identity of the worker machine
(for non-idle tasks).
The master is the conduit through which the location
of intermediate file regions is propagated from map tasks
to reduce tasks. Therefore, for each completed map task,
the master stores the locations and sizes of the R inter-
mediate file regions produced by the map task. Updates
to this location and size information are received as map
tasks are completed. The information is pushed incre-
mentally to workers that have in-progress reduce tasks.
3.3 Fault T olerance
Since the MapReduce library is designed to help process
very large amounts of data using hundreds or thousands
of machines, the library must tolerate machine failures
gracefully.
Worker Failure
The master pings every worker periodically. If no re-
sponse is received from a worker in a certain amount of
time, the master marks the worker as failed. Any map
tasks completed by the worker are reset back to their ini-
tial idle state, and therefore become eligible for schedul-
ing on other workers. Similarly, any map task or reduce
task in progress on a failed worker is also reset to idle
and becomes eligible for rescheduling.
Completed map tasks are re-executed on a failure be-
cause their output is stored on the local disk(s) of the
failed machine and is therefore inaccessible. Completed
reduce tasks do not need to be re-executed since their
output is stored in a global file system.
When a map task is executed first by worker A and
then later executed by worker B (because A failed), all
OSDI ’04: 6th Symposium on Operating Systems Design and Implementation USENIX Association140
workers executing reduce tasks are notified of the re-
execution. Any reduce task that has not already read the
data from worker A will read the data from worker B.
MapReduce is resilient to large-scale worker failures.
For example, during one MapReduce operation, network
maintenance on a running cluster was causing groups of
80 machines at a time to become unreachable for sev-
eral minutes. The MapReduce master simply re-executed
the work done by the unreachable worker machines, and
continued to make forward progress, eventually complet-
ing the MapReduce operation.
Master Failure
It is easy to make the master write periodic checkpoints
of the master data structures described above. If the mas-
ter task dies, a new copy can be started from the last
checkpointed state. However, given that there is only a
single master, its failure is unlikely; therefore our cur-
rent implementation aborts the MapReduce computation
if the master fails. Clients can check for this condition
and retry the MapReduce operation if they desire.
Semantics in the Presence of Failures
When the user-supplied map and reduce operators are de-
terministic functions of their input values, our distributed
implementation produces the same output as would have
been produced by a non-faulting sequential execution of
the entire program.
We rely on atomic commits of map and reduce task
outputs to achieve this property. Each in-progress task
writes its output to private temporary files. A reduce task
produces one such file, and a map task produces R such
files (one per reduce task). When a map task completes,
the worker sends a message to the master and includes
the names of the R temporary files in the message. If
the master receives a completion message for an already
completed map task, it ignores the message. Otherwise,
it records the names of R files in a master data structure.
When a reduce task completes, the reduce worker
atomically renames its temporary output file to the final
output file. If the same reduce task is executed on multi-
ple machines, multiple rename calls will be executed for
the same final output file. We rely on the atomic rename
operation provided by the underlying file system to guar-
antee that the final file system state contains just the data
produced by one execution of the reduce task.
The vast majority of our map and reduce operators are
deterministic, and the fact that our semantics are equiv-
alent to a sequential execution in this case makes it very
easy for programmers to reason about their program’s be-
havior. When the map and/or reduce operators are non-
deterministic, we provide weaker but still reasonable se-
mantics. In the presence of non-deterministic operators,
the output of a particular reduce task R
1 is equivalent to
the output for R1 produced by a sequential execution of
the non-deterministic program. However, the output for
a different reduce task R2 may correspond to the output
for R2 produced by a different sequential execution of
the non-deterministic program.
Consider map task M and reduce tasks R1 and R2.
Let e(Ri) be the execution of Ri that committed (there
is exactly one such execution). The weaker semantics
arise because e(R1) may have read the output produced
by one execution of M and e(R2) may have read the
output produced by a different execution of M .
3.4 Locality
Network bandwidth is a relatively scarce resource in our
computing environment. We conserve network band-
width by taking advantage of the fact that the input data
(managed by GFS [8]) is stored on the local disks of the
machines that make up our cluster. GFS divides each
file into 64 MB blocks, and stores several copies of each
block (typically 3 copies) on different machines. The
MapReduce master takes the location information of the
input files into account and attempts to schedule a map
task on a machine that contains a replica of the corre-
sponding input data. Failing that, it attempts to schedule
a map task near a replica of that task’s input data (e.g., on
a worker machine that is on the same network switch as
the machine containing the data). When running large
MapReduce operations on a significant fraction of the
workers in a cluster, most input data is read locally and
consumes no network bandwidth.
3.5 T ask Granularity
We subdivide the map phase into M pieces and the re-
duce phase into R pieces, as described above. Ideally, M
and R should be much larger than the number of worker
machines. Having each worker perform many different
tasks improves dynamic load balancing, and also speeds
up recovery when a worker fails: the many map tasks
it has completed can be spread out across all the other
worker machines.
There are practical bounds on how large M and R can
be in our implementation, since the master must make
O(M + R) scheduling decisions and keeps O(M ∗ R)
state in memory as described above. (The constant fac-
tors for memory usage are small however: the O(M ∗ R)
piece of the state consists of approximately one byte of
data per map task/reduce task pair.)
OSDI ’04: 6th Symposium on Operating Systems Design and ImplementationUSENIX Association 141
Furthermore, R is often constrained by users because
the output of each reduce task ends up in a separate out-
put file. In practice, we tend to choose M so that each
individual task is roughly 16 MB to 64 MB of input data
(so that the locality optimization described above is most
effective), and we make R a small multiple of the num-
ber of worker machines we expect to use. We often per-
form MapReduce computations with M = 200 , 000 and
R =5 , 000, using 2,000 worker machines.
3.6 Backup T asks
One of the common causes that lengthens the total time
taken for a MapReduce operation is a “straggler”: a ma-
chine that takes an unusually long time to complete one
of the last few map or reduce tasks in the computation.
Stragglers can arise for a whole host of reasons. For ex-
ample, a machine with a bad disk may experience fre-
quent correctable errors that slow its read performance
from 30 MB/s to 1 MB/s. The cluster scheduling sys-
tem may have scheduled other tasks on the machine,
causing it to execute the MapReduce code more slowly
due to competition for CPU, memory, local disk, or net-
work bandwidth. A recent problem we experienced was
a bug in machine initialization code that caused proces-
sor caches to be disabled: computations on affected ma-
chines slowed down by over a factor of one hundred.
We have a general mechanism to alleviate the prob-
lem of stragglers. When a MapReduce operation is close
to completion, the master schedules backup executions
of the remaining in-progress tasks. The task is marked
as completed whenever either the primary or the backup
execution completes. We have tuned this mechanism so
that it typically increases the computational resources
used by the operation by no more than a few percent.
We have found that this significantly reduces the time
to complete large MapReduce operations. As an exam-
ple, the sort program described in Section 5.3 takes 44%
longer to complete when the backup task mechanism is
disabled.
4 Refinements
Although the basic functionality provided by simply
writing Map and Reduce functions is sufficient for most
needs, we have found a few extensions useful. These are
described in this section.
4.1 Partitioning Function
The users of MapReduce specify the number of reduce
tasks/output files that they desire ( R). Data gets parti-
tioned across these tasks using a partitioning function on
the intermediate key. A default partitioning function is
provided that uses hashing (e.g. “ hash(key) mod R”).
This tends to result in fairly well-balanced partitions. In
some cases, however, it is useful to partition data by
some other function of the key. For example, sometimes
the output keys are URLs, and we want all entries for a
single host to end up in the same output file. To support
situations like this, the user of the MapReduce library
can provide a special partitioning function. For example,
using “hash(Hostname(urlkey )) mod R” as the par-
titioning function causes all URLs from the same host to
end up in the same output file.
4.2 Ordering Guarantees
We guarantee that within a given partition, the interme-
diate key/value pairs are processed in increasing key or-
der. This ordering guarantee makes it easy to generate
a sorted output file per partition, which is useful when
the output file format needs to support efficient random
access lookups by key, or users of the output find it con-
venient to have the data sorted.
4.3 Combiner Function
In some cases, there is significant repetition in the inter-
mediate keys produced by each map task, and the user-
specified Reduce function is commutative and associa-
tive. A good example of this is the word counting exam-
ple in Section 2.1. Since word frequencies tend to follow
a Zipf distribution, each map task will produce hundreds
or thousands of records of the form <the, 1> . All of
these counts will be sent over the network to a single re-
duce task and then added together by the Reduce function
to produce one number. We allow the user to specify an
optional Combiner function that does partial merging of
this data before it is sent over the network.
The Combiner function is executed on each machine
that performs a map task. Typically the same code is used
to implement both the combiner and the reduce func-
tions. The only difference between a reduce function and
a combiner function is how the MapReduce library han-
dles the output of the function. The output of a reduce
function is written to the final output file. The output of
a combiner function is written to an intermediate file that
will be sent to a reduce task.
Partial combining significantly speeds up certain
classes of MapReduce operations. Appendix A contains
an example that uses a combiner.
4.4 Input and Output Types
The MapReduce library provides support for reading in-
put data in several different formats. For example, “text”
OSDI ’04: 6th Symposium on Operating Systems Design and Implementation USENIX Association142
mode input treats each line as a key/value pair: the key
is the offset in the file and the value is the contents of
the line. Another common supported format stores a
sequence of key/value pairs sorted by key. Each input
type implementation knows how to split itself into mean-
ingful ranges for processing as separate map tasks (e.g.
text mode’s range splitting ensures that range splits oc-
cur only at line boundaries). Users can add support for a
new input type by providing an implementation of a sim-
ple reader interface, though most users just use one of a
small number of predefined input types.
A reader does not necessarily need to provide data
read from a file. For example, it is easy to define a reader
that reads records from a database, or from data struc-
tures mapped in memory.
In a similar fashion, we support a set of output types
for producing data in different formats and it is easy for
user code to add support for new output types.
4.5 Side-effects
In some cases, users of MapReduce have found it con-
venient to produce auxiliary files as additional outputs
from their map and/or reduce operators. We rely on the
application writer to make such side-effects atomic and
idempotent. Typically the application writes to a tempo-
rary file and atomically renames this file once it has been
fully generated.
We do not provide support for atomic two-phase com-
mits of multiple output files produced by a single task.
Therefore, tasks that produce multiple output files with
cross-file consistency requirements should be determin-
istic. This restriction has never been an issue in practice.
4.6 Skipping Bad Records
Sometimes there are bugs in user code that cause theMap
or Reduce functions to crash deterministically on certain
records. Such bugs prevent a MapReduce operation from
completing. The usual course of action is to fix the bug,
but sometimes this is not feasible; perhaps the bug is in
a third-party library for which source code is unavail-
able. Also, sometimes it is acceptable to ignore a few
records, for example when doing statistical analysis on
a large data set. We provide an optional mode of execu-
tion where the MapReduce library detects which records
cause deterministic crashes and skips these records in or-
der to make forward progress.
Each worker process installs a signal handler that
catches segmentation violations and bus errors. Before
invoking a user Map or Reduce operation, the MapRe-
duce library stores the sequence number of the argument
in a global variable. If the user code generates a signal,
the signal handler sends a “last gasp” UDP packet that
contains the sequence number to the MapReduce mas-
ter. When the master has seen more than one failure on
a particular record, it indicates that the record should be
skipped when it issues the next re-execution of the corre-
sponding Map or Reduce task.
4.7 Local Execution
Debugging problems in Map or Reduce functions can be
tricky, since the actual computation happens in a dis-
tributed system, often on several thousand machines,
with work assignment decisions made dynamically by
the master. To help facilitate debugging, profiling, and
small-scale testing, we have developed an alternative im-
plementation of the MapReduce library that sequentially
executes all of the work for a MapReduce operation on
the local machine. Controls are provided to the user so
that the computation can be limited to particular map
tasks. Users invoke their program with a special flag and
can then easily use any debugging or testing tools they
find useful (e.g. gdb).
4.8 Status Information
The master runs an internal HTTP server and exports
a set of status pages for human consumption. The sta-
tus pages show the progress of the computation, such as
how many tasks have been completed, how many are in
progress, bytes of input, bytes of intermediate data, bytes
of output, processing rates, etc. The pages also contain
links to the standard error and standard output files gen-
erated by each task. The user can use this data to pre-
dict how long the computation will take, and whether or
not more resources should be added to the computation.
These pages can also be used to figure out when the com-
putation is much slower than expected.
In addition, the top-level status page shows which
workers have failed, and which map and reduce tasks
they were processing when they failed. This informa-
tion is useful when attempting to diagnose bugs in the
user code.
4.9 Counters
The MapReduce library provides a counter facility to
count occurrences of various events. For example, user
code may want to count total number of words processed
or the number of German documents indexed, etc.
To use this facility, user code creates a named counter
object and then increments the counter appropriately in
the Map and/or Reduce function. For example:
OSDI ’04: 6th Symposium on Operating Systems Design and ImplementationUSENIX Association 143
Counter* uppercase;
uppercase = GetCounter("uppercase");
map(String name, String contents):
for each word w in contents:
if (IsCapitalized(w)):
uppercase->Increment();
EmitIntermediate(w, "1");
The counter values from individual worker machines
are periodically propagated to the master (piggybacked
on the ping response). The master aggregates the counter
values from successful map and reduce tasks and returns
them to the user code when the MapReduce operation
is completed. The current counter values are also dis-
played on the master status page so that a human can
watch the progress of the live computation. When aggre-
gating counter values, the master eliminates the effects of
duplicate executions of the same map or reduce task to
avoid double counting. (Duplicate executions can arise
from our use of backup tasks and from re-execution of
tasks due to failures.)
Some counter values are automatically maintained
by the MapReduce library, such as the number of in-
put key/value pairs processed and the number of output
key/value pairs produced.
Users have found the counter facility useful for san-
ity checking the behavior of MapReduce operations. For
example, in some MapReduce operations, the user code
may want to ensure that the number of output pairs
produced exactly equals the number of input pairs pro-
cessed, or that the fraction of German documents pro-
cessed is within some tolerable fraction of the total num-
ber of documents processed.
5 Performance
In this section we measure the performance of MapRe-
duce on two computations running on a large cluster of
machines. One computation searches through approxi-
mately one terabyte of data looking for a particular pat-
tern. The other computation sorts approximately one ter-
abyte of data.
These two programs are representative of a large sub-
set of the real programs written by users of MapReduce –
one class of programs shuffles data from one representa-
tion to another, and another class extracts a small amount
of interesting data from a large data set.
5.1 Cluster Configuration
All of the programs were executed on a cluster that
consisted of approximately 1800 machines. Each ma-
chine had two 2GHz Intel Xeon processors with Hyper-
Threading enabled, 4GB of memory, two 160GB IDE
20 40 60 80 100
Seconds
0
10000
20000
30000Input (MB/s)
Figure 2: Data transfer rate over time
disks, and a gigabit Ethernet link. The machines were
arranged in a two-level tree-shaped switched network
with approximately 100-200 Gbps of aggregate band-
width available at the root. All of the machines were
in the same hosting facility and therefore the round-trip
time between any pair of machines was less than a mil-
lisecond.
Out of the 4GB of memory, approximately 1-1.5GB
was reserved by other tasks running on the cluster. The
programs were executed on a weekend afternoon, when
the CPUs, disks, and network were mostly idle.
5.2 Grep
The grep program scans through 1010 100-byte records,
searching for a relatively rare three-character pattern (the
pattern occurs in 92,337 records). The input is split into
approximately 64MB pieces ( M = 15000 ), and the en-
tire output is placed in one file ( R =1 ).
Figure 2 shows the progress of the computation over
time. The Y -axis shows the rate at which the input data is
scanned. The rate gradually picks up as more machines
are assigned to this MapReduce computation, and peaks
at over 30 GB/s when 1764 workers have been assigned.
As the map tasks finish, the rate starts dropping and hits
zero about 80 seconds into the computation. The entire
computation takes approximately 150 seconds from start
to finish. This includes about a minute of startup over-
head. The overhead is due to the propagation of the pro-
gram to all worker machines, and delays interacting with
GFS to open the set of 1000 input files and to get the
information needed for the locality optimization.
5.3 Sort
The sort program sorts 1010 100-byte records (approxi-
mately 1 terabyte of data). This program is modeled after
the TeraSort benchmark [10].
The sorting program consists of less than 50 lines of
user code. A three-line Map function extracts a 10-byte
sorting key from a text line and emits the key and the
OSDI ’04: 6th Symposium on Operating Systems Design and Implementation USENIX Association144
500 1000
0
5000
10000
15000
20000Input (MB/s)
500 1000
0
5000
10000
15000
20000Shuffle (MB/s)
500 1000
Seconds
0
5000
10000
15000
20000Output (MB/s)
Done
(a) Normal execution
500 1000
0
5000
10000
15000
20000Input (MB/s)
500 1000
0
5000
10000
15000
20000Shuffle (MB/s)
500 1000
Seconds
0
5000
10000
15000
20000Output (MB/s)
Done
(b) No backup tasks
500 1000
0
5000
10000
15000
20000Input (MB/s)
500 1000
0
5000
10000
15000
20000Shuffle (MB/s)
500 1000
Seconds
0
5000
10000
15000
20000Output (MB/s)
Done
(c) 200 tasks killed
Figure 3: Data transfer rates over time for different executions of the sort program
original text line as the intermediate key/value pair. We
used a built-in Identity function as the Reduce operator.
This functions passes the intermediate key/value pair un-
changed as the output key/value pair. The final sorted
output is written to a set of 2-way replicated GFS files
(i.e., 2 terabytes are written as the output of the program).
As before, the input data is split into 64MB pieces
(M = 15000 ). We partition the sorted output into 4000
files (R = 4000 ). The partitioning function uses the ini-
tial bytes of the key to segregate it into one of R pieces.
Our partitioning function for this benchmark has built-
in knowledge of the distribution of keys. In a general
sorting program, we would add a pre-pass MapReduce
operation that would collect a sample of the keys and
use the distribution of the sampled keys to compute split-
points for the final sorting pass.
Figure 3 (a) shows the progress of a normal execution
of the sort program. The top-left graph shows the rate
at which input is read. The rate peaks at about 13 GB/s
and dies off fairly quickly since all map tasks finish be-
fore 200 seconds have elapsed. Note that the input rate
is less than for grep. This is because the sort map tasks
spend about half their time and I/O bandwidth writing in-
termediate output to their local disks. The corresponding
intermediate output for grep had negligible size.
The middle-left graph shows the rate at which data
is sent over the network from the map tasks to the re-
duce tasks. This shuffling starts as soon as the first
map task completes. The first hump in the graph is for
the first batch of approximately 1700 reduce tasks (the
entire MapReduce was assigned about 1700 machines,
and each machine executes at most one reduce task at a
time). Roughly 300 seconds into the computation, some
of these first batch of reduce tasks finish and we start
shuffling data for the remaining reduce tasks. All of the
shuffling is done about 600 seconds into the computation.
The bottom-left graph shows the rate at which sorted
data is written to the final output files by the reduce tasks.
There is a delay between the end of the first shuffling pe-
riod and the start of the writing period because the ma-
chines are busy sorting the intermediate data. The writes
continue at a rate of about 2-4 GB/s for a while. All of
the writes finish about 850 seconds into the computation.
Including startup overhead, the entire computation takes
891 seconds. This is similar to the current best reported
result of 1057 seconds for the TeraSort benchmark [18].
A few things to note: the input rate is higher than the
shuffle rate and the output rate because of our locality
optimization – most data is read from a local disk and
bypasses our relatively bandwidth constrained network.
The shuffle rate is higher than the output rate because
the output phase writes two copies of the sorted data (we
make two replicas of the output for reliability and avail-
ability reasons). We write two replicas because that is
the mechanism for reliability and availability provided
by our underlying file system. Network bandwidth re-
quirements for writing data would be reduced if the un-
derlying file system used erasure coding [14] rather than
replication.
OSDI ’04: 6th Symposium on Operating Systems Design and ImplementationUSENIX Association 145
5.4 Effect of Backup T asks
In Figure 3 (b), we show an execution of the sort pro-
gram with backup tasks disabled. The execution flow is
similar to that shown in Figure 3 (a), except that there is
a very long tail where hardly any write activity occurs.
After 960 seconds, all except 5 of the reduce tasks are
completed. However these last few stragglers don’t fin-
ish until 300 seconds later. The entire computation takes
1283 seconds, an increase of 44% in elapsed time.
5.5 Machine Failures
In Figure 3 (c), we show an execution of the sort program
where we intentionally killed 200 out of 1746 worker
processes several minutes into the computation. The
underlying cluster scheduler immediately restarted new
worker processes on these machines (since only the pro-
cesses were killed, the machines were still functioning
properly).
The worker deaths show up as a negative input rate
since some previously completed map work disappears
(since the corresponding map workers were killed) and
needs to be redone. The re-execution of this map work
happens relatively quickly. The entire computation fin-
ishes in 933 seconds including startup overhead (just an
increase of 5% over the normal execution time).
6 Experience
We wrote the first version of the MapReduce library in
February of 2003, and made significant enhancements to
it in August of 2003, including the locality optimization,
dynamic load balancing of task execution across worker
machines, etc. Since that time, we have been pleasantly
surprised at how broadly applicable the MapReduce li-
brary has been for the kinds of problems we work on.
It has been used across a wide range of domains within
Google, including:
• large-scale machine learning problems,
• clustering problems for the Google News and
Froogle products,
• extraction of data used to produce reports of popular
queries (e.g. Google Zeitgeist),
• extraction of properties of web pages for new exper-
iments and products (e.g. extraction of geographi-
cal locations from a large corpus of web pages for
localized search), and
• large-scale graph computations.
2003/03
2003/06
2003/09
2003/12
2004/03
2004/06
2004/090
200
400
600
800
1000
Number of instances in source tree
Figure 4: MapReduce instances over time
Number of jobs 29,423
Average job completion time 634 secs
Machine days used 79,186 days
Input data read 3,288 TB
Intermediate data produced 758 TB
Output data written 193 TB
Average worker machines per job 157
Average worker deaths per job 1.2
Average map tasks per job 3,351
Average reduce tasks per job 55
Unique map implementations 395
Unique reduce implementations 269
Unique map/reduce combinations 426
Table 1: MapReduce jobs run in August 2004
Figure 4 shows the significant growth in the number of
separate MapReduce programs checked into our primary
source code management system over time, from 0 in
early 2003 to almost 900 separate instances as of late
September 2004. MapReduce has been so successful be-
cause it makes it possible to write a simple program and
run it efficiently on a thousand machines in the course
of half an hour, greatly speeding up the development and
prototyping cycle. Furthermore, it allows programmers
who have no experience with distributed and/or parallel
systems to exploit large amounts of resources easily.
At the end of each job, the MapReduce library logs
statistics about the computational resources used by the
job. In Table 1, we show some statistics for a subset of
MapReduce jobs run at Google in August 2004.
6.1 Large-Scale Indexing
One of our most significant uses of MapReduce to date
has been a complete rewrite of the production index-
OSDI ’04: 6th Symposium on Operating Systems Design and Implementation USENIX Association146
ing system that produces the data structures used for the
Google web search service. The indexing system takes
as input a large set of documents that have been retrieved
by our crawling system, stored as a set of GFS files. The
raw contents for these documents are more than 20 ter-
abytes of data. The indexing process runs as a sequence
of five to ten MapReduce operations. Using MapReduce
(instead of the ad-hoc distributed passes in the prior ver-
sion of the indexing system) has provided several bene-
fits:
• The indexing code is simpler, smaller, and easier to
understand, because the code that deals with fault
tolerance, distribution and parallelization is hidden
within the MapReduce library. For example, the
size of one phase of the computation dropped from
approximately 3800 lines of C++ code to approx-
imately 700 lines when expressed using MapRe-
duce.
• The performance of the MapReduce library is good
enough that we can keep conceptually unrelated
computations separate, instead of mixing them to-
gether to avoid extra passes over the data. This
makes it easy to change the indexing process. For
example, one change that took a few months to
make in our old indexing system took only a few
days to implement in the new system.
• The indexing process has become much easier to
operate, because most of the problems caused by
machine failures, slow machines, and networking
hiccups are dealt with automatically by the MapRe-
duce library without operator intervention. Further-
more, it is easy to improve the performance of the
indexing process by adding new machines to the in-
dexing cluster.
7 Related Work
Many systems have provided restricted programming
models and used the restrictions to parallelize the com-
putation automatically. For example, an associative func-
tion can be computed over all prefixes of an N element
array in log N time on N processors using parallel prefix
computations [6, 9, 13]. MapReduce can be considered
a simplification and distillation of some of these models
based on our experience with large real-world compu-
tations. More significantly, we provide a fault-tolerant
implementation that scales to thousands of processors.
In contrast, most of the parallel processing systems have
only been implemented on smaller scales and leave the
details of handling machine failures to the programmer.
Bulk Synchronous Programming [17] and some MPI
primitives [11] provide higher-level abstractions that
make it easier for programmers to write parallel pro-
grams. A key difference between these systems and
MapReduce is that MapReduce exploits a restricted pro-
gramming model to parallelize the user program auto-
matically and to provide transparent fault-tolerance.
Our locality optimization draws its inspiration from
techniques such as active disks [12, 15], where compu-
tation is pushed into processing elements that are close
to local disks, to reduce the amount of data sent across
I/O subsystems or the network. We run on commodity
processors to which a small number of disks are directly
connected instead of running directly on disk controller
processors, but the general approach is similar.
Our backup task mechanism is similar to the eager
scheduling mechanism employed in the Charlotte Sys-
tem [3]. One of the shortcomings of simple eager
scheduling is that if a given task causes repeated failures,
the entire computation fails to complete. We fix some in-
stances of this problem with our mechanism for skipping
bad records.
The MapReduce implementation relies on an in-house
cluster management system that is responsible for dis-
tributing and running user tasks on a large collection of
shared machines. Though not the focus of this paper, the
cluster management system is similar in spirit to other
systems such as Condor [16].
The sorting facility that is a part of the MapReduce
library is similar in operation to NOW-Sort [1]. Source
machines (map workers) partition the data to be sorted
and send it to one of R reduce workers. Each reduce
worker sorts its data locally (in memory if possible). Of
course NOW-Sort does not have the user-definable Map
and Reduce functions that make our library widely appli-
cable.
River [2] provides a programming model where pro-
cesses communicate with each other by sending data
over distributed queues. Like MapReduce, the River
system tries to provide good average case performance
even in the presence of non-uniformities introduced by
heterogeneous hardware or system perturbations. River
achieves this by careful scheduling of disk and network
transfers to achieve balanced completion times. MapRe-
duce has a different approach. By restricting the pro-
gramming model, the MapReduce framework is able
to partition the problem into a large number of fine-
grained tasks. These tasks are dynamically scheduled
on available workers so that faster workers process more
tasks. The restricted programming model also allows
us to schedule redundant executions of tasks near the
end of the job which greatly reduces completion time in
the presence of non-uniformities (such as slow or stuck
workers).
BAD-FS [5] has a very different programming model
from MapReduce, and unlike MapReduce, is targeted to
OSDI ’04: 6th Symposium on Operating Systems Design and ImplementationUSENIX Association 147
the execution of jobs across a wide-area network. How-
ever, there are two fundamental similarities. (1) Both
systems use redundant execution to recover from data
loss caused by failures. (2) Both use locality-aware
scheduling to reduce the amount of data sent across con-
gested network links.
TACC [7] is a system designed to simplify con-
struction of highly-available networked services. Like
MapReduce, it relies on re-execution as a mechanism for
implementing fault-tolerance.
8 Conclusions
The MapReduce programming model has been success-
fully used at Google for many different purposes. We
attribute this success to several reasons. First, the model
is easy to use, even for programmers without experience
with parallel and distributed systems, since it hides the
details of parallelization, fault-tolerance, locality opti-
mization, and load balancing. Second, a large variety
of problems are easily expressible as MapReduce com-
putations. For example, MapReduce is used for the gen-
eration of data for Google’s production web search ser-
vice, for sorting, for data mining, for machine learning,
and many other systems. Third, we have developed an
implementation of MapReduce that scales to large clus-
ters of machines comprising thousands of machines. The
implementation makes efficient use of these machine re-
sources and therefore is suitable for use on many of the
large computational problems encountered at Google.
We have learned several things from this work. First,
restricting the programming model makes it easy to par-
allelize and distribute computations and to make such
computations fault-tolerant. Second, network bandwidth
is a scarce resource. A number of optimizations in our
system are therefore targeted at reducing the amount of
data sent across the network: the locality optimization al-
lows us to read data from local disks, and writing a single
copy of the intermediate data to local disk saves network
bandwidth. Third, redundant execution can be used to
reduce the impact of slow machines, and to handle ma-
chine failures and data loss.
Acknowledgements
Josh Levenberg has been instrumental in revising and
extending the user-level MapReduce API with a num-
ber of new features based on his experience with using
MapReduce and other people’s suggestions for enhance-
ments. MapReduce reads its input from and writes its
output to the Google File System [8]. We would like to
thank Mohit Aron, Howard Gobioff, Markus Gutschke,
David Kramer, Shun-Tak Leung, and Josh Redstone for
their work in developing GFS. We would also like to
thank Percy Liang and Olcan Sercinoglu for their work
in developing the cluster management system used by
MapReduce. Mike Burrows, Wilson Hsieh, Josh Leven-
berg, Sharon Perl, Rob Pike, and Debby Wallach pro-
vided helpful comments on earlier drafts of this pa-
per. The anonymous OSDI reviewers, and our shepherd,
Eric Brewer, provided many useful suggestions of areas
where the paper could be improved. Finally, we thank all
the users of MapReduce within Google’s engineering or-
ganization for providing helpful feedback, suggestions,
and bug reports.
References
[1] Andrea C. Arpaci-Dusseau, Remzi H. Arpaci-Dusseau,
David E. Culler, Joseph M. Hellerstein, and David A. Pat-
terson. High-performance sorting on networks of work-
stations. In Proceedings of the 1997 ACM SIGMOD In-
ternational Conference on Management of Data , Tucson,
Arizona, May 1997.
[2] Remzi H. Arpaci-Dusseau, Eric Anderson, Noah
Treuhaft, David E. Culler, Joseph M. Hellerstein, David
Patterson, and Kathy Yelick. Cluster I/O with River:
Making the fast case common. In Proceedings of the Sixth
W orkshop on Input/Output in Parallel and Distributed
Systems (IOPADS ’99) , pages 10–22, Atlanta, Georgia,
May 1999.
[3] Arash Baratloo, Mehmet Karaul, Zvi Kedem, and Peter
Wyckoff. Charlotte: Metacomputing on the web. In Pro-
ceedings of the 9th International Conference on Parallel
and Distributed Computing Systems , 1996.
[4] Luiz A. Barroso, Jeffrey Dean, and Urs H¨ olzle. Web
search for a planet: The Google cluster architecture. IEEE
Micro, 23(2):22–28, April 2003.
[5] John Bent, Douglas Thain, Andrea C.Arpaci-Dusseau,
Remzi H. Arpaci-Dusseau, and Miron Livny. Explicit
control in a batch-aware distributed file system. In Pro-
ceedings of the 1st USENIX Symposium on Networked
Systems Design and Implementation NSDI , March 2004.
[6] Guy E. Blelloch. Scans as primitive parallel operations.
IEEE Transactions on Computers , C-38(11), November
1989.
[7] Armando Fox, Steven D. Gribble, Yatin Chawathe,
Eric A. Brewer, and Paul Gauthier. Cluster-based scal-
able network services. In Proceedings of the 16th ACM
Symposium on Operating System Principles , pages 78–
91, Saint-Malo, France, 1997.
[8] Sanjay Ghemawat, Howard Gobioff, and Shun-Tak Le-
ung. The Google file system. In 19th Symposium on Op-
erating Systems Principles , pages 29–43, Lake George,
New Y ork, 2003.
OSDI ’04: 6th Symposium on Operating Systems Design and Implementation USENIX Association148
[9] S. Gorlatch. Systematic efficient parallelization of scan
and other list homomorphisms. In L. Bouge, P . Fraigni-
aud, A. Mignotte, and Y . Robert, editors, Euro-Par’96.
Parallel Processing, Lecture Notes in Computer Science
1124, pages 401–408. Springer-V erlag, 1996.
[10] Jim Gray. Sort benchmark home page.
http://research.microsoft.com/barc/SortBenchmark/.
[11] William Gropp, Ewing Lusk, and Anthony Skjellum.
Using MPI: Portable Parallel Programming with the
Message-Passing Interface. MIT Press, Cambridge, MA,
1999.
[12] L. Huston, R. Sukthankar, R. Wickremesinghe, M. Satya-
narayanan, G. R. Ganger, E. Riedel, and A. Ailamaki. Di-
amond: A storage architecture for early discard in inter-
active search. In Proceedings of the 2004 USENIX File
and Storage Technologies F AST Conference, April 2004.
[13] Richard E. Ladner and Michael J. Fischer. Parallel prefix
computation. Journal of the ACM, 27(4):831–838, 1980.
[14] Michael O. Rabin. Efficient dispersal of information for
security, load balancing and fault tolerance. Journal of
the ACM, 36(2):335–348, 1989.
[15] Erik Riedel, Christos Faloutsos, Garth A. Gibson, and
David Nagle. Active disks for large-scale data process-
ing. IEEE Computer, pages 68–74, June 2001.
[16] Douglas Thain, Todd Tannenbaum, and Miron Livny.
Distributed computing in practice: The Condor experi-
ence. Concurrency and Computation: Practice and Ex-
perience, 2004.
[17] L. G. V aliant. A bridging model for parallel computation.
Communications of the ACM , 33(8):103–111, 1997.
[18] Jim Wyllie. Spsort: How to sort a terabyte quickly.
http://alme1.almaden.ibm.com/cs/spsort.pdf.
A Word Frequency
This section contains a program that counts the number
of occurrences of each unique word in a set of input files
specified on the command line.
#include "mapreduce/mapreduce.h"
// User’s map function
class WordCounter : public Mapper {
public:
virtual void Map(const MapInput& input) {
const string& text = input.value();
const int n = text.size();
for (int i = 0; i < n; ) {
// Skip past leading whitespace
while ((i < n) && isspace(text[i]))
i++;
// Find word end
int start = i;
while ((i < n) && !isspace(text[i]))
i++;
if (start < i)
Emit(text.substr(start,i-start),"1");
}
}
};
REGISTER_MAPPER(WordCounter);
// User’s reduce function
class Adder : public Reducer {
virtual void Reduce(ReduceInput* input) {
// Iterate over all entries with the
// same key and add the values
int64 value = 0;
while (!input->done()) {
value += StringToInt(input->value());
input->NextValue();
}
// Emit sum for input->key()
Emit(IntToString(value));
}
};
REGISTER_REDUCER(Adder);
int main(int argc, char** argv) {
ParseCommandLineFlags(argc, argv);
MapReduceSpecification spec;
// Store list of input files into "spec"
for (int i = 1; i < argc; i++) {
MapReduceInput* input = spec.add_input();
input->set_format("text");
input->set_filepattern(argv[i]);
input->set_mapper_class("WordCounter");
}
// Specify the output files:
// /gfs/test/freq-00000-of-00100
// /gfs/test/freq-00001-of-00100
// ...
MapReduceOutput* out = spec.output();
out->set_filebase("/gfs/test/freq");
out->set_num_tasks(100);
out->set_format("text");
out->set_reducer_class("Adder");
// Optional: do partial sums within map
// tasks to save network bandwidth
out->set_combiner_class("Adder");
// Tuning parameters: use at most 2000
// machines and 100 MB of memory per task
spec.set_machines(2000);
spec.set_map_megabytes(100);
spec.set_reduce_megabytes(100);
// Now run it
MapReduceResult result;
if (!MapReduce(spec, &result)) abort();
// Done: ’result’ structure contains info
// about counters, time taken, number of
// machines used, etc.
return 0;
}
OSDI ’04: 6th Symposium on Operating Systems Design and ImplementationUSENIX Association 149