小王算钱

Interview Prep · Data Infra

Big-Data Processing Engines
From MapReduce to Spark, Flink and Ray

Every distributed processing engine answers two questions: where do intermediate results live, and where do you restart from when something fails? MapReduce writes every step to disk and reruns failed tasks. Presto streams everything through memory, which is fast, but one lost worker restarts the whole query. Spark recomputes lost partitions from lineage. Flink takes snapshots of state that never stops growing. Ray puts CPU and GPU work in one pipeline. The nine engines below are in the order they appeared, and each one changes the previous one's answer.

For engineers preparing for staff-level data infrastructure or backend interviews who have used Spark or Flink but can't yet explain why they are built the way they are.

Timeline

From MapReduce to DuckDB: what each step changed

  1. Origin

    Built by Matei Zaharia and others at UC Berkeley's AMPLab. HotCloud paper in 2010, the RDD paper at NSDI 2012. An Apache top-level project in 2014. As of November 2026 the latest feature release is 4.3.0 (October 30, 2026)

    The problem it set out to solve

    On iterative algorithms and multi-step jobs, MapReduce spent its time reading and writing HDFS. Spark wanted intermediate data to stay in memory without relying on replication for fault tolerance, as distributed shared memory does.
    One Spark job: its parts
    • DriverSparkSession, DAG scheduler, task scheduler
    • Job (one per action)
      • Stage 0Read files → filter → map, chained in one task
      • Shuffle filesOn each executor's local disk, sorted by partition
      • Stage 1Fetch shuffle data → aggregate → write output
    • Executors × NRun tasks, cache partitions, keep shuffle files

    How it works

    • An RDD is a read-only, partitioned dataset that records how it was computed from other RDDs (its lineage). If a partition is lost, only that partition is recomputed from the lineage.
    • Transformations are lazy and only run when an action (collect, writing a file) is called. The driver hands the whole computation to the DAG scheduler.
    • Stages are cut at wide dependencies, where a shuffle is needed. Narrow dependencies inside a stage (map, filter) run back to back in one task without touching disk.
    • In a shuffle, upstream tasks sort their output by partition and write it to local disk, and downstream tasks fetch it. So if a stage after a shuffle fails, the upstream stage need not rerun as long as its shuffle files survive.
    • DataFrames and Spark SQL, added later, go through the Catalyst optimizer and execute with whole-stage code generation (2.0). Since 3.0, AQE adjusts the plan using the real data sizes seen after each shuffle.

    Submitting a job

    1. Write the logic with DataFrames or SQL, package it and run spark-submit, or run it directly in a notebook.
    2. The driver starts and requests executors from the cluster manager (YARN, Kubernetes).

    One execution, step by step

    1. An action triggers a job.
    2. Catalyst analyzes and optimizes the logical plan and produces a physical plan.
    3. The DAG scheduler cuts stages at shuffles and submits them in dependency order.
    4. Each stage becomes as many tasks as it has partitions, sent to executors.
    5. Upstream stages write shuffle files to local disk and downstream stages fetch them.
    6. After each shuffle, AQE adjusts the rest of the plan using real data sizes.
    7. The last stage writes the output and commits it.

    Strengths

    • A job can be a DAG of any number of steps, with narrow dependencies chained together and nothing written to disk.
    • Lineage-based fault tolerance: only lost partitions are recomputed, with no replication of intermediate results.
    • One API for SQL, batch, streaming and machine learning, and the largest ecosystem.
    • The Catalyst optimizer and AQE give DataFrame code good plans too.

    Weaknesses

    • Shuffles still go to disk and over the network, and that is where most of a large job's time goes.
    • It runs on the JVM, with real garbage collection and object overhead; Tungsten and code generation reduce some of it.
    • Streaming (Structured Streaming) is micro-batch by default, with latency from hundreds of milliseconds to seconds. Version 4.1 added a real-time mode that reaches milliseconds; from 4.3 it supports a first set of stateful operators such as deduplication and aggregation, but not yet stream-stream joins or session windows.
    • Many knobs: partition counts, executor memory and broadcast thresholds can decide whether a job succeeds.

    Where it is used, and where it still is

    Large-scale ETL, batch processing on data lakes and data preparation for machine learning; it is the most widely used batch engine today. Databricks, EMR and Dataproc are built around it.

    What replaced it, and why

    Not replaced. What is changing: its execution layer is being swapped for native engines (Photon, Gluten + Velox), streaming is chasing lower latency (real-time mode in 4.1), and client and server are being separated (Spark Connect).

    In an interview, one sentence

    A DAG engine with lineage-based fault tolerance: intermediate results in memory where possible, recomputed if lost, shuffles on disk.

    In an interview, two minutes

    Spark targeted MapReduce's habit of reading and writing HDFS over and over in multi-step jobs and iterative computation. Its core is the RDD's lineage: every partition knows how it was computed and can be recomputed if lost, so one in-memory copy of intermediate results is enough, with no replication. A job is a DAG cut into stages at shuffles, and work inside a stage runs back to back. Shuffle files go to local disk, which lets a failure rerun only part of the job, and that is the key difference from Presto. Catalyst, code generation and AQE later turned it from a faster MapReduce into a SQL engine with an optimizer. Its weaknesses now are JVM execution efficiency and the shuffle, which is exactly what native execution layers and remote shuffle services are addressing.

    Worth adding

    Spark's key idea is not "in memory" but lineage: deterministic recomputation instead of replication for fault tolerance, which is why one in-memory copy of intermediate data is enough.

Eight concepts first

Words that keep coming back

Partition
A slice of the data and the smallest unit of parallelism: one task processes one partition.
Too few partitions and the cluster sits idle; too many and scheduling and small files cost more than the work.
Narrow and wide dependencies
When each upstream partition is used by at most one downstream partition, the dependency is narrow (map, filter, union). When one upstream partition feeds many downstream partitions, it is wide (groupBy, a join that needs repartitioning).
Narrow dependencies can run back to back in one task; wide ones need a shuffle, which is where Spark cuts stages. A join whose inputs are already partitioned on the same key into the same number of partitions is narrow and needs no shuffle.
Shuffle
Redistributing data across machines by key so that all data for one key reaches one task.
Data crosses machines, and batch engines also sort it and write it to disk first. It is the most expensive step in almost any distributed job.
Materialized vs pipelined
Data between stages can be written out in full before the next stage reads it (MapReduce, Spark's shuffle) or streamed while it is computed (Presto, Flink streaming jobs).
Materializing is slower but lets you rerun only part of the work on failure; pipelining is faster but often means starting over.
Lineage and checkpoints
Lineage records how data was computed, so it can be recomputed if lost. A checkpoint saves a snapshot of state to restore from after a failure.
A batch job's input is still there, so recomputing works. A streaming job's state has accumulated since the job started, and the input that produced it is long gone, so only a snapshot will do.
Vectorization and code generation
Vectorization calls a precompiled function once per batch of column values. Code generation writes, for each query, a piece of code that fuses several operators together.
Both cut per-row overhead. Spark uses code generation; Photon, Velox and DuckDB use vectorization.
Event time and watermarks
Event time is when something happened, not when it reached the engine. A watermark is the engine's estimate that data from before some time has all arrived.
Data a phone uploads after an hour offline belongs in the windows of an hour ago. The watermark decides how long to wait: too long and latency suffers, too short and data is dropped.
Data skew
A few keys have far more data than the rest, so the tasks that get them run much longer.
A stage waits for its slowest task. More machines won't help; the hot keys have to be split.

In depth · 1

One Spark SQL query, from code to tasks

Take total spend per user since November: read the orders table, filter by date, sum by user_id and write the result.

  1. 1

    Writing the code: nothing has happened yet

    spark.read.parquet("orders").filter(col("dt") >= "2026-11-01").groupBy("user_id").agg(sum("amount")).write.parquet(...). Every step before write only builds a logical plan. write is an action, and that is when the job is submitted.

  2. 2

    Catalyst: analysis and optimization

    First it checks the catalog that the table and columns exist and the types line up. Then it applies rules: push the filter down into the file scan (Parquet can skip row groups using their min/max), read only user_id, amount and dt (column pruning), and if dt is a partition column, read only the matching directories.

  3. 3

    Physical plan: the aggregation splits in two

    groupBy becomes a partial aggregate and a final aggregate, with an exchange (shuffle) on user_id in between. Each task first sums amounts per user locally and then shuffles, so far less data moves. This is the same thing as MapReduce's combiner.

  4. 4

    Cutting stages and creating tasks

    The plan is cut into two stages at the exchange. Stage 0 has as many tasks as input splits; stage 1 has as many as shuffle partitions (spark.sql.shuffle.partitions, 200 by default). The scan, filter and partial aggregate within a stage are fused into one function by whole-stage codegen.

  5. 5

    Stage 0 finishes and writes shuffle files

    Each task divides its partial aggregates into 200 parts by the hash of user_id, sorts them, and writes one data file and one index file to local disk. Stage 1 starts only when every stage 0 task is done.

  6. 6

    AQE looks at real sizes and changes the plan

    With shuffle statistics in hand, AQE can merge many small partitions into a few tasks, split a partition that is many times the median size in a join, and turn a sort-merge join into a broadcast join when one side turns out to be small.

  7. 7

    Stage 1: fetch, merge, write

    Each task fetches its part from the shuffle files of every upstream task, runs the final aggregate and writes Parquet. Output goes through a commit protocol: tasks write to a temporary location and the job commits only on success, so a retried task never leaves half a result behind.

In depth · 2

Why shuffle is the most expensive step in a distributed job

When a distributed job is slow, the shuffle is often why. That holds whichever engine you use, and so do the fixes.

  1. 1

    Why it's expensive: M × R

    With M upstream tasks and R downstream partitions there are M × R blocks to move. Ten thousand maps times ten thousand reduces is a hundred million blocks, perhaps a few kilobytes each, and downstream reads turn into a flood of small random IOs.

  2. 2

    First: move less

    Combine before the shuffle wherever possible (combiners, partial aggregates). If one side of a join is small enough, broadcast it to every executor so the other side doesn't shuffle at all. Tables bucketed on the join key can skip the shuffle when both sides are bucketed the same way.

  3. 3

    Second: deal with skew

    When one key holds most of the data, add a random suffix (salting) to spread it over several tasks and aggregate in two rounds: first by key plus suffix, then by key. AQE in Spark 3 can split oversized partitions in a sort-merge join automatically.

  4. 4

    Third: turn small blocks into big ones

    LinkedIn's Magnet (VLDB 2020, merged into Spark 3.2) has map tasks push data to a remote shuffle service that merges it into large blocks per partition, so downstream reads become sequential. The Magnet paper reports nearly 30% shorter end-to-end runtimes for LinkedIn's production jobs. Push-based shuffle in Spark 3.2 works only on YARN.

  5. 5

    Fourth: take shuffle off the compute nodes

    Shuffle files live on the node that ran the executor. If the node goes (a spot instance reclaimed, a machine failure), the files go with it, downstream tasks can't fetch them, and upstream work has to rerun. Under dynamic allocation Spark keeps the files with an external shuffle service or shuffle tracking, but they still sit on compute nodes. A remote shuffle service (Apache Celeborn, a top-level project since 2024) keeps shuffle data on a separate cluster so compute nodes can be released at any time.

In depth · 3

What Flink's exactly-once actually guarantees

The follow-up interviewers ask most about stream processing. Get barriers, recovery and sinks straight and you won't be caught out.

  1. 1

    Three guarantees, kept apart

    At-most-once: on failure, data is lost. At-least-once: on failure, data is resent and may be duplicated (Storm's default). Exactly-once: the effect on state and output is as if each record were processed exactly once. Note that the last one is about the effect; after a failure, data is still processed again.

  2. 2

    Barriers cut the stream into segments

    The checkpoint coordinator tells every source. Each source records its current read position (the offset of each Kafka partition, say) and inserts barrier n into the stream. Data before the barrier belongs to checkpoint n, data after it to the next one.

  3. 3

    Alignment: wait for the barrier on every input

    When an operator has several inputs, the input whose barrier arrives first pauses until barrier n has arrived on all the others. Then the operator snapshots its state and sends the barrier downstream; uploading the snapshot to durable storage happens asynchronously in the background. The snapshot reflects exactly the data before the barrier. The method is based on the Chandy-Lamport distributed snapshot algorithm and was described by the Flink team in a 2015 paper.

  4. 4

    Unaligned: the trade-off under backpressure

    When downstream is slow and buffers are full, a barrier can queue for a long time and the checkpoint never finishes. An unaligned checkpoint lets the barrier overtake the queued data and stores that in-flight data in the snapshot too. Checkpoints finish faster, at the cost of larger snapshots.

  5. 5

    Recovery: state and read positions roll back together

    After a failure, every operator loads its state from checkpoint n and each source goes back to the offset recorded in checkpoint n. Data processed after checkpoint n is processed again, but because state rolled back too, nothing is counted twice.

  6. 6

    End to end: the sink has to cooperate

    If a sink has already written results to an external system between checkpoints, they are written again after recovery. There are two ways out. One is two-phase commit: write into a transaction and commit it only after the checkpoint completes (this is how Kafka transactions are used), at the cost that downstream readers see data no sooner than the checkpoint completes. The other is idempotent writes: overwrite by primary key, so writing twice does no harm.

Side by side

All nine engines in one table

EngineExecution modelData between stagesRecovery from failureTypical latencyBest for
MapReduceTwo steps: map and reduceMap output on local disk; HDFS between jobsRerun failed tasksMinutesExisting Hadoop batch jobs
HiveSQL compiled into MapReduce (later Tez) jobsAs MapReduce; Tez cut down HDFS writes in betweenRerun failed tasksMinutesOld Hadoop warehouses; the metastore is still in use
SparkDAG, stages cut at shufflesShuffle files on local diskRecompute lost partitions from lineageSeconds to hours; streaming from ~100 ms by default, milliseconds in real-time modeLarge ETL, ML data preparation, teams that need both batch and streaming
Presto / TrinoMPP, long-running workers, pipelinedIn-memory buffers, straight over the networkBy default rerun the whole query; optionally store inter-stage data externallySub-second to minutesInteractive queries, BI, queries across sources
StormRecord-at-a-time topologyStraight over the networkRe-emit from the source; at-least-onceMillisecondsExisting older systems; rarely chosen for new projects
FlinkStateful streaming dataflow; batch as bounded streamsNetwork buffers, pipelinedRestore state from a checkpoint and rewind the sourcesMilliseconds to secondsStateful real-time computation, CDC, real-time features
RayGeneral tasks and actors scheduled by CPU / GPU resources; Ray Data streamsShared-memory object store, spilled to disk when fullThe owner recomputes lost objects from lineage; actor state is yours to saveMillisecond scheduling; jobs take seconds to hoursMixed CPU and GPU AI data processing, batch inference, training and RL
Native execution layersColumnar, vectorized execution embedded in Spark, Presto and othersUp to the host engineUp to the host engineAs the host engine, with less CPULarge-scale SQL where CPU is the bottleneck
DuckDBSingle process, vectorized, multi-coreProcess memory, spilled to local disk when shortNo distributed fault tolerance; rerun the queryMilliseconds to minutesAnalysis that fits on one machine, local development, embedded analytics

Where the industry is heading · checked November 30, 2026

Where things have been going

  • Native code replaces the JVM engines' execution layer

    Databricks uses Photon; in open source, Gluten hands Spark's execution to Velox, and Gluten became an Apache top-level project in February 2026. PrestoDB also offers a C++ worker built on Velox that can replace its Java worker. SQL and scheduling stay where they are, and the execution library has become a shared component.

  • Single-node engines take a share of "big data"

    DuckDB 2.0 (October 2026, LTS) added asynchronous IO for reading Parquet and CSV, which speeds up queries on object storage. Polars and DataFusion are moving the same way. More teams ask first whether one machine is enough, and reach for a cluster only when it isn't.

  • Streaming and batch are converging

    Spark 4.1's real-time mode (December 2025) brings Structured Streaming down to milliseconds, and 4.3 (October 2026) began supporting stateful queries in it; Flink 2.3 (June 2026) kept developing materialized tables, so one table can be updated continuously or refreshed on demand. Both sides want one API for both cases.

  • AI data processing is now a workload of its own

    Data processing before training and batch inference has to use CPUs and GPUs together, on unstructured data such as images, audio and video. Ray Data has taken this ground with streaming execution and GPU actor pools, and Ray joined the PyTorch Foundation in October 2025, alongside PyTorch and vLLM. Architectures that use Spark and Ray together (Spark for structured cleaning, Ray for the GPU stage) are increasingly common.

  • Separating storage from compute now covers state and shuffle

    ForSt, the state backend added in Flink 2.0 (March 2025), keeps state in remote storage with only a local cache, which speeds up checkpoints and rescaling. Remote shuffle services such as Celeborn take shuffle data out of executors so compute nodes can be released at any time. The goal in both cases is compute nodes that hold no state and can come and go.

Common misconceptions

Eight things that are easy to get wrong in an interview

  • Misconception: Spark is fast because all the data is in memory.

    Shuffle files are always written to disk, and caches and aggregations spill when memory runs out. Spark beats MapReduce mainly because multi-step jobs no longer write HDFS at every step, narrow dependencies run back to back in one task, and the optimizer and code generation do their work.

  • Misconception: Exactly-once means each message is processed only once.

    After a failure, data is always processed again. Exactly-once is about the effect: state rolls back to a consistent snapshot and is replayed, so the result is as if each record were processed once. Writing to external systems also needs transactions or idempotent writes.

  • Misconception: Spark Structured Streaming can only do micro-batches, so latency is always seconds.

    Micro-batch is the default, but Spark 4.1 added a real-time mode that reaches millisecond latency, and from 4.3 it supports a first set of stateful operators such as deduplication and aggregation. Stream-stream joins, session windows and some others are not yet supported, so those cases still often go to Flink. (There has also been an experimental continuous processing mode since 2.3.)

  • Misconception: If a job is slow, add machines.

    With skew, a hot key still sits in one task, so more machines don't help. With a fixed number of shuffle partitions, more machines don't make each task smaller either. Look first at the spread of task times and shuffle sizes in the Spark UI.

  • Misconception: MapReduce is dead, so there's no need to understand it.

    As a programming interface it is rarely used now, but partitioning by key, the shuffle and rerunning deterministic tasks survive unchanged in Spark, Flink and every MPP engine. When an interviewer asks about the shuffle, the answer starts with MapReduce.

  • Misconception: Presto / Trino is a database that stores data.

    It is only a query engine and stores nothing. The data is in HDFS, S3, relational databases or Kafka, read through connectors, and table definitions come from an external catalog.

  • Misconception: Ray is a faster Spark and can replace it directly.

    Ray Core is a general distributed runtime, and Ray Data is a data processing library on top of it. There is no SQL optimizer, and Spark and Trino remain more mature for large joins and complex aggregations. Ray's strength is pipelines that mix CPUs and GPUs and keep models resident.

  • Misconception: A watermark guarantees no earlier data will arrive.

    A watermark is only the engine's estimate. Earlier data can still arrive; it is then dropped, used to update windows already emitted (within allowed lateness), or sent to a side output to be handled separately.

Staff-level interview questions

Answer first, then open

▶A Spark job's 199 tasks finish in two minutes and the last one runs for an hour. How do you investigate, and what do you change?
  • Start on the stage page of the Spark UI: compare that task's shuffle read size and input rows with the median. Much larger means skew. About the same size but slow points to the machine (GC, disk), and speculative execution can help there.
  • Once it's skew, find the hot keys. Common culprits are null, empty strings, default values and one very large customer. Nulls and defaults can often be filtered out or handled separately.
  • Skew in an aggregation: add a random suffix and aggregate in two rounds. Skew in a join: turn on AQE's skew join handling, or pull the hot keys out into a broadcast join and send the rest through the normal join.
  • More machines won't help, because a single key still lands in a single task.
  • It depends on: whether the skew is in a join or an aggregation, how many hot keys there are, and whether the other side is small enough to broadcast.
▶The team needs a daily revenue table, and late data can arrive up to three days late. Spark batch or Flink streaming?
  • Batch: every day, recompute the partitions for the last three days and overwrite them whole. Simple and idempotent, and a failure just means rerunning; the costs are that data updates once a day and the same data is computed three times.
  • Streaming: window by event time with three days of allowed lateness, so late data updates its window, and downstream has to accept the same window being updated several times (upserts). Lower latency, but three days of state and heavier operations.
  • If downstream is a report people read each morning, batch fits better. Streaming is worth it for a live dashboard or for risk control.
  • Many teams do both: streaming gives a fast approximate answer and batch produces the correct version each day that replaces it. You have to say which one wins when they disagree.
  • It depends on: how fresh downstream needs the data, whether results may change after publication, and whether the team can operate a stateful streaming job.
▶When would you recommend DuckDB over Spark?
  • When the data is tens of gigabytes to a terabyte or two compressed, fits a large-memory machine, and the queries are mostly scans and aggregations. DuckDB skips cluster startup, scheduling and network shuffles, and is often faster and cheaper.
  • For local development and tests: the same SQL runs against Parquet files on a laptop without waiting for a cluster.
  • Reasons to stay on Spark: the data or intermediate results outgrow one machine; several jobs must write the same table concurrently; there is already a mature Spark platform with access control and monitoring; failures are expensive and you need to rerun only part of the work.
  • It depends on: how large the biggest intermediate result is, not just the input, and on the platform the team already has.
▶How do you get end-to-end exactly-once with Flink reading from Kafka and writing back to Kafka? What does it cost?
  • Source: the Kafka source puts its offsets into the checkpoint and resumes from them on recovery.
  • State: enable checkpointing in EXACTLY_ONCE mode and store snapshots on S3 or HDFS. The choice of state backend has nothing to do with exactly-once; pick RocksDB when state is large.
  • Sink: set DeliveryGuarantee.EXACTLY_ONCE and a transactionalIdPrefix on the Kafka sink, which then uses transactions (two-phase commit) and commits only after a checkpoint completes. Downstream consumers must set isolation.level=read_committed, or they will read uncommitted data that may later be rolled back.
  • Cost: data becomes visible downstream only when the next checkpoint completes, up to one checkpoint interval plus the checkpoint's own duration later. Kafka transactions have a timeout that must exceed the checkpoint interval plus any recovery time, or the broker aborts the transaction and data is lost.
  • Alternative: if downstream is a database that upserts by primary key, at-least-once with idempotent writes is simpler and has lower latency.
  • It depends on: whether downstream can deduplicate, how much latency it tolerates, and whether the Kafka and downstream teams can support the transaction settings.
▶Many companies run Trino for interactive queries and Spark for ETL. Why both? Could you keep only one?
  • Trino's long-running workers and pipelined execution return small queries in seconds, which suits BI and ad hoc analysis; but by default there is no fault tolerance mid-query, so losing one machine during a multi-hour ETL means starting over.
  • Spark's on-disk shuffle and lineage let long jobs rerun only part of their work, which suits large ETL; but each job starts executors, so interactive latency trails Trino.
  • Keeping one is possible: Trino with fault-tolerant execution can run ETL, and Spark with a long-running cluster and caching can serve interactive queries. The price is worse performance and cost on the side each is weaker at.
  • Running both only works if they share one table format and catalog (Iceberg, a Hive metastore); otherwise the same table ends up with two definitions.
  • It depends on: the mix of the two workloads, how many systems the team can maintain, and whether slow queries or failed jobs hurt the business more.
▶A Spark job runs on spot instances and keeps rerunning large upstream stages when nodes are reclaimed. What do you change?
  • Cause: shuffle files live on the executor's local disk. When the node goes, so do the files, downstream can't fetch them, and every upstream task whose output was lost reruns.
  • Option one: enable decommissioning, so shuffle data and cached blocks are migrated to other executors before the node goes (if there's time).
  • Option two: use a remote shuffle service (Celeborn or similar), so shuffle data is not on compute nodes and they can disappear at any time. The cost is another cluster to operate and an extra network hop.
  • Option three: put the driver and shuffle-heavy stages on on-demand instances and only stateless, cheap-to-rerun work on spot.
  • It depends on: how often spot capacity is reclaimed, how much data is shuffled, and whether the team can operate an extra shuffle cluster.
▶You need embeddings for 500 million images: read from S3, decode and resize, run a GPU model, write back. Spark or Ray Data?
  • The key in this kind of job is keeping the GPUs busy. CPU decoding and GPU inference run at different speeds, so each side has to scale on its own, with a buffer in between.
  • Spark: since 3.1, stage-level scheduling can request GPUs for just the GPU stage, and since 3.4 predict_batch_udf caches the model in each Python worker. But a stage boundary sits between the CPU and GPU steps: either they share one stage (and the GPU idles while decoding), or they become two stages and the first must finish and materialize its output before the second starts.
  • Ray Data: decoding runs as CPU tasks and inference as a pool of GPU actors with the model resident. There is no stage boundary between them: blocks stream across, each side scales as it needs, and backpressure keeps the CPU side from exhausting memory. GPU utilization is usually higher.
  • Conversely, if the job is mostly large joins, deduplication and per-user aggregation, Spark's optimizer and shuffle are more mature. A common split is Spark for structured cleaning and Ray for the GPU stage.
  • It depends on: the GPU step's share of total cost, whether there are large shuffles, the platform the team already has, and how expensive the model is to load.
▶Should you add a native execution layer such as Gluten + Velox to an existing Spark platform? How would you evaluate it?
  • Start with where the bottleneck is. If jobs are stuck on shuffle, IO or skew, a new execution layer won't help; CPU-bound scans, filters, aggregations and joins gain the most.
  • Test with real jobs, not TPC-DS, and count how many operators fall back to the JVM. With many fallbacks, row/column conversion can cancel out the gain.
  • Compare results one by one. Differences in function semantics (overflow, nulls, time zones, float formatting) produce silently different answers, so run the same jobs in a shadow environment and compare outputs.
  • Weigh the operational cost: when something breaks, someone on the team has to debug across JNI and C++.
  • It depends on: the share of CPU-heavy operators in your jobs, the share that can be offloaded, and how strictly results must match.

Hands-on exercise · about 5 minutes

A mini MapReduce in fifty lines: shuffle, combiners and skew

It uses only the Python standard library (3.8 or later), so there is nothing to install. Save the code below as mini_mapreduce.py. It hands four pieces of text to four mappers, sends each word to one of four reducers to be counted, runs once without a combiner and once with one, and prints how many records each reducer receives.

import zlib
from collections import Counter, defaultdict

# Four input splits. "the" is far more common than any other word, as in real text.
SPLITS = [
    "the cat sat on the mat the end",
    "the dog ate the cat food",
    "a cat and a dog and the bird",
    "the the the the the the the the",
]
REDUCERS = 4


def partition(key):
    # Same key -> same reducer, on every machine. (Python's hash() of a str
    # changes per process, so use a stable hash, as a real engine must.)
    return zlib.crc32(key.encode()) % REDUCERS


def map_split(text, combine):
    pairs = [(word, 1) for word in text.split()]
    if combine:  # combiner: sum inside the mapper before anything is sent
        pairs = list(Counter(word for word, _ in pairs).items())
    return pairs


def run(combine):
    inbox = defaultdict(list)  # reducer -> records it receives over the "network"
    for text in SPLITS:
        for key, value in map_split(text, combine):
            inbox[partition(key)].append((key, value))
    shuffled = sum(len(records) for records in inbox.values())
    print(f"combiner={combine}: {shuffled} records shuffled")
    result = {}
    for r in range(REDUCERS):
        groups = defaultdict(int)
        for key, value in sorted(inbox[r]):  # sort, then group by key
            groups[key] += value
        result.update(groups)
        print(f"  reducer {r}: {len(inbox[r]):2} records in, keys {sorted(groups)}")
    return result


counts = run(combine=False)
assert counts == run(combine=True)
print("top 3:", Counter(counts).most_common(3))

Run it:

python3 mini_mapreduce.py

The real output:

combiner=False: 30 records shuffled
  reducer 0:  6 records in, keys ['ate', 'cat', 'on', 'sat']
  reducer 1:  5 records in, keys ['and', 'dog', 'end']
  reducer 2: 16 records in, keys ['bird', 'mat', 'the']
  reducer 3:  3 records in, keys ['a', 'food']
combiner=True: 18 records shuffled
  reducer 0:  6 records in, keys ['ate', 'cat', 'on', 'sat']
  reducer 1:  4 records in, keys ['and', 'dog', 'end']
  reducer 2:  6 records in, keys ['bird', 'mat', 'the']
  reducer 3:  2 records in, keys ['a', 'food']
top 3: [('the', 14), ('cat', 3), ('and', 2)]
  • Without a combiner, all 30 records go through the shuffle. Fourteen of them are "the", and they all go to reducer 2, which receives 16 records while the others get between 3 and 6. That is skew: one key can only go to one reducer.
  • With a combiner, each mapper first adds up each word locally, the shuffle drops from 30 records to 18, and reducer 2 receives only 6. Spark's partial aggregate does the same thing.
  • A combiner only works for operations that are both associative and commutative (sums, counts, maximums). Joins and medians can't be pre-merged like this; their skew has to be handled by splitting hot keys or broadcasting the small table.
  • The partition function uses crc32 rather than Python's hash(), because Python's string hash changes from process to process, and a real engine must compute the same partition number on every machine.
  • Try setting REDUCERS to 8, or adding more lines of "the" to SPLITS, and watch how the skew changes.

Cheat sheet

Ten minutes before the interview

The thread
Each generation changes two things: where intermediate results live (disk, memory, network pipes, a remote service) and where you restart after a failure (the task, lineage, a checkpoint, the whole query).
MapReduce
Map, shuffle, reduce; intermediate data on disk, HDFS between jobs; rerun tasks on failure.
Hive
SQL compiled to MapReduce; left us directory partitions and the metastore.
Spark
Lineage-based fault tolerance, DAG cut into stages at shuffles, shuffles on disk; Catalyst, AQE.
Presto / Trino
Long-running workers, pipelined, nothing on disk; fast, but by default a failure restarts the query.
Storm
Record at a time, the acker's XOR tracking, re-emit on timeout; at-least-once, no state.
Flink
Engine-managed state, barrier snapshots, event time and watermarks; end to end needs a transactional or idempotent sink.
Ray
Tasks, actors, a shared-memory object store, scheduled by CPU / GPU; Ray Data streams with backpressure; if the owner dies, the object is lost.
Native execution
Photon, Velox, DataFusion: columnar and vectorized, new execution layer under the same API; the hard parts are matching semantics and fallbacks.
DuckDB
An in-process, single-node columnar engine; size the largest intermediate result first, and if it fits on one machine, skip the cluster.
Shuffle fixes
Combine first (combiners, partial aggregates), broadcast when you can, split hot keys, merge small blocks (Magnet), use a remote shuffle service.
Ending an answer
It depends on: latency needs, data size (especially intermediate results), the cost of failure, state size, and what the team can operate.

Sources

Version numbers, release dates and project status were checked on November 30, 2026. They may have changed since. Performance figures reported by a vendor reflect that vendor's own tests.

DISCUSSION

Join the discussion

Share a thought or question. Comments publish immediately; add your email only if you would like reply notifications.

Be the first to start the conversation.