Skip to content
LeetQuant
QD07 Databases, Pipelines and Distributed Systems

QD07 · Databases, Pipelines and Distributed Systems · Lesson 4 of 5

Distributed Processing

Split data across machines with hash and range partitioning, follow a job through map, shuffle and reduce, diagnose and fix key skew, and explain why columnar formats such as Parquet make analytical queries far cheaper.

17 min

Objective

Ten years of tick data does not fit on one machine, and scanning it on one machine would take days. Distributed processing splits the data and the work across many machines. The interview topics are how data is split (partitioning), how a computation that needs data from everywhere is organised (map, shuffle, reduce), why one machine often ends up doing most of the work (skew), and why storage layout (columnar files) often matters more than cluster size. By the end of this lesson you should be able to estimate the cost of a job from these pieces.

Partitioning and sharding

Partitioning splits a dataset into pieces; sharding is the same idea for a live database, with each shard on a different server. The choice of partition key decides which queries are cheap.

  • Hash partitioning: partition =h(key) mod N= h(\text{key}) \bmod N. Spreads keys evenly and makes "all rows for symbol X" a single-partition lookup. Range queries over the key touch every partition.
  • Range partitioning: contiguous key ranges (dates, or symbols A to F). Makes range scans cheap ("all of March") and allows pruning. Prone to hot spots: today's date partition receives every write.
  • Composite: a common layout for market data is date ranges at the top level (files per day) and symbol within each day, sorted by (symbol, ts).

Use a hash function that is stable across processes. Python's built-in hash() on strings is randomised per process (PYTHONHASHSEED), so two workers would disagree about where a key lives; use zlib.crc32 or a cryptographic hash.

Resharding. With h mod Nh \bmod N, changing NN moves almost every key: for a key to stay put from 10 to 11 shards it needs h mod 10=h mod 11h \bmod 10 = h \bmod 11, which holds for 10 of every 110 residues, so 10/11≈91%10/11 \approx 91\% of keys move (a simulation over 100,000 keys gives 90.9%). Consistent hashing places nodes and keys on a ring and assigns each key to the next node clockwise; adding the 11th node moves only the keys it takes over, about 1/11≈9%1/11 \approx 9\% (9.4% in the same simulation with 200 virtual points per node). That is why distributed key-value stores use it.

Map, shuffle, reduce

A distributed aggregation such as "VWAP per symbol" runs in three phases:

  1. Map: each worker reads its input split and emits (key, value) pairs, here (symbol, (price * qty, qty)).
  2. Shuffle: pairs are routed over the network so that all values for a key reach the same reducer, by partition(key). This is the expensive step: it writes to disk, crosses the network and is where most jobs spend their time.
  3. Reduce: each reducer combines the values for its keys.

A combiner (map-side pre-aggregation) runs the reduce logic inside each mapper first, so each mapper sends one partial result per key instead of one record per trade. It works whenever the reduction is associative and commutative: sums, counts, min, max, and anything built from them, such as VWAP as (sum of notional, sum of quantity). It does not work for an exact median.

from collections import defaultdict
from zlib import crc32

# Trades as they sit on three input splits (one per mapper).
splits = [
    [("AAA", 100.0, 200), ("BBB", 50.0, 500), ("AAA", 101.0, 100)],
    [("DDD", 20.0, 1000), ("AAA", 102.0, 300)],
    [("BBB", 51.0, 500), ("DDD", 21.0, 1000), ("AAA", 99.0, 400)],
]
R = 2  # reducers

def mapper(split):
    # Map + combine: pre-aggregate inside the split before sending.
    partial = defaultdict(lambda: [0.0, 0])
    for sym, px, qty in split:
        partial[sym][0] += px * qty
        partial[sym][1] += qty
    return partial.items()

def partition(key: str) -> int:
    return crc32(key.encode()) % R   # stable across processes, unlike hash()

shuffle = [defaultdict(list) for _ in range(R)]
sent = 0
for split in splits:
    for sym, (notional, qty) in mapper(split):
        shuffle[partition(sym)][sym].append((notional, qty))
        sent += 1

for r in range(R):
    for sym, parts in sorted(shuffle[r].items()):
        notional = sum(n for n, _ in parts)
        qty = sum(q for _, q in parts)
        print(f"reducer {r}: {sym} vwap={notional / qty:.4f} qty={qty}")
print("records shuffled:", sent, "of", sum(len(s) for s in splits), "trades")
reducer 0: DDD vwap=20.5000 qty=2000
reducer 1: AAA vwap=100.3000 qty=1000
reducer 1: BBB vwap=50.5000 qty=1000
records shuffled: 7 of 8 trades

On toy data the combiner saves one record; on real data, where each split holds millions of trades for a few thousand symbols, it shrinks the shuffle by orders of magnitude. Note also that reducer 1 got two of the three keys: with few keys, hashing is lumpy.

Joins shuffle too: both tables are repartitioned by the join key. If one side is small (a symbol reference table), a broadcast join copies it to every worker and avoids shuffling the large side at all.

Skew

A distributed job finishes when its slowest task finishes. If one key holds a large share of the rows, the reducer that owns it does that share of the work alone, however many reducers you have. In market data, skew is the norm: a few index ETFs and mega-caps account for a large fraction of all trades, and one day (an index rebalance, a crash) can carry several times the normal volume.

Fixes:

  • Combiners first: if the reduction is associative, skew in raw records mostly disappears after map-side aggregation.
  • Salting: split a hot key into kk sub-keys, (symbol, random(0..k-1)), aggregate those in parallel, then combine the kk partials per symbol in a second, tiny step.
  • Broadcast the small side of a join so the hot key never shuffles.
  • Finer partitioning of the hot range (split one date into hourly files).

Columnar formats

Row-oriented storage (CSV, a row-store database page) keeps all the fields of one record together. Analytical queries usually read a few columns of many rows: "average spread for AAA in March" needs 3 of perhaps 50 columns. Columnar formats (Parquet, ORC, Arrow in memory, the storage inside kdb+, ClickHouse, DuckDB and most cloud warehouses) store each column contiguously, which gives:

  1. Column pruning: read only the columns the query names.
  2. Better compression: a column holds values of one type that change slowly (sorted symbols, increasing timestamps, prices near each other), which suits dictionary, run-length and delta encodings followed by a general compressor.
  3. Predicate pushdown: a Parquet file is divided into row groups, and each column chunk stores min/max statistics. A reader evaluating symbol = 'AAA' skips any row group whose min/max range for symbol excludes AAA, without decompressing it. This only helps if the data is sorted or clustered by that column; if every row group contains every symbol, every range includes AAA and nothing is skipped.
  4. Vectorised execution: operating on a batch of one column at a time is cache-friendly and SIMD-friendly.

The costs: updating a single record means rewriting a file, so columnar files suit append-and-read analytics, not transactional updates; and very many small files destroy the benefits (each file has fixed overhead and too little data to compress or skip), so streaming writers compact small files periodically.

Partitioned directories (date=2024-03-01/part-0.parquet) add partition pruning on top: a filter on date never opens other days' files.

Worked example

how much does a skewed key cost?

A job aggregates 1 billion trades with 200 reducers and no combiner. One symbol accounts for 3% of trades; the rest are spread evenly. Roughly how much slower is the job than a perfectly balanced one, and what does salting the hot key into 20 sub-keys achieve?

Show solution

Step 1: balanced baseline. 109/200=510^9 / 200 = 5 million records per reducer.

Step 2: skewed load. The hot symbol is 0.03×109=300.03 \times 10^9 = 30 million records on one reducer. The other 970 million spread over 200 reducers add about 970/200=4.85970 / 200 = 4.85 million per reducer, so the hot reducer has about 34.8534.85 million, roughly 7×7\times the balanced load. The job's time is set by that reducer, so it runs about 7×7\times slower than it should, while 199 reducers sit idle for most of it. Adding reducers barely helps: with 400 reducers the hot one still has over 32 million.

Step 3: salting. Twenty sub-keys of 1.51.5 million each land on (up to) 20 different reducers, each also carrying about 4.854.85 million, so the maximum load is about 6.356.35 million, 1.27×1.27\times the balanced load. The second stage combines 20 partial results for one symbol, which is negligible.

Step 4: say the cheaper fix. For a sum-like aggregation, a combiner solves this without salting: each mapper sends one partial per symbol, so the hot reducer receives one record per mapper. Salting is for reductions that cannot be pre-aggregated in the mapper, or for joins on a hot key.

Worked example

bytes read, row store versus Parquet

A trades table has 100 million rows per year, 250 trading days, and 50 columns averaging 8 bytes each. A query asks for the average price of one symbol on one day, reading symbol, price and the date. Compare bytes read for (a) an unpartitioned row-oriented file, (b) the same rows partitioned by date, (c) date-partitioned Parquet reading 2 columns with 4:1 compression, and (d) as (c) with each day sorted by symbol so row-group statistics skip all but 1% of the day.

Show solution

(a) Full scan: 108×50×8=4×101010^8 \times 50 \times 8 = 4 \times 10^{10} bytes, 40 GB.

(b) Partition pruning reads one day: 40 GB/250=16040 \text{ GB} / 250 = 160 MB.

(c) Column pruning: the date is the partition directory, so only symbol and price are read, 2/502/50 of the bytes: 160×2/50=6.4160 \times 2/50 = 6.4 MB uncompressed, and 6.4/4=1.66.4 / 4 = 1.6 MB on disk.

(d) Predicate pushdown on the sorted symbol column: 1.6×0.01=161.6 \times 0.01 = 16 kB, plus the file footer and statistics.

The chain is 40 GB to 160 MB (partitioning, 250×250\times) to 1.6 MB (columns and compression, 100×100\times) to about 16 kB (sorting plus statistics, 100×100\times). None of it needed more machines. In an interview, this is the answer to "the query is slow, should we add nodes?": first check layout, partitioning and sort order.

Knowledge check

A Spark job computing per-symbol statistics has 199 tasks finishing in 2 minutes and one running for 40 minutes. What is the most likely cause and first fix?

Knowledge check

A Parquet dataset of one day's trades is written in arrival order, so every row group contains every symbol. How much does row-group min/max pushdown help a query with WHERE symbol = 'AAA'?

Knowledge check

A cache is sharded over 10 servers by hash(key) mod 10. One server is added. Roughly what fraction of keys now map to a different server, and what reduces it?

Key takeaways

  • Hash partitioning spreads load and makes key lookups cheap; range partitioning makes range scans and pruning cheap but creates hot spots. Use a hash that is stable across processes.
  • Modulo resharding moves about N/(N+1)N/(N+1) of keys; consistent hashing moves about 1/(N+1)1/(N+1).
  • The shuffle is the expensive phase. Combiners (for associative reductions) and broadcast joins avoid most of it.
  • Jobs run at the speed of the slowest task. Skewed keys need pre-aggregation, salting or finer partitioning, not more machines.
  • Columnar formats win on analytics through column pruning, compression, row-group statistics and vectorised execution; statistics only help on sorted or clustered data.
  • Before scaling out, fix layout: partition by date, sort by (symbol, ts), read only needed columns, compact small files.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).