AAI Agentic Handbook
Problem 99 · Data Engineering & Streaming

Distributed Group-By with Partial Aggregates

MediumClassic DSA & systems
01Problem

Compute per-key count, sum, min, max and avg over rows spread across partitions using a map-side combine, a hash shuffle to R reducers, and a final reduce.

02Key insight

Only algebraic aggregates can be combined early: AVG is carried as (sum, count) and finalized at the end. Map-side combining shrinks shuffle volume from rows to distinct keys per partition; the merge function must be associative and commutative so partial order doesn't matter. Use a stable hash for partitioning (Python's hash() is salted per process).

03Solution

Try it first.

TimeO(n) total; shuffle O(partitions * distinct keys)
SpaceO(distinct keys per partition)
tests.py · 2 passing
tests.pypython10 lines
import random
rng = random.Random(5)
rows = [{"region": rng.choice("ABCD"), "amt": rng.randint(1, 100)} for _ in range(2000)]
parts = [rows[i::4] for i in range(4)]
res = distributed_group_by(parts, "region", "amt")
for r in "ABCD":
    vals = [x["amt"] for x in rows if x["region"] == r]
    assert res[r] == {"count": len(vals), "sum": sum(vals), "min": min(vals),
                      "max": max(vals), "avg": sum(vals) / len(vals)}
assert distributed_group_by([[], []], "region", "amt") == {}
04Staff-level follow-up

What about COUNT(DISTINCT) or MEDIAN, which aren't algebraic? Either shuffle raw values (expensive) or use mergeable sketches - HLL for distinct count, t-digest/KLL for quantiles - as the partial aggregate.