Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Parallel information retrieval and MapReduce

How to scale indexing and querying across machines using MapReduce-style parallelism, plus the key laws (Amdahl) and a runnable Python MapReduce word-count example.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Parallel information retrieval is how modern search engines and large-scale IR systems process and index massive text collections and answer queries quickly. Engineers use these techniques to split work across many machines for speed, to exploit data locality, and to tolerate failures in production search systems.

Key ideas

  • Exact definition (signature style used in exams): map takes a (key, value) input and emits zero or more intermediate (key, value) pairs. reduce takes a key and the list of all values associated with that key and emits zero or more final (key, value) pairs. Assume deterministic functions and that intermediate keys are groupable by equality.

  • Typical execution flow to draw (diagram description): draw three vertical columns labelled "Input → Mappers → Shuffle & Sort → Reducers → Output". On the left draw a box labelled "Input splits" feeding into multiple boxes labelled "Map tasks (workers)". From each map box draw arrows to local disks (label "map output, partitioned by key") then arrows from map output to reducer boxes in the middle labelled "Shuffle". Finally draw reducer boxes writing to distributed output. Add a separate small box labelled "Master/JobTracker" connected to workers for task assignment; mark worker failure with a cross and show the master reassigning that task.

  • Data locality: placing computation on the same node that stores input data reduces network I/O. In exam answers state: "Prefer scheduling map tasks on nodes that hold the input split to reduce network transfer and increase throughput." Assume replicated input blocks (e.g., HDFS) so a scheduler can choose local copies.

  • Partitioner and combiners: a partitioner decides which reducer receives which intermediate keys (often hash(key) mod R). A combiner is an optional mini-reducer executed on map output to reduce data sent across the network (works when the reduce operation is associative and commutative, e.g., sum). Combiner execution is not guaranteed; job correctness must not depend on the combiner running.

  • Fault tolerance: MapReduce systems assume worker failures and handle them by re-running failed map or reduce tasks on other nodes. The correctness assumption: map and reduce functions are side-effect-free so re-running is safe. Systems may also use speculative execution to mitigate stragglers (slow-running tasks).

  • Performance model — Amdahl's law: If a fraction f of the work is perfectly parallelizable and the rest (1 − f) is serial, then with p processors the maximum speedup S is given by Amdahl's formula (derivation below). Assumptions: overheads (communication, scheduling, synchronization) are ignored in the basic formula. Also know Gustafson–Barsis law for scaled speedup: S_G(p) = p − (1 − f)(p − 1), which assumes problem size scales with p.

    • Derivation (step-by-step, as expected in exams):
      1. Let the total time on one processor be T1 = Ts + Tp where Ts is serial part and Tp is parallel part.
      2. With p processors, serial part still takes Ts, parallel part ideally takes Tp/p.
      3. So Tp = f·T1 and Ts = (1 − f)·T1. Time on p processors T(p) = Ts + (Tp/p) = (1 − f)T1 + (fT1)/p.
      4. Speedup S = T1 / T(p) = 1 / ((1 − f) + f/p). This is the Amdahl formula. Note the limit as p → ∞ is 1/(1 − f) meaning the serial fraction bounds maximum speedup.
  • Shuffle cost: after map tasks, intermediate pairs are partitioned and transferred to reducers. If M total intermediate pairs and network bandwidth B, naive transfer time is approximately M/B (ignoring protocol overheads) plus sorting cost at reducers (if reducers sort keys, cost per reducer ~ O(m_r log m_r) where m_r is that reducer's records). In practice, combiners and partitioning reduce M.

  • When to use MapReduce in IR: large-scale batch tasks that are easily decomposed by documents or terms: building inverted indices from a web crawl, computing document statistics (DF, TF), re-ranking with large models, offline training. For low-latency query processing, prefer distributed query-serving architectures not batch MapReduce.

Formulas

map: (k_in, v_in) -> [(k_int, v_int), ...] — map function signature; k_in, v_in are input key and value (no SI unit); applies in MapReduce jobs.

reduce: (k_int, [v_int]) -> [(k_out, v_out), ...] — reduce function signature; takes a key and list of its values.

Amdahl: S(p) = 1 / ((1 - f) + f / p) — S(p) is the speedup with p processors (dimensionless); f is fraction of work parallelizable (0 ≤ f ≤ 1); p is number of processors (integer). Applies when overheads and communication are ignored.

T(p) = T1 * ((1 - f) + f / p) — time with p processors in seconds if T1 is single-processor time in seconds; same symbols as above.

partition(key) = hash(key) mod R — typical partitioner formula where R is number of reducers; hash returns integer. Applies to assign intermediate keys to reducers.

Note: When implementing MapReduce in code, remember to include shuffle (group-by-key) between map and reduce phases and optionally a combiner step.

Worked examples

  1. Amdahl's-law numerical example (exam-style):

    • Problem: A data-processing job takes 1000 s on one machine. 90% of the job (f = 0.9) can be parallelized perfectly. Compute time and speedup with p = 10 processors.
    • Formula: T(p) = T1 * ((1 - f) + f / p) and S = T1 / T(p).
    • Numbers: T1 = 1000 s, f = 0.9, p = 10.
    • Compute T(10) = 1000 * ((1 - 0.9) + 0.9 / 10) = 1000 * (0.1 + 0.09) = 1000 * 0.19 = 190 s.
    • Speedup S = 1000 / 190 = 5.263157... ≈ 5.26.
    • Final answers: T(10) = 190 s, Speedup ≈ 5.26.
  2. Runnable Python MapReduce (word count) — single-file parallel map/reduce using multiprocessing. This is a minimal educational framework that runs on one machine but demonstrates the map → shuffle → reduce steps.

# mapreduce_wordcount.py
import re
from multiprocessing import Pool
from collections import defaultdict

# mapper: process a chunk of lines
def map_chunk(lines):
    out = []
    for line in lines:
        for w in re.findall(r"\w+", line.lower()):
            out.append((w, 1))
    return out

# reducer: sum counts for a single key
def reduce_key(item):
    k, values = item
    return (k, sum(values))

# simple driver
def simple_mapreduce(lines, num_workers=2):
    # split lines into nearly equal chunks
    n = len(lines)
    chunk_size = (n + num_workers - 1) // num_workers
    chunks = [lines[i:i+chunk_size] for i in range(0, n, chunk_size)]

    with Pool(num_workers) as p:
        map_outputs = p.map(map_chunk, chunks)

    # shuffle: group by key
    groups = defaultdict(list)
    for mo in map_outputs:
        for k, v in mo:
            groups[k].append(v)

    # reduce (can also be parallelized)
    items = list(groups.items())
    with Pool(num_workers) as p:
        reduced = p.map(reduce_key, items)

    # return sorted results
    return sorted(reduced)

if __name__ == '__main__':
    sample = [
        "Dog cat dog",
        "cat mouse",
        "dog."
    ]
    result = simple_mapreduce(sample, num_workers=2)
    for k, v in result:
        print(f"{k}\t{v}")

Sample input (the program reads the sample list in code). Exact output when run with Python 3.8+ on a typical system:

cat 2

dog 3

mouse 1

(Each key printed on its own line with a tab then the count; exact ordering shown here is alphabetical by key.)

  1. MapReduce for inverted index (model answer outline, exam theory):
    • Map step: for each (docID, text) input, for each token t in text emit (t, docID:tf) or (t, docID, tf) after counting tokens per document (you may use a combiner to emit (t, docID:tf)).
    • Reduce step: for each token t, gather list of docID:tf pairs and write posting list for t (optionally sorted by docID). State assumptions: tokens are preprocessed (tokenized, stemmed) before map.

Common mistakes

  • Using a combiner when the reduction is not associative/commutative (e.g., order-dependent operations). This can give incorrect results.
  • Ignoring data-locality and assuming network is free — leads to wrong performance expectations.
  • Misapplying Amdahl's law without accounting for parallel overheads (communication, synchronization); students quote unrealistic speedups.
  • In code answers, not sorting or deterministically grouping keys when the exam expects deterministic output order.

For your exam

Types of questions you will see:

  • Definitions: define MapReduce, map, reduce, partitioner, combiner, data locality, shuffle.
  • Short notes: describe MapReduce execution pipeline (draw and label diagram), explain fault tolerance, explain use-cases in IR (indexing, DF computation).
  • Derivations: derive Amdahl's law step-by-step and compute numerical examples.
  • Numericals: compute speedup or time with given f, p, T1; compute amount of network traffic given intermediate pair counts and combiner savings.
  • Programs: write map and reduce functions for word count or inverted index; or explain how to implement a combiner.

What a full-marks answer must include:

  • Precise definitions of map and reduce with their signatures.
  • A correctly labelled diagram of the MapReduce pipeline (input splits, mapper, local disk, shuffle, reducer, master scheduler).
  • In derivations, show the decomposition of T1 into serial and parallel parts and each algebra step for Amdahl.
  • For program answers, include how data is partitioned, how keys are grouped (shuffle), and how reducers aggregate.

Quick check

  1. State the MapReduce map function signature in one line.
  2. If f = 0.6 and p = 4, what is Amdahl speedup S(p)?
  3. Name two reasons MapReduce jobs are preferred for batch IR tasks but not for low-latency query serving.

Answers: 1) map: (k_in, v_in) -> [(k_int, v_int), ...] ; 2) S = 1 / ((1 - 0.6) + 0.6/4) = 1 / (0.4 + 0.15) = 1 / 0.55 ≈ 1.818 ; 3) Because MapReduce offers (a) easy scaling for large, embarrassingly parallel batch jobs and (b) fault tolerance and simple programming model — but it has high startup, shuffle, and batch latency making it unsuitable for low-latency query answering.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?